text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix problem on no-longer existing bands that are still as logged in session available
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: del session['bandId'] return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
Correct variable name is singular here
from app.actions.mslookup import proteinquant as lookups from app.drivers.mslookup import base class ProteinQuantLookupDriver(base.LookupDriver): """Creates lookup of protein tables that contain quant data""" lookuptype = 'prottable' def __init__(self, **kwargs): super().__init__(**kwargs) self.poolnames = [x.replace('"', '') for x in kwargs.get('setnames')] # FIXME need check to see same poolnames correlate with self.fn len self.quantcolpattern = kwargs.get('quantcolpattern', None) self.psmnrcolpattern = kwargs.get('psmnrcolpattern', None) self.precursorquantcolpattern = kwargs.get('precursorquantcolpattern', None) self.proteincol = kwargs.get('protcol', None) - 1 self.probcolpattern = kwargs.get('probcolpattern', None) self.fdrcolpattern = kwargs.get('fdrcolpattern', None) self.pepcolpattern = kwargs.get('pepcolpattern', None) def create_lookup(self): lookups.create_proteinquant_lookup(self.fn, self.lookup, self.poolnames, self.proteincol, self.precursorquantcolpattern, self.quantcolpattern, self.psmnrcolpattern, self.probcolpattern, self.fdrcolpattern, self.pepcolpattern)
from app.actions.mslookup import proteinquant as lookups from app.drivers.mslookup import base class ProteinQuantLookupDriver(base.LookupDriver): """Creates lookup of protein tables that contain quant data""" lookuptype = 'prottable' def __init__(self, **kwargs): super().__init__(**kwargs) self.poolnames = [x.replace('"', '') for x in kwargs.get('setnames')] # FIXME need check to see same poolnames correlate with self.fn len self.quantcolpattern = kwargs.get('quantcolpattern', None) self.psmnrcolpattern = kwargs.get('psmnrcolpattern', None) self.precursorquantcolpattern = kwargs.get('precursorquantcolpattern', None) self.proteincols = kwargs.get('protcol', None) - 1 self.probcolpattern = kwargs.get('probcolpattern', None) self.fdrcolpattern = kwargs.get('fdrcolpattern', None) self.pepcolpattern = kwargs.get('pepcolpattern', None) def create_lookup(self): lookups.create_proteinquant_lookup(self.fn, self.lookup, self.poolnames, self.proteincols, self.precursorquantcolpattern, self.quantcolpattern, self.psmnrcolpattern, self.probcolpattern, self.fdrcolpattern, self.pepcolpattern)
Modify request to add necessary header
'use strict'; angular.module('scratchApp') .controller('ContractCtrl', function ($scope, $http, $location) { var serversPublicKey, wallet, paymentTx, refundTx, signedTx; $scope.generate = function () { getServersPublicKey($scope.walet_publicKey); signTransactionAtServer(); } function getServersPublicKey(clientsPublicKey) { var req = { method: 'POST', url: 'http://0.0.0.0:3000/wallet/create', headers: { 'Content-Type': 'application/json' }, data: { userPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01" } }; $http(req).success(function (data, status, headers, config) { console.log("Server responded with key: " + data); serversPublicKey = data; createTransactions($scope.wallet_amount, $scope.wallet_duration); }).error(function (data, status, headers, config) { $location.path('/'); }); serversPublicKey = "ServersPublicKey"; } function createTransactions(amount, duration) { // generate wallet // create payment transaction // create refund transaction } function signTransactionAtServer() { signedTx = "signed transaction"; } });
'use strict'; angular.module('scratchApp') .controller('ContractCtrl', function ($scope, $http, $location) { var serversPublicKey, wallet, paymentTx, refundTx, signedTx; $scope.generate = function () { getServersPublicKey($scope.walet_publicKey); signTransactionAtServer(); } function getServersPublicKey(clientsPublicKey) { $http.post("http://0.0.0.0:3000/wallet/create", {clientsPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01"}).success(function (data, status, headers, config) { console.log("Server responded with key: " + data); serversPublicKey = data; createTransactions($scope.wallet_amount, $scope.wallet_duration); }). error(function (data, status, headers, config) { alert("Server returned an error: " + status + " " + data); $location.path('/'); }); serversPublicKey = "ServersPublicKey"; } function createTransactions(amount, duration) { // generate wallet // create payment transaction // create refund transaction } function signTransactionAtServer() { signedTx = "signed transaction"; } });
Add some logs to scheduling.
package com.novoda.downloadmanager; import android.content.Context; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.novoda.notils.logger.simple.Log; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w("Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); Log.v("Scheduling Network Recovery."); } }
package com.novoda.downloadmanager; import android.content.Context; import android.util.Log; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w(getClass().getSimpleName(), "Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); } }
Check for null and empty body before trying to map a json string to an object. Signed-off-by: Clement Escoffier <[email protected]>
package org.wisdom.content.bodyparsers; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Instantiate; import org.apache.felix.ipojo.annotations.Provides; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wisdom.api.content.BodyParser; import org.wisdom.api.http.Context; import org.wisdom.api.http.MimeTypes; import org.wisdom.content.json.Json; import java.io.IOException; @Component @Provides @Instantiate public class BodyParserJson implements BodyParser { private final Logger logger = LoggerFactory.getLogger(BodyParserJson.class); public <T> T invoke(Context context, Class<T> classOfT) { T t = null; try { final String content = context.body(); if (content == null || content.length() == 0) { return null; } t = Json.mapper().readValue(content, classOfT); } catch (IOException e) { logger.error("Error parsing incoming Json", e); } return t; } @Override public <T> T invoke(byte[] bytes, Class<T> classOfT) { T t = null; try { t = Json.mapper().readValue(bytes, classOfT); } catch (IOException e) { logger.error("Error parsing incoming Json", e); } return t; } public String getContentType() { return MimeTypes.JSON; } }
package org.wisdom.content.bodyparsers; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Instantiate; import org.apache.felix.ipojo.annotations.Provides; import org.wisdom.api.content.BodyParser; import org.wisdom.api.http.Context; import org.wisdom.api.http.MimeTypes; import org.wisdom.content.json.Json; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; @Component @Provides @Instantiate public class BodyParserJson implements BodyParser { private final Logger logger = LoggerFactory.getLogger(BodyParserJson.class); public <T> T invoke(Context context, Class<T> classOfT) { T t = null; try { t = Json.mapper().readValue(context.getReader(), classOfT); } catch (IOException e) { logger.error("Error parsing incoming Json", e); } return t; } @Override public <T> T invoke(byte[] bytes, Class<T> classOfT) { T t = null; try { t = Json.mapper().readValue(bytes, classOfT); } catch (IOException e) { logger.error("Error parsing incoming Json", e); } return t; } public String getContentType() { return MimeTypes.JSON; } }
Fix API description for Subscribe Controller
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Create subscriber") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Delete subscriber") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
Remove support for python 2.x
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs from setuptools import setup, find_packages from axes import get_version setup( name='django-axes', version=get_version(), description="Keep track of failed login attempts in Django-powered sites.", long_description=( codecs.open("README.rst", encoding='utf-8').read() + '\n' + codecs.open("CHANGES.txt", encoding='utf-8').read()), keywords='authentication django pci security'.split(), author='Josh VanderLinden, Philip Neustrom, Michael Blume, Camilo Nova', author_email='[email protected]', maintainer='Alex Clark', maintainer_email='[email protected]', url='https://github.com/django-pci/django-axes', license='MIT', package_dir={'axes': 'axes'}, install_requires=['pytz', 'django-appconf'], include_package_data=True, packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Log Analysis', 'Topic :: Security', 'Topic :: System :: Logging', ], zip_safe=False, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs from setuptools import setup, find_packages from axes import get_version setup( name='django-axes', version=get_version(), description="Keep track of failed login attempts in Django-powered sites.", long_description=( codecs.open("README.rst", encoding='utf-8').read() + '\n' + codecs.open("CHANGES.txt", encoding='utf-8').read()), keywords='authentication django pci security'.split(), author='Josh VanderLinden, Philip Neustrom, Michael Blume, Camilo Nova', author_email='[email protected]', maintainer='Alex Clark', maintainer_email='[email protected]', url='https://github.com/django-pci/django-axes', license='MIT', package_dir={'axes': 'axes'}, install_requires=['pytz', 'django-appconf'], include_package_data=True, packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Log Analysis', 'Topic :: Security', 'Topic :: System :: Logging', ], zip_safe=False, )
Add retries to cppn param test
from __future__ import absolute_import, division, print_function import pytest import numpy as np import tensorflow as tf import logging from lucid.optvis.param.cppn import cppn log = logging.getLogger(__name__) @pytest.mark.slow def test_cppn_fits_xor(): with tf.Graph().as_default(), tf.Session() as sess: cppn_param = cppn(16, num_output_channels=1)[0] def xor_objective(a): return -( tf.square(a[0, 0]) + tf.square(a[-1, -1]) + tf.square(1.0 - a[-1, 0]) + tf.square(1.0 - a[0, -1]) ) loss_t = xor_objective(cppn_param) optimizer = tf.train.AdamOptimizer(0.01) objective = optimizer.minimize(loss_t) for try_i in range(3): tf.global_variables_initializer().run() # loss = loss_t.eval() for i in range(200): _, vis = sess.run([objective, cppn_param]) close_enough = ( vis[0, 0] > .99 and vis[-1, -1] > .99 and vis[-1, 0] < .01 and vis[0, -1] < .01 ) if close_enough: return assert False, "fitting XOR took more than 200 steps, failing test"
from __future__ import absolute_import, division, print_function import pytest import numpy as np import tensorflow as tf import logging from lucid.optvis.param.cppn import cppn log = logging.getLogger(__name__) @pytest.mark.slow def test_cppn_fits_xor(): with tf.Graph().as_default(), tf.Session() as sess: cppn_param = cppn(16, num_output_channels=1)[0] def xor_objective(a): return -( tf.square(a[0, 0]) + tf.square(a[-1, -1]) + tf.square(1.0 - a[-1, 0]) + tf.square(1.0 - a[0, -1]) ) loss_t = xor_objective(cppn_param) optimizer = tf.train.AdamOptimizer(0.01) objective = optimizer.minimize(loss_t) tf.global_variables_initializer().run() loss = loss_t.eval() for i in range(100): _, vis = sess.run([objective, cppn_param]) close_enough = ( vis[0, 0] > .99 and vis[-1, -1] > .99 and vis[-1, 0] < .01 and vis[0, -1] < .01 ) if close_enough: return assert False, "fitting XOR took more than 100 steps, failing test"
Fix incorrect indentation messing up PySide
import pkg_resources import glob import os def check(cmd, mf): name = 'PySide' m = mf.findNode(name) if m is None or m.filename is None: return None from PySide import QtCore plugin_dir = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.PluginsPath) resources = [pkg_resources.resource_filename('py2app', 'recipes/qt.conf')] for item in cmd.qt_plugins: if '/' not in item: item = item + '/*' if '*' in item: for path in glob.glob(os.path.join(plugin_dir, item)): resources.append((os.path.dirname('qt_plugins' + path[len(plugin_dir):]), [path])) else: resources.append((os.path.dirname(os.path.join('qt_plugins', item)), [os.path.join(plugin_dir, item)])) # PySide dumps some of its shared files # into /usr/lib, which is a system location # and those files are therefore not included # into the app bundle by default. from macholib.util import NOT_SYSTEM_FILES NOT_SYSTEM_FILES import sys for fn in os.listdir('/usr/lib'): add=False if fn.startswith('libpyside-python'): add=True elif fn.startswith('libshiboken-python'): add=True if add: NOT_SYSTEM_FILES.append(os.path.join('/usr/lib', fn)) return dict(resources=resources)
import pkg_resources import glob import os def check(cmd, mf): name = 'PySide' m = mf.findNode(name) if m is None or m.filename is None: return None from PySide import QtCore plugin_dir = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.PluginsPath) resources = [pkg_resources.resource_filename('py2app', 'recipes/qt.conf')] for item in cmd.qt_plugins: if '/' not in item: item = item + '/*' if '*' in item: for path in glob.glob(os.path.join(plugin_dir, item)): resources.append((os.path.dirname('qt_plugins' + path[len(plugin_dir):]), [path])) else: resources.append((os.path.dirname(os.path.join('qt_plugins', item)), [os.path.join(plugin_dir, item)])) # PySide dumps some of its shared files # into /usr/lib, which is a system location # and those files are therefore not included # into the app bundle by default. from macholib.util import NOT_SYSTEM_FILES NOT_SYSTEM_FILES import sys for fn in os.listdir('/usr/lib'): add=False if fn.startswith('libpyside-python'): add=True elif fn.startswith('libshiboken-python'): add=True if add: NOT_SYSTEM_FILES.append(os.path.join('/usr/lib', fn)) return dict(resources=resources)
Update sending request status message
$(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ $(updateField).html('Sending delete request...'); confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); }
$(document).ready(function(){ $('#deleteAccountSubmitLabel').on('click',function(){ var userID = $('#userIDValue').val(); var verifyCode = $('#verifyCodeValue').val(); var password = $('#passwordValue').val(); var updateField = '#deleteAccountSubmitMessage'; confirmDelete(userID,verifyCode,password,updateField); }); }); function confirmDelete(userID,verifyCode,password,updateField){ confirmDeleteAjax(userID,verifyCode,password,function(data){ switch (data){ case 'success': $(updateField).html('Account has been deleted. You now have a chance at a new life.'); logout(); break; case 'badVerifyCode': $(updateField).html('Unable to verify. Make sure that you followed the link from the delete request email that was sent to you.'); break; case 'badPassword': $(updateField).html('Incorrect password.'); break; case 'expired': $(updateField).html('Request has expired. Please create a new request if you still need to delete this account.'); break; } }); } function confirmDeleteAjax(userID,verifyCode,password,callback){ $.ajax({ 'url' : '/deleteAccountAction', 'type' : 'POST', 'data' : {'userID':userID,'verifyCode':verifyCode,'password':password}, 'success' : function(data){ callback(data); }, }); }
Update ConnectedSWFObject: raise KeyError if credentials are not set
# -*- coding:utf-8 -*- from boto.swf.layer1 import Layer1 AWS_CREDENTIALS = { #'aws_access_key_id': AWS_ACCESS_KEY_ID, #'aws_secret_access_key': AWS_SECRET_ACCESS_KEY, } def set_aws_credentials(aws_access_key_id, aws_secret_access_key): """Set default credentials.""" AWS_CREDENTIALS.update({ 'aws_access_key_id': aws_access_key_id, 'aws_secret_access_key': aws_secret_access_key, }) class ConnectedSWFObject(object): """Authenticated object interface Once inherited, implements the AWS authentication into the child, adding a `connection` property. """ def __init__(self, *args, **kwargs): for kwarg in kwargs: setattr(self, kwarg, kwargs[kwarg]) self.connection = Layer1( AWS_CREDENTIALS['aws_access_key_id'], AWS_CREDENTIALS['aws_secret_access_key'], ) def exists(self): """Checks if the connected swf object exists amazon-side""" raise NotImplemented def save(self): """Creates the connected swf object amazon side""" raise NotImplemented def deprecate(self): """Deprecates the connected swf object amazon side""" raise NotImplemented
# -*- coding:utf-8 -*- from boto.swf.layer1 import Layer1 AWS_CREDENTIALS = { 'aws_access_key_id': None, 'aws_secret_access_key': None } def set_aws_credentials(aws_access_key_id, aws_secret_access_key): """Set default credentials.""" AWS_CREDENTIALS.update({ 'aws_access_key_id': aws_access_key_id, 'aws_secret_access_key': aws_secret_access_key, }) class ConnectedSWFObject(object): """Authenticated object interface Once inherited, implements the AWS authentication into the child, adding a `connection` property. """ def __init__(self, *args, **kwargs): for credkey in ('aws_access_key_id', 'aws_secret_access_key'): if AWS_CREDENTIALS.get(credkey): setattr(self, credkey, AWS_CREDENTIALS[credkey]) for kwarg in kwargs: setattr(self, kwarg, kwargs[kwarg]) self.connection = Layer1( self.aws_access_key_id, self.aws_secret_access_key ) def exists(self): """Checks if the connected swf object exists amazon-side""" raise NotImplemented def save(self): """Creates the connected swf object amazon side""" raise NotImplemented def deprecate(self): """Deprecates the connected swf object amazon side""" raise NotImplemented
Set as FAILED when maxTries is set to 0
<?php namespace Imtigger\LaravelJobStatus\EventManagers; use Carbon\Carbon; use Illuminate\Queue\Events\JobExceptionOccurred; use Illuminate\Queue\Events\JobFailed; use Illuminate\Queue\Events\JobProcessed; use Illuminate\Queue\Events\JobProcessing; class DefaultEventManager extends EventManager { public function before(JobProcessing $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_EXECUTING, 'job_id' => $event->job->getJobId(), 'queue' => $event->job->getQueue(), 'started_at' => Carbon::now(), ]); } public function after(JobProcessed $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_FINISHED, 'finished_at' => Carbon::now(), ]); } public function failing(JobFailed $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_FAILED, 'finished_at' => Carbon::now(), ]); } public function exceptionOccurred(JobExceptionOccurred $event): void { $this->getUpdater()->update($event, [ 'status' => ($event->job->attempts() >= $event->job->maxTries()) ? $this->getEntity()::STATUS_FAILED : $this->getEntity()::STATUS_RETRYING, 'finished_at' => Carbon::now(), 'output' => ['message' => $event->exception->getMessage()], ]); } }
<?php namespace Imtigger\LaravelJobStatus\EventManagers; use Carbon\Carbon; use Illuminate\Queue\Events\JobExceptionOccurred; use Illuminate\Queue\Events\JobFailed; use Illuminate\Queue\Events\JobProcessed; use Illuminate\Queue\Events\JobProcessing; class DefaultEventManager extends EventManager { public function before(JobProcessing $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_EXECUTING, 'job_id' => $event->job->getJobId(), 'queue' => $event->job->getQueue(), 'started_at' => Carbon::now(), ]); } public function after(JobProcessed $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_FINISHED, 'finished_at' => Carbon::now(), ]); } public function failing(JobFailed $event): void { $this->getUpdater()->update($event, [ 'status' => $this->getEntity()::STATUS_FAILED, 'finished_at' => Carbon::now(), ]); } public function exceptionOccurred(JobExceptionOccurred $event): void { $this->getUpdater()->update($event, [ 'status' => ($event->job->attempts() === $event->job->maxTries()) ? $this->getEntity()::STATUS_FAILED : $this->getEntity()::STATUS_RETRYING, 'finished_at' => Carbon::now(), 'output' => ['message' => $event->exception->getMessage()], ]); } }
Move register outside of guard Even if we don't load the ``verbatim`` tag backbport, the module still needs to have a ``register`` variable. Addresses #660
""" Handlebars templates use constructs like: {{if condition}} print something{{/if}} This, of course, completely screws up Django templates, because Django thinks {{ and }} mean something. Wrap {% verbatim %} and {% endverbatim %} around those blocks of Handlebars templates and this will try its best to output the contents with no changes. """ from django import template register = template.Library() # For Django >= 1.5, use the default verbatim tag implementation if not hasattr(template.defaulttags, 'verbatim'): class VerbatimNode(template.Node): def __init__(self, text): self.text = text def render(self, context): return self.text @register.tag def verbatim(parser, token): text = [] while 1: token = parser.tokens.pop(0) if token.contents == 'endverbatim': break if token.token_type == template.TOKEN_VAR: text.append('{{') elif token.token_type == template.TOKEN_BLOCK: text.append('{%') text.append(token.contents) if token.token_type == template.TOKEN_VAR: text.append('}}') elif token.token_type == template.TOKEN_BLOCK: text.append('%}') return VerbatimNode(''.join(text))
""" Handlebars templates use constructs like: {{if condition}} print something{{/if}} This, of course, completely screws up Django templates, because Django thinks {{ and }} mean something. Wrap {% verbatim %} and {% endverbatim %} around those blocks of Handlebars templates and this will try its best to output the contents with no changes. """ from django import template # For Django >= 1.5, use the default verbatim tag implementation if not hasattr(template.defaulttags, 'verbatim'): register = template.Library() class VerbatimNode(template.Node): def __init__(self, text): self.text = text def render(self, context): return self.text @register.tag def verbatim(parser, token): text = [] while 1: token = parser.tokens.pop(0) if token.contents == 'endverbatim': break if token.token_type == template.TOKEN_VAR: text.append('{{') elif token.token_type == template.TOKEN_BLOCK: text.append('{%') text.append(token.contents) if token.token_type == template.TOKEN_VAR: text.append('}}') elif token.token_type == template.TOKEN_BLOCK: text.append('%}') return VerbatimNode(''.join(text))
Use consistent naming for 'Print / Export' section
Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', title: 'Student Progress', data: true, applyData: function(data) { if (data !== true) { return data; } return [ { text: 'Section Interim Reports', href: '#progress/interims/report', children: [ { text: 'Print / Export', href: '#progress/interims/print' }, { text: 'Email', href: '#progress/interims/email' } ] }, { text: 'Section Term Reports', href: '#progress/terms/report', children: [ { text: 'Print / Export', href: '#progress/terms/print' }, { text: 'Email', href: '#progress/terms/email' } ] } ]; } });
Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', title: 'Student Progress', data: true, applyData: function(data) { if (data !== true) { return data; } return [ { text: 'Section Interim Reports', href: '#progress/interims/report', children: [ { text: 'Print / Export', href: '#progress/interims/print' }, { text: 'Email', href: '#progress/interims/email' } ] }, { text: 'Section Term Reports', href: '#progress/terms/report', children: [ { text: 'Search & Print', href: '#progress/terms/print' }, { text: 'Email', href: '#progress/terms/email' } ] } ]; } });
Change inline css to href
import React from 'react'; import Helmet from 'react-helmet'; import { prefixLink } from 'gatsby-helpers'; const BUILD_TIME = new Date().getTime(); module.exports = React.createClass({ displayName: 'HTML', propTypes: { body: React.PropTypes.string, }, render() { const { body } = this.props; const { title } = Helmet.rewind(); const font = <link href="https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic" rel="stylesheet" type="text/css" />; let css; if (process.env.NODE_ENV === 'production') { // eslint-disable-next-line import/no-webpack-loader-syntax css = <link rel="stylesheet" type="text/css" href="/styles.css" />; } return ( <html lang="zh"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" /> { title.toComponent() } { font } { css } </head> <body> <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} /> <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} /> </body> </html> ); }, });
import React from 'react'; import Helmet from 'react-helmet'; import { prefixLink } from 'gatsby-helpers'; const BUILD_TIME = new Date().getTime(); module.exports = React.createClass({ displayName: 'HTML', propTypes: { body: React.PropTypes.string, }, render() { const { body } = this.props; const { title } = Helmet.rewind(); const font = <link href="https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic" rel="stylesheet" type="text/css" />; let css; if (process.env.NODE_ENV === 'production') { // eslint-disable-next-line import/no-webpack-loader-syntax css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />; } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" /> { title.toComponent() } { font } { css } </head> <body> <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} /> <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} /> </body> </html> ); }, });
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main()
Use config instead of hardcoding target channel
from irc3.plugins.command import command from irc3.plugins.cron import cron import irc3 from teamspeak_web_utils import nplstatus @irc3.plugin class TS3NPL(object): def __init__(self, bot): self.bot = bot self.npl_status = None config = bot.config.get('ts3npl', {}) self.target_channel = config.get('channel') @cron('* * * * *') def fetch_status(self): print('checking status') new_status = nplstatus() if self.npl_status is not None and new_status != self.npl_status \ and self.target_channel: if new_status: self.bot.privmsg(self.target_channel, 'NPL-Registrations are now open!') else: self.bot.privmsg(self.target_channel, 'NPL-Registrations are now closed!') self.npl_status = new_status @command(permission='view') def nplstatus(self, mask, target, args): '''check Teamspeak3 NPL-Registration-status %%nplstatus ''' if self.npl_status is None: self.npl_status = nplstatus() if self.npl_status: return 'NPL-Registrations are currently open!' else: return 'NPL-Registrations are currently closed!'
from irc3.plugins.command import command from irc3.plugins.cron import cron import irc3 from teamspeak_web_utils import nplstatus @irc3.plugin class TS3NPL(object): def __init__(self, bot): self.bot = bot self.npl_status = None self.target_channel = '#teamspeak' @cron('* * * * *') def fetch_status(self): new_status = nplstatus() if self.npl_status is not None and new_status != self.npl_status: if new_status: self.bot.privmsg(self.target_channel, 'NPL-Registrations are now open!') else: self.bot.privmsg(self.target_channel, 'NPL-Registrations are now closed!') self.npl_status = new_status @command(permission='view') def nplstatus(self, mask, target, args): '''check Teamspeak3 NPL-Registration-status %%nplstatus ''' if self.npl_status is None: self.npl_status = nplstatus() if self.npl_status: return 'NPL-Registrations are currently open!' else: return 'NPL-Registrations are currently closed!'
Watch only tests root folder
module.exports = function(grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), watch: { php: { files: ["src/**/*.php", "tests/*.php"], tasks: ["testphp"] } }, phpunit: { unit: { dir: "tests" }, options: { bin: "vendor/bin/phpunit --coverage-text --coverage-html ./report", colors: true, testdox: false } }, phplint: { options: { swapPath: "/tmp" }, all: ["src/**/*.php", "tests/**/*.php"] }, phpcs: { application: { src: ["src/**/*.php", "tests/**/*.php"] }, options: { bin: "vendor/bin/phpcs", standard: "PSR2" } } }); require("load-grunt-tasks")(grunt); grunt.registerTask("testphp", ["phplint", "phpcs", "phpunit"]); grunt.registerTask("default", ["testphp"]); };
module.exports = function(grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), watch: { php: { files: ["src/**/*.php", "tests/**/*.php"], tasks: ["testphp"] } }, phpunit: { unit: { dir: "tests" }, options: { bin: "vendor/bin/phpunit --coverage-text --coverage-html ./report", colors: true, testdox: false } }, phplint: { options: { swapPath: "/tmp" }, all: ["src/**/*.php", "tests/**/*.php"] }, phpcs: { application: { src: ["src/**/*.php", "tests/**/*.php"] }, options: { bin: "vendor/bin/phpcs", standard: "PSR2" } } }); require("load-grunt-tasks")(grunt); grunt.registerTask("testphp", ["phplint", "phpcs", "phpunit"]); grunt.registerTask("default", ["testphp"]); };
Add in handling for a user being unmuted
module.exports = function (bot) { bot.on('modMute', function (data) { if (config.verboseLogging) { console.log('[EVENT] modMute ', JSON.stringify(data, null, 2)); } var duration = 'unknown'; switch (data.d) { case 's': duration = '15'; break; case 'm': duration = '30'; break; case 'l': duration = '45'; break; default: // maybe this is an unmute? break; } getDbUserFromUsername(data.t, function (dbUser) { var message; if (duration == 'unknown') { message = '[UNMUTE] ' + data.t + ' (ID:' + data.i + ') was unmuted by ' + data.m; } else if (dbUser == null) { message = '[MUTE] ' + data.t + ' (ID:' + data.i + ') was muted for ' + duration + ' minutes by ' + data.m; } else { message = '[MUTE] ' + data.t + ' (ID:' + data.i + ', LVL:' + dbUser.site_points + ') was muted for ' + duration + ' minutes by ' + data.m; } console.log(message); sendToSlack(message); }); }); };
module.exports = function (bot) { bot.on('modMute', function (data) { if (config.verboseLogging) { console.log('[EVENT] modMute ', JSON.stringify(data, null, 2)); } var duration = 'unknown'; switch (data.d) { case 's': duration = '15'; break; case 'm': duration = '30'; break; case 'l': duration = '45'; break; } getDbUserFromUsername(data.t, function (dbUser) { var message; if (dbUser == null) { message = '[MUTE] ' + data.t + ' (ID: ' + data.i + ') was muted for ' + duration + ' minutes by ' + data.m; message = '[MUTE] ' + data.t + ' (ID: ' + data.i + ') was muted for ' + duration + ' minutes by ' + data.m; } else { message = '[BAN] ' + data.t + ' (ID: ' + data.i + ', LVL: ' + dbUser.site_points + ') was muted for ' + duration + ' minutes by ' + data.m; } console.log(message); sendToSlack(message); }); }); };
Support ipv6 for status endpoint security
package org.apereo.cas.configuration.model.core.web.security; import org.springframework.core.io.Resource; /** * This is {@link AdminPagesSecurityProperties}. * * @author Misagh Moayyed * @since 5.0.0 */ public class AdminPagesSecurityProperties { private String ip = "127\\.0\\.0\\.1|0:0:0:0:0:0:0:1"; private String adminRoles = "ROLE_ADMIN"; private String loginUrl; private String service; private Resource users; private boolean actuatorEndpointsEnabled; public boolean isActuatorEndpointsEnabled() { return actuatorEndpointsEnabled; } public void setActuatorEndpointsEnabled(final boolean actuatorEndpointsEnabled) { this.actuatorEndpointsEnabled = actuatorEndpointsEnabled; } public String getIp() { return ip; } public void setIp(final String ip) { this.ip = ip; } public String getAdminRoles() { return adminRoles; } public void setAdminRoles(final String adminRoles) { this.adminRoles = adminRoles; } public String getLoginUrl() { return loginUrl; } public void setLoginUrl(final String loginUrl) { this.loginUrl = loginUrl; } public String getService() { return service; } public void setService(final String service) { this.service = service; } public Resource getUsers() { return users; } public void setUsers(final Resource users) { this.users = users; } }
package org.apereo.cas.configuration.model.core.web.security; import org.springframework.core.io.Resource; /** * This is {@link AdminPagesSecurityProperties}. * * @author Misagh Moayyed * @since 5.0.0 */ public class AdminPagesSecurityProperties { private String ip = "127\\.0\\.0\\.1"; private String adminRoles = "ROLE_ADMIN"; private String loginUrl; private String service; private Resource users; private boolean actuatorEndpointsEnabled; public boolean isActuatorEndpointsEnabled() { return actuatorEndpointsEnabled; } public void setActuatorEndpointsEnabled(final boolean actuatorEndpointsEnabled) { this.actuatorEndpointsEnabled = actuatorEndpointsEnabled; } public String getIp() { return ip; } public void setIp(final String ip) { this.ip = ip; } public String getAdminRoles() { return adminRoles; } public void setAdminRoles(final String adminRoles) { this.adminRoles = adminRoles; } public String getLoginUrl() { return loginUrl; } public void setLoginUrl(final String loginUrl) { this.loginUrl = loginUrl; } public String getService() { return service; } public void setService(final String service) { this.service = service; } public Resource getUsers() { return users; } public void setUsers(final Resource users) { this.users = users; } }
Add dump function in development environment.
<?php /** * This file is part of the Miny framework. * (c) Dániel Buga <[email protected]> * * For licensing information see the LICENCE file. */ namespace Modules\Templating\Extensions; use Miny\Application\Application; use Miny\Application\BaseApplication; use Modules\Templating\Compiler\Functions\MethodFunction; use Modules\Templating\Compiler\Functions\SimpleFunction; use Modules\Templating\Extension; class Miny extends Extension { /** * @var BaseApplication */ private $application; public function __construct(Application $app) { parent::__construct(); $this->application = $app; } public function getExtensionName() { return 'miny'; } public function getFunctions() { $functions = array( new MethodFunction('route', 'routeFunction'), new MethodFunction('request', 'requestFunction'), ); if($this->application->isDeveloperEnvironment()) { $functions[] = new SimpleFunction('dump', 'var_dump'); } return $functions; } public function routeFunction($route, array $parameters = array()) { return $this->application->router->generate($route, $parameters); } public function requestFunction($url, $method = 'GET', array $post = array()) { $main = $this->application->response; $main->addContent(ob_get_clean()); $request = $this->application->request->getSubRequest($method, $url, $post); $response = $this->application->dispatch($request); $main->addResponse($response); ob_start(); } }
<?php /** * This file is part of the Miny framework. * (c) Dániel Buga <[email protected]> * * For licensing information see the LICENCE file. */ namespace Modules\Templating\Extensions; use Miny\Application\Application; use Miny\Application\BaseApplication; use Modules\Templating\Compiler\Functions\MethodFunction; use Modules\Templating\Extension; class Miny extends Extension { /** * @var BaseApplication */ private $application; public function __construct(Application $app) { parent::__construct(); $this->application = $app; } public function getExtensionName() { return 'miny'; } public function getFunctions() { return array( new MethodFunction('route', 'routeFunction'), new MethodFunction('request', 'requestFunction'), ); } public function routeFunction($route, array $parameters = array()) { return $this->application->router->generate($route, $parameters); } public function requestFunction($url, $method = 'GET', array $post = array()) { $main = $this->application->response; $main->addContent(ob_get_clean()); $request = $this->application->request->getSubRequest($method, $url, $post); $response = $this->application->dispatch($request); $main->addResponse($response); ob_start(); } }
Add ability to pass extra parameters for property types.
<?php namespace CatLab\Requirements\Traits; use CatLab\Requirements\Enums\PropertyType; /** * Class TypeSetter * @package CatLab\Requirements\Enums\PropertyType */ trait TypeSetter { /** * @param $type * @return $this */ public abstract function setType($type); /** * @return $this */ public function int() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::INTEGER); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } /** * @return $this */ public function string() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::STRING); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } /** * @return $this */ public function bool() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::BOOL); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } /** * @return $this */ public function datetime() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::DATETIME); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } /** * @return $this */ public function number() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::NUMBER); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } /** * @return $this */ public function object() { $arguments = func_get_args(); array_unshift($arguments, PropertyType::OBJECT); call_user_func_array([ $this, 'setType' ], $arguments); return $this; } }
<?php namespace CatLab\Requirements\Traits; use CatLab\Requirements\Enums\PropertyType; /** * Class TypeSetter * @package CatLab\Requirements\Enums\PropertyType */ trait TypeSetter { /** * @param $type * @return $this */ public abstract function setType($type); /** * @return $this */ public function int() { $this->setType(PropertyType::INTEGER); return $this; } /** * @return $this */ public function string() { $this->setType(PropertyType::STRING); return $this; } /** * @return $this */ public function bool() { $this->setType(PropertyType::BOOL); return $this; } /** * @return $this */ public function datetime() { $this->setType(PropertyType::DATETIME); return $this; } /** * @return $this */ public function number() { $this->setType(PropertyType::NUMBER); return $this; } public function object() { $this->setType(PropertyType::OBJECT); return $this; } }
Mod: Make comment removal a fallback when failed.
# -*- coding: utf-8 -*- """ JSON-LD extractor """ import json import re import lxml.etree import lxml.html HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)') class JsonLdExtractor(object): _xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]') def extract(self, htmlstring, base_url=None, encoding="UTF-8"): parser = lxml.html.HTMLParser(encoding=encoding) lxmldoc = lxml.html.fromstring(htmlstring, parser=parser) return self.extract_items(lxmldoc, base_url=base_url) def extract_items(self, document, base_url=None): return [item for items in map(self._extract_items, self._xp_jsonld(document)) for item in items if item] def _extract_items(self, node): script = node.xpath('string()') try: # TODO: `strict=False` can be configurable if needed data = json.loads(script, strict=False) except ValueError: # sometimes JSON-decoding errors are due to leading HTML or JavaScript comments data = json.loads(HTML_OR_JS_COMMENTLINE.sub('', script), strict=False) if isinstance(data, list): return data elif isinstance(data, dict): return [data]
# -*- coding: utf-8 -*- """ JSON-LD extractor """ import json import re import lxml.etree import lxml.html HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)') class JsonLdExtractor(object): _xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]') def extract(self, htmlstring, base_url=None, encoding="UTF-8"): parser = lxml.html.HTMLParser(encoding=encoding) lxmldoc = lxml.html.fromstring(htmlstring, parser=parser) return self.extract_items(lxmldoc, base_url=base_url) def extract_items(self, document, base_url=None): return [item for items in map(self._extract_items, self._xp_jsonld(document)) for item in items if item] def _extract_items(self, node): script = node.xpath('string()') # now do remove possible leading HTML/JavaScript comment first, allow control characters to be loaded # TODO: `strict=False` can be configurable if needed data = json.loads(HTML_OR_JS_COMMENTLINE.sub('', script), strict=False) if isinstance(data, list): return data elif isinstance(data, dict): return [data]
Revert cherry-picked jsma tutorial constant change
import unittest import numpy as np class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, 'train_end': 1000, 'test_start': 0, 'test_end': 1666, 'viz_enabled': False, 'source_samples': 1, 'nb_epochs': 2} report = mnist_tutorial_jsma.mnist_tutorial_jsma(**jsma_tutorial_args) # Check accuracy values contained in the AccuracyReport object # We already have JSMA tests in test_attacks.py, so just sanity # check the values here. self.assertTrue(report.clean_train_clean_eval > 0.65) self.assertTrue(report.clean_train_adv_eval < 0.25) # There is no adversarial training in the JSMA tutorial self.assertTrue(report.adv_train_clean_eval == 0.) self.assertTrue(report.adv_train_adv_eval == 0.) if __name__ == '__main__': unittest.main()
import unittest import numpy as np class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, 'train_end': 1000, 'test_start': 0, 'test_end': 166, 'viz_enabled': False, 'source_samples': 1, 'nb_epochs': 2} report = mnist_tutorial_jsma.mnist_tutorial_jsma(**jsma_tutorial_args) # Check accuracy values contained in the AccuracyReport object # We already have JSMA tests in test_attacks.py, so just sanity # check the values here. self.assertTrue(report.clean_train_clean_eval > 0.65) self.assertTrue(report.clean_train_adv_eval < 0.25) # There is no adversarial training in the JSMA tutorial self.assertTrue(report.adv_train_clean_eval == 0.) self.assertTrue(report.adv_train_adv_eval == 0.) if __name__ == '__main__': unittest.main()
Set default contentStyle prop to make message more readable
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { red900, grey50 } from 'material-ui/styles/colors'; class ErrorReporting extends Component { static defaultProps = { open: false, action: '', error: null, autoHideDuration: 10000, getMessage: (props) => props.error ? props.action + ': ' + props.error.toString() : '', style: { backgroundColor: red900, color: grey50 }, contentStyle: { display: 'block', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' } } exclusiveProps = [ 'getMessage', 'error', 'action' ] getSnackbarProps() { return Object .keys(this.props) .filter( (name) => this.exclusiveProps.indexOf(name) === -1 ) .reduce( (acc, name) => { acc[name] = this.props[name]; return acc; }, {} ); } render() { return ( <Snackbar open={this.props.open} message={this.props.getMessage(this.props)} autoHideDuration={this.props.autoHideDuration} style={this.props.style} contentStyle={this.props.style} bodyStyle={this.props.style} {...this.getSnackbarProps()} /> ); } } function mapStoreToProps(state) { const { action, error } = state.errors; return { open: error !== null, action: action, error: error }; } export default connect(mapStoreToProps)(ErrorReporting);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { red900, grey50 } from 'material-ui/styles/colors'; class ErrorReporting extends Component { static defaultProps = { open: false, action: '', error: null, autoHideDuration: 10000, getMessage: (props) => props.error ? props.action + ': ' + props.error.toString() : '', style: { backgroundColor: red900, color: grey50 } } render() { return ( <Snackbar open={this.props.open} message={this.props.getMessage(this.props)} autoHideDuration={this.props.autoHideDuration} style={this.props.style} contentStyle={this.props.style} bodyStyle={this.props.style} /> ); } } function mapStoreToProps(state) { const { action, error } = state.errors; return { open: error !== null, action: action, error: error }; } export default connect(mapStoreToProps)(ErrorReporting);
Test something with the mailer.
<?php require_once(__DIR__ . "/../libs/sendgrid-php/sendgrid-php.php"); // Simple class to send email notifications. class Mailer { public static function sendMail($clientAddress, $body) { $request_body = json_decode('{ "personalizations": [ { "to": [ { "email": "'.$clientAddress.'" } ], "cc": [ { "email": "[email protected]" } ], "subject": "Your order!" } ], "from": { "email": "[email protected]" }, "content": [ { "type": "text/plain", "value": "'.$body.'" } ] }'); if (Mailer::getWeb1Env() == "PROD") { $apiKey = getenv('SENDGRID_API'); $sg = new \SendGrid($apiKey); $response = $sg->client->mail()->send()->post($request_body); // DEBUG //echo $request_body."\n"; //echo $response->statusCode(); //echo $response->headers(); //echo $response->body(); return $response->statusCode(); } else { // We do not send mails in dev and test. // Maybe print some debug output here. } } private static function getWeb1Env() { $env = getenv('WEB1_ENV'); if ( $env != "") { return $env; } else { die("WEB1_ENV environment variable is not set!"); } } }
<?php require_once("libs/sendgrid-php/sendgrid-php.php"); // Simple class to send email notifications. class Mailer { public static function sendMail($clientAddress, $body) { $request_body = json_decode('{ "personalizations": [ { "to": [ { "email": "'.$clientAddress.'" } ], "cc": [ { "email": "[email protected]" } ], "subject": "Your order!" } ], "from": { "email": "[email protected]" }, "content": [ { "type": "text/plain", "value": "'.$body.'" } ] }'); if (Mailer::getWeb1Env() == "PROD") { $apiKey = getenv('SENDGRID_API'); $sg = new SendGrid($apiKey); $response = $sg->client->mail()->send()->post($request_body); // DEBUG //echo $request_body."\n"; //echo $response->statusCode(); //echo $response->headers(); //echo $response->body(); return $response->statusCode(); } else { // We do not send mails in dev and test. // Maybe print some debug output here. } } private static function getWeb1Env() { $env = getenv('WEB1_ENV'); if ( $env != "") { return $env; } else { die("WEB1_ENV environment variable is not set!"); } } }
Fix a small typo in the github url Signed-off-by: Ben Lopatin <[email protected]>
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='[email protected]', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='[email protected]', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
Add missing keywords, fix typo from vim syntax file
define(function (require) { 'use strict'; var jquery = require('jquery'); var monaco = require('monaco'); var cpp = require('vs/basic-languages/src/cpp'); function definition() { var ispc = jquery.extend(true, {}, cpp.language); // deep copy ispc.tokenPostfix = '.ispc'; ispc.keywords.push( 'cbreak', 'ccontinue', 'cdo', 'cfor', 'cif', 'creturn', 'cwhile', 'delete', 'export', 'foreach', 'foreach_active', 'foreach_tiled', 'foreach_unique', 'int16', 'int32', 'int64', 'int8', 'launch', 'new', 'operator', 'print', 'programCount', 'programIndex', 'reference', 'soa', 'sync', 'task', 'taskCount', 'taskCount0', 'taskCount1', 'taskCount2', 'taskIndex', 'taskIndex0', 'taskIndex1', 'taskIndex2', 'threadCount', 'threadIndex', 'uniform', 'varying' ); return ispc; } monaco.languages.register({id: 'ispc'}); monaco.languages.setMonarchTokensProvider('ispc', definition()); });
define(function (require) { 'use strict'; var jquery = require('jquery'); var monaco = require('monaco'); var cpp = require('vs/basic-languages/src/cpp'); function definition() { var ispc = jquery.extend(true, {}, cpp.language); // deep copy ispc.tokenPostfix = '.ispc'; ispc.keywords.push( 'cbreak', 'ccontinue', 'cdo', 'cfor', 'cif', 'creturn', 'cwhile', 'delete', 'export', 'foreach', 'foreach_active', 'foreach_tiled', 'foreach_unique', 'int16', 'int32', 'int64', 'int8', 'launch', 'new', 'operator', 'print', 'programCount', 'programIndex', 'reference', 'soa', 'sync', 'task', 'taskCount', 'taskCount0', 'taskCount1', 'taskCount3', 'taskIndex', 'taskIndex0', 'taskIndex1', 'taskIndex2', 'uniform', 'varying' ); return ispc; } monaco.languages.register({id: 'ispc'}); monaco.languages.setMonarchTokensProvider('ispc', definition()); });
Fix wrong stackOffset / stack slicing problem
define(['summernote/core/range'], function (range) { /** * History * @class */ var History = function ($editable) { var stack = [], stackOffset = -1; var editable = $editable[0]; var makeSnapshot = function () { var rng = range.create(); var emptyBookmark = {s: {path: [0], offset: 0}, e: {path: [0], offset: 0}}; return { contents: $editable.html(), bookmark: (rng ? rng.bookmark(editable) : emptyBookmark) }; }; var applySnapshot = function (snapshot) { if (snapshot.contents !== null) { $editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(editable, snapshot.bookmark).select(); } }; this.undo = function () { if (0 < stackOffset) { stackOffset--; applySnapshot(stack[stackOffset]); } }; this.redo = function () { if (stack.length - 1 > stackOffset) { stackOffset++; applySnapshot(stack[stackOffset]); } }; this.recordUndo = function () { stackOffset++; // Wash out stack after stackOffset if (stack.length > stackOffset) { stack = stack.slice(0, stackOffset); } // Create new snapshot and push it to the end stack.push(makeSnapshot()); }; // Create first undo stack this.recordUndo(); }; return History; });
define(['summernote/core/range'], function (range) { /** * History * @class */ var History = function ($editable) { var stack = [], stackOffset = 0; var editable = $editable[0]; var makeSnapshot = function () { var rng = range.create(); var emptyBookmark = {s: {path: [0], offset: 0}, e: {path: [0], offset: 0}}; return { contents: $editable.html(), bookmark: (rng ? rng.bookmark(editable) : emptyBookmark) }; }; var applySnapshot = function (snapshot) { if (snapshot.contents !== null) { $editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(editable, snapshot.bookmark).select(); } }; this.undo = function () { if (0 < stackOffset) { stackOffset--; applySnapshot(stack[stackOffset]); } }; this.redo = function () { if (stack.length - 1 > stackOffset) { stackOffset++; applySnapshot(stack[stackOffset]); } }; this.recordUndo = function () { // Wash out stack after stackOffset if (stack.length > stackOffset) { stack = stack.slice(0, stackOffset); } // Create new snapshot and push it to the end stack.push(makeSnapshot()); stackOffset++; }; // Create first undo stack this.recordUndo(); }; return History; });
Use Object.defineProperty() to define Response methods. git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9491 688a9155-6ab5-4160-a077-9df41f55a9e9
include('helma.buffer'); import('helma.system', 'system'); if (!global.Response) { system.addHostObject(org.helma.web.Response); /** * Render a skin to the response's buffer * @param skin * @param context * @param scope */ Object.defineProperty(Response.prototype, 'render', { value: function render(skin, context, scope) { var render = require('helma.skin').render; this.write(render(skin, context, scope)); } }); /** * Print a debug message to the rendered page. */ Object.defineProperty(Response.prototype, 'debug', { value: function debug() { var buffer = this.debugBuffer || new Buffer(); buffer.write("<div class=\"helma-debug-line\" style=\"background: yellow;"); buffer.write("color: black; border-top: 1px solid black;\">"); var length = arguments.length; for (var i = 0; i < length; i++) { buffer.write(arguments[i]); if (i < length - 1) { buffer.write(" "); } } buffer.writeln("</div>"); this.debugBuffer = buffer; return null; } }); /** * Write the debug buffer to the response's main buffer. */ Object.defineProperty(Response.prototype, 'flushDebug', { value: function() { if (this.debugBuffer != null) { this.write(this.debugBuffer); this.debugBuffer.reset(); } return null; } }); }
include('helma.buffer'); import('helma.system', 'system'); system.addHostObject(org.helma.web.Response); (function() { /** * Render a skin to the response's buffer * @param skin * @param context * @param scope */ this.render = function render(skin, context, scope) { var render = require('helma.skin').render; this.write(render(skin, context, scope)); } /** * Print a debug message to the rendered page. */ this.debug = function debug() { var buffer = this.debugBuffer || new Buffer(); buffer.write("<div class=\"helma-debug-line\" style=\"background: yellow;"); buffer.write("color: black; border-top: 1px solid black;\">"); var length = arguments.length; for (var i = 0; i < length; i++) { buffer.write(arguments[i]); if (i < length - 1) { buffer.write(" "); } } buffer.writeln("</div>"); this.debugBuffer = buffer; return null; }; /** * Write the debug buffer to the response's main buffer. */ this.flushDebug = function() { if (this.debugBuffer != null) { this.write(this.debugBuffer); this.debugBuffer.reset(); } return null; }; }).apply(Response.prototype);
Support kwargs along with args for functions
""" This module is to include utils for managing compatibility between Python and Odin releases. """ import inspect import warnings def deprecated(message, category=DeprecationWarning): """ Decorator for marking classes/functions as being deprecated and are to be removed in the future. :param message: Message provided. :param category: Category of warning, defaults to DeprecationWarning """ def wrap(obj): if inspect.isclass(obj): old_init = obj.__init__ def wrapped_init(*args, **kwargs): warnings.warn( "{0} is deprecated and scheduled for removal. {1}".format(obj.__name__, message), category=category ) return old_init(*args, **kwargs) obj.__init__ = wrapped_init return obj else: def wrapped_func(*args, **kwargs): warnings.warn( "{0} is deprecated and scheduled for removal. {1}".format(obj.__name__, message), category=category ) return obj(*args, **kwargs) return wrapped_func return wrap
""" This module is to include utils for managing compatibility between Python and Odin releases. """ import inspect import warnings def deprecated(message, category=DeprecationWarning): """ Decorator for marking classes/functions as being deprecated and are to be removed in the future. :param message: Message provided. :param category: Category of warning, defaults to DeprecationWarning """ def wrap(obj): if inspect.isclass(obj): old_init = obj.__init__ def wrapped_init(*args, **kwargs): warnings.warn( "{0} is deprecated and scheduled for removal. {1}".format(obj.__name__, message), category=category ) return old_init(*args, **kwargs) obj.__init__ = wrapped_init return obj else: def wrapped_func(*args): warnings.warn( "{0} is deprecated and scheduled for removal. {1}".format(obj.__name__, message), category=category ) return obj(*args) return wrapped_func return wrap
Add missing number and object static methods Took from "Object static methods" and "Number properties" sections here https://kangax.github.io/compat-table/es6/
'use strict'; module.exports = { meta: { docs: { description: 'Forbid methods added in ES6' }, schema: [{ type: 'object', properties: { exceptMethods: { type: 'array', items: { type: 'string' } } } }] }, create(context) { const options = Object.assign({ exceptMethods: [] }, context.options[0]); const exceptMethods = new Set(options.exceptMethods); const es6StaticFunctions = [ 'Array.from', 'Array.of', 'Math.acosh', 'Math.hypot', 'Math.trunc', 'Math.imul', 'Math.sign', 'Number.isNaN', 'Number.isFinite', 'Number.isInteger', 'Number.isSafeInteger', 'Number.parseFloat', 'Number.parseInt', 'Object.assign', 'Object.is', 'Object.getOwnPropertySymbols', 'Object.setPrototypeOf', ]; const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name)); return { CallExpression(node) { if(node.callee && node.callee.property && node.callee.object) { const functionName = node.callee.object.name + '.' + node.callee.property.name; if(staticFunctions.includes(functionName)) { context.report({ node: node.callee.property, message: 'ES6 static methods not allowed: ' + functionName }); } } } }; } };
'use strict'; module.exports = { meta: { docs: { description: 'Forbid methods added in ES6' }, schema: [{ type: 'object', properties: { exceptMethods: { type: 'array', items: { type: 'string' } } } }] }, create(context) { const options = Object.assign({ exceptMethods: [] }, context.options[0]); const exceptMethods = new Set(options.exceptMethods); const es6StaticFunctions = [ 'Array.from', 'Array.of', 'Math.acosh', 'Math.hypot', 'Math.trunc', 'Math.imul', 'Math.sign', 'Number.isNaN', 'Number.isFinite', 'Number.isSafeInteger', 'Object.assign', ]; const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name)); return { CallExpression(node) { if(node.callee && node.callee.property && node.callee.object) { const functionName = node.callee.object.name + '.' + node.callee.property.name; if(staticFunctions.includes(functionName)) { context.report({ node: node.callee.property, message: 'ES6 static methods not allowed: ' + functionName }); } } } }; } };
Split the Tomat mining commandlet into an Unreal part and a TomatConsole part.
# -*- coding: utf-8 -*- from nimp.commands._cis_command import * from nimp.utilities.ue3 import * from nimp.utilities.deployment import * from nimp.utilities.file_mapper import * import tempfile import shutil #------------------------------------------------------------------------------- class CisTomatMining(CisCommand): abstract = 0 def __init__(self): CisCommand.__init__(self, 'cis-tomat-mining', 'Mines UE3 content into Tomat') #--------------------------------------------------------------------------- def cis_configure_arguments(self, env, parser): return True #--------------------------------------------------------------------------- def _cis_run(self, env): if call_process('.', ['pacman', '-S', '--noconfirm', 'repman']) != 0: return False if call_process('.', ['repman', 'add', 'dont-nod', 'http://pacman/']) != 0: return False if call_process('.', ['pacman', '-Scc', '--noconfirm']) != 0: return False if call_process('.', ['pacman', '-S', '--noconfirm', '--force', 'tomat-console']) != 0: return False tmpdir = tempfile.mkdtemp() success = True if success and env.is_ue3: success = ue3_commandlet(env.game, 'dnetomatminingcommandlet', [ tmpdir ]) if success: success = call_process('.', [ 'TomatConsole', 'ImportFromUnreal', '--RepositoryUri', 'sql://mining@console', '--TmpDirectory', tmpdir ]) == 0 # Clean up after ourselves shutil.rmtree(tmpdir) return success
# -*- coding: utf-8 -*- from nimp.commands._cis_command import * from nimp.utilities.ue3 import * from nimp.utilities.deployment import * from nimp.utilities.file_mapper import * #------------------------------------------------------------------------------- class CisTomatMining(CisCommand): abstract = 0 def __init__(self): CisCommand.__init__(self, 'cis-tomat-mining', 'Mines UE3 content into Tomat') #--------------------------------------------------------------------------- def cis_configure_arguments(self, env, parser): return True #--------------------------------------------------------------------------- def _cis_run(self, env): if call_process('.', ['pacman', '-S', '--noconfirm', 'repman']) != 0: return False if call_process('.', ['repman', 'add', 'dont-nod', 'http://pacman']) != 0: return False if call_process('.', ['pacman', '-S', '--noconfirm', '--needed', 'tomat-console']) != 0: return False return call_process('.', [ 'TomatConsole', 'ImportFromUnreal', '--RepositoryUri', 'sql://mining@console', '--UnrealEnginePath', 'Binaries/Win64/ExampleGame.exe' ])
Change development status to beta
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-allauth', version='0.0.1', author='Raymond Penners', author_email='[email protected]', description='Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.', long_description=open('README.rst').read(), url='http://github.com/pennersr/django-allauth', keywords='django auth account social openid twitter facebook oauth registration', install_requires=['django', 'oauth2', 'python-openid', 'django-email-confirmation', 'django-uni-form'], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(), package_data={'allauth': ['templates/allauth/*.html'], } ) if __name__ == '__main__': setup(**METADATA)
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-allauth', version='0.0.1', author='Raymond Penners', author_email='[email protected]', description='Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.', long_description=open('README.rst').read(), url='http://github.com/pennersr/django-allauth', keywords='django auth account social openid twitter facebook oauth registration', install_requires=['django', 'oauth2', 'python-openid', 'django-email-confirmation', 'django-uni-form'], include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(), package_data={'allauth': ['templates/allauth/*.html'], } ) if __name__ == '__main__': setup(**METADATA)
Remove default argument syntax on getVersionedGithubPath() Summary: Removes ES6 syntax of default arguments to fix website building as per #7434. [More info](https://github.com/facebook/react-native/pull/7434). Closes https://github.com/facebook/react-native/pull/7439 Differential Revision: D3274206 fb-gh-sync-id: 3a8f5950ead91cf59c27fd384e97bf9587005398 fbshipit-source-id: 3a8f5950ead91cf59c27fd384e97bf9587005398
/** * 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. * * @providesModule HeaderWithGithub */ var H = require('Header'); var React = require('React'); function getVersionedGithubPath(path, version) { version = version || 'next'; return [ 'https://github.com/facebook/react-native/blob', version === 'next' ? 'master' : version + '-stable', path ].join('/'); } var HeaderWithGithub = React.createClass({ contextTypes: { version: React.PropTypes.string }, render: function() { return ( <table width="100%"> <tbody> <tr> <td> <H level={this.props.level || 3} toSlug={this.props.title}> {this.props.title} </H> </td> <td style={{textAlign: 'right'}}> <a target="_blank" href={getVersionedGithubPath(this.props.path, this.context.version)}> Edit on GitHub </a> </td> </tr> </tbody> </table> ); } }); module.exports = HeaderWithGithub;
/** * 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. * * @providesModule HeaderWithGithub */ var H = require('Header'); var React = require('React'); function getVersionedGithubPath(path, version='next') { return [ 'https://github.com/facebook/react-native/blob', version === 'next' ? 'master' : version + '-stable', path ].join('/') } var HeaderWithGithub = React.createClass({ contextTypes: { version: React.PropTypes.string }, render: function() { return ( <table width="100%"> <tbody> <tr> <td> <H level={this.props.level || 3} toSlug={this.props.title}> {this.props.title} </H> </td> <td style={{textAlign: 'right'}}> <a target="_blank" href={getVersionedGithubPath(this.props.path, this.context.version)}> Edit on GitHub </a> </td> </tr> </tbody> </table> ); } }); module.exports = HeaderWithGithub;
Fix access of yaml config
package net.md_5.bungee.config; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Map; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @NoArgsConstructor(access = AccessLevel.PACKAGE) public class YamlConfiguration extends ConfigurationProvider { private final ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>() { @Override protected Yaml initialValue() { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK ); return new Yaml( options ); } }; @Override public Configuration load(File file) { try ( FileReader reader = new FileReader( file ) ) { return load( reader ); } catch ( IOException ex ) { return null; } } @Override @SuppressWarnings("unchecked") public Configuration load(Reader reader) { Configuration conf = new Configuration( (Map<String, Object>) yaml.get().loadAs( reader, Map.class ), null ); return conf; } @Override @SuppressWarnings("unchecked") public Configuration load(String string) { Configuration conf = new Configuration( (Map<String, Object>) yaml.get().loadAs( string, Map.class ), null ); return conf; } }
package net.md_5.bungee.config; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Map; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; class YamlConfiguration extends ConfigurationProvider { private final ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>() { @Override protected Yaml initialValue() { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK ); return new Yaml( options ); } }; @Override public Configuration load(File file) { try ( FileReader reader = new FileReader( file ) ) { return load( reader ); } catch ( IOException ex ) { return null; } } @Override @SuppressWarnings("unchecked") public Configuration load(Reader reader) { Configuration conf = new Configuration( (Map<String, Object>) yaml.get().loadAs( reader, Map.class ), null ); return conf; } @Override @SuppressWarnings("unchecked") public Configuration load(String string) { Configuration conf = new Configuration( (Map<String, Object>) yaml.get().loadAs( string, Map.class ), null ); return conf; } }
Remove reliance on distutils log verbosity.
import pytest from jaraco import path from setuptools.command.test import test from setuptools.dist import Distribution from .textwrap import DALS @pytest.mark.usefixtures('tmpdir_cwd') def test_tests_are_run_once(capfd): params = dict( name='foo', packages=['dummy'], ) files = { 'setup.py': 'from setuptools import setup; setup(' + ','.join(f'{name}={params[name]!r}' for name in params) + ')', 'dummy': { '__init__.py': '', 'test_dummy.py': DALS( """ import unittest class TestTest(unittest.TestCase): def test_test(self): print('Foo') """ ), }, } path.build(files) dist = Distribution(params) dist.script_name = 'setup.py' cmd = test(dist) cmd.ensure_finalized() cmd.run() out, err = capfd.readouterr() assert out.endswith('Foo\n') assert len(out.split('Foo')) == 2
import pytest from jaraco import path from setuptools.command.test import test from setuptools.dist import Distribution from .textwrap import DALS @pytest.fixture def quiet_log(): # Running some of the other tests will automatically # change the log level to info, messing our output. import distutils.log distutils.log.set_verbosity(0) @pytest.mark.usefixtures('tmpdir_cwd', 'quiet_log') def test_tests_are_run_once(capfd): params = dict( name='foo', packages=['dummy'], ) files = { 'setup.py': 'from setuptools import setup; setup(' + ','.join(f'{name}={params[name]!r}' for name in params) + ')', 'dummy': { '__init__.py': '', 'test_dummy.py': DALS( """ import unittest class TestTest(unittest.TestCase): def test_test(self): print('Foo') """ ), }, } path.build(files) dist = Distribution(params) dist.script_name = 'setup.py' cmd = test(dist) cmd.ensure_finalized() cmd.run() out, err = capfd.readouterr() assert out == 'Foo\n'
Use smallint for Firebird if tinyint is requested
package liquibase.datatype.core; import liquibase.database.Database; import liquibase.database.core.DerbyDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.database.core.PostgresDatabase; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; @DataTypeInfo(name="tinyint", aliases = "java.sql.Types.TINYINT", minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class TinyIntType extends LiquibaseDataType { private boolean autoIncrement; public boolean isAutoIncrement() { return autoIncrement; } public void setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; } @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof DerbyDatabase || database instanceof PostgresDatabase || database instanceof FirebirdDatabase) { return new DatabaseDataType("SMALLINT"); } if (database instanceof MSSQLDatabase) { return new DatabaseDataType("TINYINT"); } if (database instanceof OracleDatabase) { return new DatabaseDataType("NUMBER",3); } return super.toDatabaseDataType(database); } }
package liquibase.datatype.core; import liquibase.database.Database; import liquibase.database.core.DerbyDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.database.core.PostgresDatabase; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; @DataTypeInfo(name="tinyint", aliases = "java.sql.Types.TINYINT", minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class TinyIntType extends LiquibaseDataType { private boolean autoIncrement; public boolean isAutoIncrement() { return autoIncrement; } public void setAutoIncrement(boolean autoIncrement) { this.autoIncrement = autoIncrement; } @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof DerbyDatabase || database instanceof PostgresDatabase) { return new DatabaseDataType("SMALLINT"); } if (database instanceof MSSQLDatabase) { return new DatabaseDataType("TINYINT"); } if (database instanceof OracleDatabase) { return new DatabaseDataType("NUMBER",3); } return super.toDatabaseDataType(database); } }
Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods. Signed-off-by: Baptiste Millou <[email protected]>
# -*- coding: utf-8 -*- import unittest from bitbucket.bitbucket import Bitbucket from bitbucket.tests.private import USERNAME, PASSWORD TEST_REPO_SLUG = 'test_bitbucket_api' class AuthenticatedBitbucketTest(unittest.TestCase): """ Bitbucket test base class for authenticated methods.""" def setUp(self): """Creating a new authenticated Bitbucket...""" self.bb = Bitbucket(USERNAME, PASSWORD) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug'] def tearDown(self): """Destroying the Bitbucket...""" # Delete the repository. self.bb.repository.delete() self.bb = None class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest): """ Testing Bitbucket annonymous methods.""" def test_get_tags(self): """ Test get_tags.""" success, result = self.bb.get_tags() self.assertTrue(success) self.assertIsInstance(result, dict) # test with invalid repository name success, result = self.bb.get_tags(repo_slug='azertyuiop') self.assertFalse(success) def test_get_branches(self): """ Test get_branches.""" success, result = self.bb.get_branches() self.assertTrue(success) self.assertIsInstance(result, dict) # test with invalid repository name success, result = self.bb.get_branches(repo_slug='azertyuiop') self.assertFalse(success)
# -*- coding: utf-8 -*- import unittest from bitbucket.bitbucket import Bitbucket from bitbucket.tests.private import USERNAME, PASSWORD TEST_REPO_SLUG = 'test_bitbucket_api' class AuthenticatedBitbucketTest(unittest.TestCase): """ Bitbucket test base class for authenticated methods.""" def setUp(self): """Creating a new authenticated Bitbucket...""" self.bb = Bitbucket(USERNAME, PASSWORD) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug'] def tearDown(self): """Destroying the Bitbucket...""" # Delete the repository. self.bb.repository.delete() self.bb = None class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest): """ Testing Bitbucket annonymous methods.""" def test_get_tags(self): """ Test get_tags.""" success, result = self.bb.get_tags() self.assertTrue(success) self.assertIsInstance(result, dict) def test_get_branches(self): """ Test get_branches.""" success, result = self.bb.get_branches() self.assertTrue(success) self.assertIsInstance(result, dict)
Add Python 3.8 to supported versions
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="pdf2image", version="1.9.1", description="A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Belval/pdf2image", author="Edouard Belval", author_email="[email protected]", # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], keywords="pdf image png jpeg jpg convert", packages=find_packages(exclude=["contrib", "docs", "tests"]), install_requires=["pillow"], )
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="pdf2image", version="1.9.0", description="A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Belval/pdf2image", author="Edouard Belval", author_email="[email protected]", # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], keywords="pdf image png jpeg jpg convert", packages=find_packages(exclude=["contrib", "docs", "tests"]), install_requires=["pillow"], )
Replace calls to deprecated Symfony2 functions, fix phpdoc
<?php namespace Ddeboer\VatinBundle\Validator\Constraints; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Constraint; use Ddeboer\Vatin\Validator; /** * Validate a VAT identification number using the ddeboer/vatin library * */ class VatinValidator extends ConstraintValidator { /** * VATIN validator * * @var Validator */ protected $validator; /** * Constructor * * @param Validator $validator VATIN validator */ public function __construct(Validator $validator) { $this->validator = $validator; } /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (null === $value || '' === $value) { return; } if ($this->isValidVatin($value, $constraint->checkExistence)) { return; } $this->context->addViolation($constraint->message); } /** * Is the value a valid VAT identification number? * * @param string $value Value * @param bool $checkExistence Also check whether the VAT number exists * * @return bool */ protected function isValidVatin($value, $checkExistence) { return $this->validator->isValid($value, $checkExistence); } }
<?php namespace Ddeboer\VatinBundle\Validator\Constraints; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Constraint; use Ddeboer\Vatin\Validator; /** * Validate a VAT identification number using the ddeboer/vatin library * */ class VatinValidator extends ConstraintValidator { /** * VATIN validator * * @var Validator */ protected $validator; /** * Constructor * * @param Validator $validator VATIN validator */ public function __construct(Validator $validator) { $this->validator = $validator; } /** * {@inheritdoc} */ public function isValid($value, Constraint $constraint) { if (null === $value || '' === $value) { return; } if ($this->isValidVatin($value, $constraint->checkExistence)) { return; } $this->setMessage($constraint->message); } /** * Is the value a valid VAT identification number? * * @param string $value Value * * @return bool */ protected function isValidVatin($value, $checkExistence) { return $this->validator->isValid($value, $checkExistence); } }
Make it possible to step() in a newly created env, rather than throwing AttributeError
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering self._reset() @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
Remove 3.1 and 3.2 from python_requires (and classifiers) to allow it to still install for those versions
import io import os import re from setuptools import setup, find_packages def find_version(): file_dir = os.path.dirname(__file__) with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f: version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read()) if version: return version.group(1) else: raise RuntimeError("Unable to find version string.") setup( name='auth0-python', version=find_version(), description='Auth0 Python SDK', author='Auth0', author_email='[email protected]', license='MIT', packages=find_packages(), install_requires=['requests'], extras_require={'test': ['mock']}, python_requires='>=2.7, !=3.0.*, !=3.1.*', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], url='https://github.com/auth0/auth0-python', )
import io import os import re from setuptools import setup, find_packages def find_version(): file_dir = os.path.dirname(__file__) with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f: version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read()) if version: return version.group(1) else: raise RuntimeError("Unable to find version string.") setup( name='auth0-python', version=find_version(), description='Auth0 Python SDK', author='Auth0', author_email='[email protected]', license='MIT', packages=find_packages(), install_requires=['requests'], extras_require={'test': ['mock']}, python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], url='https://github.com/auth0/auth0-python', )
Use ECMAScript strict mode, fix jslint errors.
/*jslint browser: true, forin: true */ (function($, window) { "use strict"; var REFRESH_SERVICES_TIMEOUT = 5000; $.ajaxSetup({ error: function(e, req, options, error) { $('#url').text(options.url); $('#error').show(); } }); var needRefreshServices, refreshServices; refreshServices = function() { refreshServices.timer = null; $.ajax({ url: '/services', cache: false }).error(function() { $('#url').text('/services'); $('#error').show(); }).success(function(html) { $('#error').hide(); $('#services').html(html); }).complete(function() { needRefreshServices(false); }); }; refreshServices.timer = null; needRefreshServices = function(now) { if (refreshServices.timer !== null) { window.clearTimeout(refreshServices.timer); refreshServices.timer = null; } if (now) { refreshServices(); } else { refreshServices.timer = window.setTimeout(refreshServices, REFRESH_SERVICES_TIMEOUT); } }; $('#services').delegate('form.service-action,form.service-signal', 'submit', function(e) { e.preventDefault(); $.post($(this).attr('action')).complete(function() { needRefreshServices(true); }); return false; }); $('#service-refresh-interval').text(REFRESH_SERVICES_TIMEOUT / 1000); needRefreshServices(true); })(jQuery, window);
(function($) { var REFRESH_SERVICES_TIMEOUT = 5000; $.ajaxSetup({ error: function(e, req, options, error) { $('#url').text(settings.url); $('#error').show(); } }); var needRefreshServices; var refreshServices = function() { refreshServices.timer = null; $.ajax({ url: '/services', cache: false }).error(function() { $('#url').text('/services'); $('#error').show(); }).success(function(html) { $('#error').hide(); $('#services').html(html); }).complete(function() { needRefreshServices(false); }); }; needRefreshServices = function(now) { if (refreshServices.timer != null) { clearTimeout(refreshServices.timer); refreshServices.timer = null; } if (now) { refreshServices(); } else { refreshServices.timer = setTimeout(refreshServices, REFRESH_SERVICES_TIMEOUT); } }; $('#services').delegate('form.service-action,form.service-signal', 'submit', function(e) { e.preventDefault(); $.post($(this).attr('action')).complete(function() { needRefreshServices(true); }); return false; }); $('#service-refresh-interval').text(REFRESH_SERVICES_TIMEOUT / 1000); needRefreshServices(true); })(jQuery);
Handle cases where [anonymous function].name is undefined instead of "".
(function(global) { "use strict"; // ulta-simple Object.create polyfill (only does half the job) var create = Object.create || (function() { var Maker = function(){}; return function(prototype) { Maker.prototype = prototype; return new Maker(); } }()); var newless = function(constructor) { // in order to preserve constructor name, use the Function constructor var name = constructor.name || ""; var newlessConstructor = Function("constructor, create", "var newlessConstructor = function " + name + "() {" + "var obj = this;" + // don't create a new object if we've already got one // (e.g. we were called with `new`) "if (!(this instanceof newlessConstructor)) {" + "obj = create(newlessConstructor.prototype);" + "}" + // run the original constructor "var returnValue = constructor.apply(obj, arguments);" + // if we got back an object (and not null), use it as the return value "return (typeof returnValue === 'object' && returnValue) || obj;" + "};" + "return newlessConstructor;")(constructor, create); newlessConstructor.prototype = constructor.prototype; newlessConstructor.prototype.constructor = newlessConstructor; newlessConstructor.displayName = constructor.displayName; return newlessConstructor; }; // support Node and browser if (typeof module !== "undefined") { module.exports = newless; } else { global.newless = newless; } }(this));
(function(global) { "use strict"; // ulta-simple Object.create polyfill (only does half the job) var create = Object.create || (function() { var Maker = function(){}; return function(prototype) { Maker.prototype = prototype; return new Maker(); } }()); var newless = function(constructor) { // in order to preserve constructor name, use the Function constructor var newlessConstructor = Function("constructor, create", "var newlessConstructor = function " + constructor.name + "() {" + "var obj = this;" + // don't create a new object if we've already got one // (e.g. we were called with `new`) "if (!(this instanceof newlessConstructor)) {" + "obj = create(newlessConstructor.prototype);" + "}" + // run the original constructor "var returnValue = constructor.apply(obj, arguments);" + // if we got back an object (and not null), use it as the return value "return (typeof returnValue === 'object' && returnValue) || obj;" + "};" + "return newlessConstructor;")(constructor, create); newlessConstructor.prototype = constructor.prototype; newlessConstructor.prototype.constructor = newlessConstructor; newlessConstructor.displayName = constructor.displayName; return newlessConstructor; }; // support Node and browser if (typeof module !== "undefined") { module.exports = newless; } else { global.newless = newless; } }(this));
Use url in query, not path
// Mine const getResponse = query => { const token = require('../config.json').token || false; if (!token) { throw new Error(`token is not defined`); } return require('gh-got')('https://api.github.com/graphql', { json: true, headers: { authorization: `bearer ${token}` }, body: { query } }); }; exports.tools = { radar: () => { return new Promise((resolve, reject) => { let query = `query { repository(owner: "github", name: "services") { issues(first: 1, labels: "O: radar", states: OPEN) { edges { node { url } } } } }`; getResponse(query) .then(response => { let url = response.body.data.repository.issues.edges[0].node.url; resolve(`${url}`); }) .catch(err => { reject(err); }); }); }, repo: repo => { return new Promise((resolve, reject) => { let query = `query { repository(owner: "github", name: "${repo}") { url } }`; getResponse(query) .then(response => { let url = response.body.data.repository.url; resolve(`${url}`); }) .catch(err => { reject(err); }); }); } };
// Mine const getResponse = query => { const token = require('../config.json').token || false; if (!token) { throw new Error(`token is not defined`); } return require('gh-got')('https://api.github.com/graphql', { json: true, headers: { authorization: `bearer ${token}` }, body: { query } }); }; exports.tools = { radar: () => { return new Promise((resolve, reject) => { let query = `query { repository(owner: "github", name: "services") { issues(first: 1, labels: "O: radar", states: OPEN) { edges { node { path } } } } }`; getResponse(query) .then(response => { let radar = response.body.data.repository.issues.edges[0].node.path; resolve(`https://github.com${radar}`); }) .catch(err => { reject(err); }); }); }, repo: repo => { return new Promise((resolve, reject) => { let query = `query { repository(owner: "github", name: "${repo}") { url } }`; getResponse(query) .then(response => { let url = response.body.data.repository.url; resolve(`${url}`); }) .catch(err => { reject(err); }); }); } };
Fix fail when no StyleBlock classes are allowed
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\Markdown\StyleBlock; use Ds\Set; use InvalidArgumentException; use League\CommonMark\Block\Element\AbstractBlock; use League\CommonMark\Block\Renderer\BlockRendererInterface; use League\CommonMark\ElementRendererInterface; use League\CommonMark\HtmlElement; use League\CommonMark\Util\ConfigurationAwareInterface; use League\CommonMark\Util\ConfigurationInterface; class Renderer implements BlockRendererInterface, ConfigurationAwareInterface { /** * @var Set */ private $allowedClasses; public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false) { if (!$block instanceof Element) { throw new InvalidArgumentException('Incompatible block type: '.get_class($block)); } $renderedChildren = $htmlRenderer->renderBlocks($block->children()); if (!$this->allowedClasses->contains($block->getClass())) { return $renderedChildren; } $separator = $htmlRenderer->getOption('inner_separator', "\n"); return new HtmlElement( 'div', $block->getData('attributes', []), $separator.$renderedChildren.$separator, ); } public function setConfiguration(ConfigurationInterface $configuration): void { $this->allowedClasses = new Set($configuration->get('style_block_allowed_classes') ?? []); } }
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\Markdown\StyleBlock; use Ds\Set; use InvalidArgumentException; use League\CommonMark\Block\Element\AbstractBlock; use League\CommonMark\Block\Renderer\BlockRendererInterface; use League\CommonMark\ElementRendererInterface; use League\CommonMark\HtmlElement; use League\CommonMark\Util\ConfigurationAwareInterface; use League\CommonMark\Util\ConfigurationInterface; class Renderer implements BlockRendererInterface, ConfigurationAwareInterface { /** * @var Set */ private $allowedClasses; public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false) { if (!$block instanceof Element) { throw new InvalidArgumentException('Incompatible block type: '.get_class($block)); } $renderedChildren = $htmlRenderer->renderBlocks($block->children()); if (!$this->allowedClasses->contains($block->getClass())) { return $renderedChildren; } $separator = $htmlRenderer->getOption('inner_separator', "\n"); return new HtmlElement( 'div', $block->getData('attributes', []), $separator.$renderedChildren.$separator, ); } public function setConfiguration(ConfigurationInterface $configuration): void { $this->allowedClasses = new Set($configuration->get('style_block_allowed_classes')); } }
Fix glibc version detect string
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' if is_glibc: glibc_ver = platform.libc_ver()[1] libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit()) libc_ok = libc_numeric >= (2, 9) else: libc_ok = False windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) min_unix_version = not windows and sys.version_info >= (3, 3) if cpython and ((min_unix_version and libc_ok) or min_win_version): _cbor2 = Extension( '_cbor2', # math.h routines are built-in to MSVCRT libraries=['m'] if not windows else [], extra_compile_args=['-std=c99'], sources=[ 'source/module.c', 'source/encoder.c', 'source/decoder.c', 'source/tags.c', 'source/halffloat.c', ] ) kwargs = {'ext_modules': [_cbor2]} else: kwargs = {} setup( use_scm_version={ 'version_scheme': 'post-release', 'local_scheme': 'dirty-tag' }, setup_requires=[ 'setuptools >= 36.2.7', 'setuptools_scm >= 1.7.0' ], **kwargs )
import sys import platform from setuptools import setup, Extension cpython = platform.python_implementation() == 'CPython' is_glibc = platform.libc_ver()[0] == 'glibc' libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9' windows = sys.platform.startswith('win') min_win_version = windows and sys.version_info >= (3, 5) min_unix_version = not windows and sys.version_info >= (3, 3) if cpython and ((min_unix_version and libc_ok) or min_win_version): _cbor2 = Extension( '_cbor2', # math.h routines are built-in to MSVCRT libraries=['m'] if not windows else [], extra_compile_args=['-std=c99'], sources=[ 'source/module.c', 'source/encoder.c', 'source/decoder.c', 'source/tags.c', 'source/halffloat.c', ] ) kwargs = {'ext_modules': [_cbor2]} else: kwargs = {} setup( use_scm_version={ 'version_scheme': 'post-release', 'local_scheme': 'dirty-tag' }, setup_requires=[ 'setuptools >= 36.2.7', 'setuptools_scm >= 1.7.0' ], **kwargs )
Add Pomodoro and remove pomodoro functionality
// @flow import React, { Component } from "react"; import { connect } from "react-redux"; import { addTask } from "../actions/task"; import type { actionType } from "../reducers/task"; type Props = { cancel: () => void, dispatch: (action: actionType) => void }; type State = { pomodoros: number }; class AddInput extends Component { props: Props; state: State; constructor(props: Props) { super(props); this.state = { pomodoros: 0 }; } componentDidMount() {} componentWillUnmount() {} addPomodoro() { this.setState({ pomodoros: this.state.pomodoros + 1 }); } removePomodoro() { if (this.state.pomodoros > 0) { this.setState({ pomodoros: this.state.pomodoros - 1 }); } } render() { let task: ?HTMLInputElement; return ( <form onSubmit={e => { e.preventDefault(); if (task && task.value.trim()) { this.props.dispatch(addTask(task.value.trim(), 1)); task.value = ""; this.props.cancel(); } }} > {/* eslint-disable jsx-a11y/no-autofocus */} <input ref={node => { task = node; }} type="text" autoFocus placeholder="Task name" />; </form> ); } } /* eslint-disable no-class-assign */ AddInput = connect()(AddInput); export default AddInput;
// @flow import React, { Component } from "react"; import { connect } from "react-redux"; import { addTask } from "../actions/task"; import type { actionType } from "../reducers/task"; type Props = { cancel: () => void, dispatch: (action: actionType) => void }; type State = { pomodoros: number }; class AddInput extends Component { props: Props; state: State; constructor(props: Props) { super(props); this.state = { pomodoros: 0 }; } render() { let task: ?HTMLInputElement; return ( <form onSubmit={e => { e.preventDefault(); if (task && task.value.trim()) { this.props.dispatch(addTask(task.value.trim(), 1)); task.value = ""; this.props.cancel(); } }} > {/* eslint-disable jsx-a11y/no-autofocus */} <input ref={node => { task = node; }} type="text" autoFocus placeholder="Task name" />; </form> ); } } /* eslint-disable no-class-assign */ AddInput = connect()(AddInput); export default AddInput;
Remove (Participant) relationship displayed after the last non PI researcher CC2608
@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0) <?php // preparation $researchers_array = array(); foreach ($related['researchers']['docs'] as $col) { $col['display_relationship'] = str_replace("Participant, ","", $col['display_relationship']); $col['display_relationship'] = str_replace(", Participant","", $col['display_relationship']); $researchers_array[$col['display_relationship']][] = $col; } $displayNum = 0; ?> <p> <strong>Researchers: </strong> @foreach($researchers_array as $relation=>$researchers) @foreach($researchers as $key=>$col) <?php $displayNum++; ?> <a href="{{ base_url() }}{{$col['to_slug']}}/{{$col['to_id']}}" title="{{ $col['to_title'] }}" class="ro_preview" tip="{{ $col['display_description'] }}" ro_id="{{ $col['to_id'] }}"> {{$col['to_title']}} </a> @if($relation!="Participant") ({{ $relation }}) @endif @if($displayNum<$related['researchers']['count']) ,&nbsp; @endif @endforeach @endforeach @if($related['researchers']['count'] > 5) <br> <a href="{{ $related['researchers']['searchUrl'] }}">View all {{ $related['researchers']['count'] }} related researchers</a> @endif </p> @endif
@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0) <?php // preparation $researchers_array = array(); foreach ($related['researchers']['docs'] as $col) { $researchers_array[$col['display_relationship']][] = $col; } ?> <p> <strong>Researchers: </strong> @foreach($researchers_array as $relation=>$researchers) @foreach($researchers as $key=>$col) <a href="{{ base_url() }}{{$col['to_slug']}}/{{$col['to_id']}}" title="{{ $col['to_title'] }}" class="ro_preview" tip="{{ $col['display_description'] }}" ro_id="{{ $col['to_id'] }}"> {{$col['to_title']}} </a> @if($key!=sizeof($researchers)-1) ,&nbsp; @endif @endforeach ({{ $relation }}) @endforeach @if($related['researchers']['count'] > 5) <br> <a href="{{ $related['researchers']['searchUrl'] }}">View all {{ $related['researchers']['count'] }} related researchers</a> @endif </p> @endif
Fix - No isAdmin function
<div class="navigation"> <div class="ui list"> <div class="mobile"><a href="javascript:void(0);" class="active"><i class="sidebar icon"></i></a></div> <div><a href="{{ route('dashboard.index') }}" class="{{ Request::is('dashboard*') || Request::is('check*') ? 'active' : null }}">Checks</a></div> <div><a href="{{ route('partner.index') }}" class="{{ Request::is('partner*') ? 'active' : null }}">Partner/innen</a></div> <div><a href="{{ route('tags.index') }}" class="{{ Request::is('tags*') ? 'active' : null }}">Schlagwörter</a></div> <!-- topnavigation - responsive --> <div><a href="{{ route('profile.index') }}" class="{{ Request::is('profile*') ? 'active' : null }} topnavigation">{{ Auth::user()->name }}</a></div> <div><a href="{{ Config::get('help.support') }}" class="topnavigation" target="_blank">Hilfe/FAQ</a></div> <div> <form action="{{ route('logout') }}" method="POST" class=topnavigation"> {{ csrf_field() }} <a href="javascript:void(0)" onclick="$(this).closest('form').submit()" class="topnavigation">Abmelden</a> </form> </div> <!-- end - topnavigation - responsive --> </div> </div>
<div class="navigation"> <div class="ui list"> <div class="mobile"><a href="javascript:void(0);" class="active"><i class="sidebar icon"></i></a></div> <div><a href="{{ route('dashboard.index') }}" class="{{ Request::is('dashboard*') || Request::is('check*') ? 'active' : null }}">Checks</a></div> <div><a href="{{ route('partner.index') }}" class="{{ Request::is('partner*') ? 'active' : null }}">Partner/innen</a></div> <div><a href="{{ route('tags.index') }}" class="{{ Request::is('tags*') ? 'active' : null }}">Schlagwörter</a></div> @if(Auth::user()->isAdmin()) <div><a href="{{ route('admin.users.index') }}" class="{{ Request::is('admin*') ? 'active' : null }}">Administration</a></div> @endif <!-- topnavigation - responsive --> <div><a href="{{ route('profile.index') }}" class="{{ Request::is('profile*') ? 'active' : null }} topnavigation">{{ Auth::user()->name }}</a></div> <div><a href="{{ Config::get('help.support') }}" class="topnavigation" target="_blank">Hilfe/FAQ</a></div> <div> <form action="{{ route('logout') }}" method="POST" class=topnavigation"> {{ csrf_field() }} <a href="javascript:void(0)" onclick="$(this).closest('form').submit()" class="topnavigation">Abmelden</a> </form> </div> <!-- end - topnavigation - responsive --> </div> </div>
Support for symmetrization of DIRECTIVE and REFERENCE. See the 1.20 Parser.jjt PR: Obtained from: Submitted by: Reviewed by: git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@73570 13f79535-47bb-0310-9956-ffa450edef68
/* Generated By:JJTree: Do not edit this line. ASTText.java */ package org.apache.velocity.runtime.parser.node; import java.io.Writer; import java.io.IOException; import org.apache.velocity.Context; import org.apache.velocity.runtime.parser.*; public class ASTText extends SimpleNode { private String text; public ASTText(int id) { super(id); } public ASTText(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object init(Context context, Object data) throws Exception { // text = NodeUtils.specialText(getFirstToken()) + // getFirstToken().image; /* * there is only one special case we care about now : if the specialToken leads with a $ * Everything else seems to be working right now */ text = getFirstToken().image; if (NodeUtils.specialText(getFirstToken()).startsWith("$")) text = "$" + text; else if ( NodeUtils.specialText(getFirstToken()).startsWith("#") ) text = "#" + text; return data; } public boolean render(Context context, Writer writer) throws IOException { writer.write(text); return true; } }
/* Generated By:JJTree: Do not edit this line. ASTText.java */ package org.apache.velocity.runtime.parser.node; import java.io.Writer; import java.io.IOException; import org.apache.velocity.Context; import org.apache.velocity.runtime.parser.*; public class ASTText extends SimpleNode { private String text; public ASTText(int id) { super(id); } public ASTText(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object init(Context context, Object data) throws Exception { // text = NodeUtils.specialText(getFirstToken()) + // getFirstToken().image; /* * there is only one special case we care about now : if the specialToken leads with a $ * Everything else seems to be working right now */ text = getFirstToken().image; if (NodeUtils.specialText(getFirstToken()).startsWith("$") ) text = "$" + text; return data; } public boolean render(Context context, Writer writer) throws IOException { writer.write(text); return true; } }
Send the charset with simpleBody.
/*! * Ext JS Connect * Copyright(c) 2010 Ext JS, Inc. * MIT Licensed */ /** * Module dependencies. */ var http = require('http'), Buffer = require('buffer').Buffer; var resProto = http.ServerResponse.prototype; /** * Respond with custom status code * if the message is a non-buffer object, send it as JSON * otherwise send it as text/plain. * defaultType can override the text/plain mime. * * @param {Number} code * @param message * @param {String} defaultType * @api public */ resProto.simpleBody = function(code, message, extraHeaders) { var length; var encoding; var type = "text/plain; charset=utf8"; if (typeof message === 'object' && !(message instanceof Buffer)) { message = JSON.stringify(message); type = "application/json; charset=utf8"; } message = message || ""; length = message.length; if (typeof message === 'string') { length = Buffer.byteLength(message); encoding = "utf8"; } var headers = { "Content-Type": type, "Content-Length": length }; if (extraHeaders) { if (typeof extraHeaders === 'string') { headers["Content-Type"] = extraHeaders; } else { extraHeaders.forEach(function (value, key) { headers[key] = value; }); } } this.writeHead(code, headers); this.end(message, encoding); };
/*! * Ext JS Connect * Copyright(c) 2010 Ext JS, Inc. * MIT Licensed */ /** * Module dependencies. */ var http = require('http'), Buffer = require('buffer').Buffer; var resProto = http.ServerResponse.prototype; /** * Respond with custom status code * if the message is a non-buffer object, send it as JSON * otherwise send it as text/plain. * defaultType can override the text/plain mime. * * @param {Number} code * @param message * @param {String} defaultType * @api public */ resProto.simpleBody = function(code, message, extraHeaders) { var length; var encoding; var type = "text/plain"; if (typeof message === 'object' && !(message instanceof Buffer)) { message = JSON.stringify(message); type = "application/json"; } message = message || ""; length = message.length; if (typeof message === 'string') { length = Buffer.byteLength(message); encoding = "utf8"; } var headers = { "Content-Type": type, "Content-Length": length }; if (extraHeaders) { if (typeof extraHeaders === 'string') { headers["Content-Type"] = extraHeaders; } else { extraHeaders.forEach(function (value, key) { headers[key] = value; }); } } this.writeHead(code, headers); this.end(message, encoding); };
Add note describing array copy if discontiguous
import numpy as np def unique_rows(ar): """Remove repeated rows from a 2D array. Parameters ---------- ar : 2D np.ndarray The input array. Returns ------- ar_out : 2D np.ndarray A copy of the input array with repeated rows removed. Raises ------ ValueError : if `ar` is not two-dimensional. Notes ----- The function will generate a copy of `ar` if it is not C-contiguous, which will negatively affect performance for large input arrays. Examples -------- >>> ar = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], np.uint8) >>> aru = unique_rows(ar) array([[0, 1, 0], [1, 0, 1]], dtype=uint8) """ if ar.ndim != 2: raise ValueError("unique_rows() only makes sense for 2D arrays, " "got %dd" % ar.ndim) # the view in the next line only works if the array is C-contiguous ar = np.ascontiguousarray(ar) # np.unique() finds identical items in a raveled array. To make it # see each row as a single item, we create a view of each row as a # byte string of length itemsize times number of columns in `ar` ar_row_view = ar.view('|S%d' % (ar.itemsize * ar.shape[1])) _, unique_row_indices = np.unique(ar_row_view, return_index=True) ar_out = ar[unique_row_indices] return ar_out
import numpy as np def unique_rows(ar): """Remove repeated rows from a 2D array. Parameters ---------- ar : 2D np.ndarray The input array. Returns ------- ar_out : 2D np.ndarray A copy of the input array with repeated rows removed. Raises ------ ValueError : if `ar` is not two-dimensional. Examples -------- >>> ar = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]], np.uint8) >>> aru = unique_rows(ar) array([[0, 1, 0], [1, 0, 1]], dtype=uint8) """ if ar.ndim != 2: raise ValueError("unique_rows() only makes sense for 2D arrays, " "got %dd" % ar.ndim) # the view in the next line only works if the array is C-contiguous ar = np.ascontiguousarray(ar) # np.unique() finds identical items in a raveled array. To make it # see each row as a single item, we create a view of each row as a # byte string of length itemsize times number of columns in `ar` ar_row_view = ar.view('|S%d' % (ar.itemsize * ar.shape[1])) _, unique_row_indices = np.unique(ar_row_view, return_index=True) ar_out = ar[unique_row_indices] return ar_out
Update router metric to Histogram. Use toggleable service label for router metric. Bug: T238658 Bug: T247820
'use strict'; function emitMetric(hyper, req, res, specInfo, startTime) { let statusCode = 'unknown'; if (res && res.status) { statusCode = res.status; } hyper.metrics.makeMetric({ type: 'Histogram', name: 'router', prometheus: { name: 'hyperswitch_router_duration_seconds', help: 'hyperswitch router duration', staticLabels: hyper.metrics.getServiceLabel(), buckets: [0.01, 0.05, 0.1, 0.3, 1] }, labels: { names: ['request_class', 'path', 'method', 'status'], omitLabelNames: true } }).endTiming(startTime, [hyper.requestClass, // Remove the /{domain}/ prefix, as it's not very useful in stats specInfo.path.replace(/\/[^/]+\//, ''), req.method.toUpperCase(), statusCode]); } module.exports = (hyper, req, next, options, specInfo) => { if (!hyper.metrics) { return next(hyper, req); } // Start timer const startTime = Date.now(); return next(hyper, req).then((res) => { // Record request metrics & log emitMetric(hyper, req, res, specInfo, startTime); return res; }, (err) => { emitMetric(hyper, req, err, specInfo, startTime); throw err; }); };
'use strict'; function emitMetric(hyper, req, res, specInfo, startTime) { let statusCode = 'unknown'; if (res && res.status) { statusCode = res.status; } hyper.metrics.makeMetric({ type: 'Gauge', name: 'router', prometheus: { name: 'hyperswitch_router_duration_seconds', help: 'hyperswitch router duration', staticLabels: { service: hyper.metrics.getServiceName() } }, labels: { names: ['request_class', 'path', 'method', 'status'], omitLabelNames: true } }).endTiming(startTime, [hyper.requestClass, // Remove the /{domain}/ prefix, as it's not very useful in stats specInfo.path.replace(/\/[^/]+\//, ''), req.method.toUpperCase(), statusCode]); } module.exports = (hyper, req, next, options, specInfo) => { if (!hyper.metrics) { return next(hyper, req); } // Start timer const startTime = Date.now(); return next(hyper, req).then((res) => { // Record request metrics & log emitMetric(hyper, req, res, specInfo, startTime); return res; }, (err) => { emitMetric(hyper, req, err, specInfo, startTime); throw err; }); };
Add neutron client without test
""" OpenstackDriver for Network based on NetworkDriver """ from neutronclient.v2_0 import client from network_driver import NetworkDriver class OpenstackNetWorkDriver(NetworkDriver): """docstring for OpenstackNetWorkDriver""" def __init__(self, auth_url, project_name, username, password, **kargs): super(OpenstackNetWorkDriver, self).__init__() self.provider = "OPENSTACK" self.auth_url = auth_url self.project_name = project_name self.username = username self.password = password self.driver_name = kargs.pop('driver_name', 'default') self._setup() def _setup(self): self.client = client.Client( username=self.username, password=self.password, project_name=self.project_name, auth_url=self.auth_url ) def create(self, network): return self.client.create_network({'network': network}) def show(self, network_id): return self.client.show_network(network_id) def list(self, retrieve_all=True, **kargs): return self.client.list_networks(retrieve_all, **kargs) def update(self, network_id, network): return self.client.update_network(network_id, {'network': network}) def delete(self, network_id): return self.client.delete_network(network_id)
""" OpenstackDriver for Network based on NetworkDriver """ from neutronclient.v2_0 import client from network_driver import NetworkDriver class OpenstackNetWorkDriver(NetworkDriver): """docstring for OpenstackNetWorkDriver""" def __init__(self, auth_url, project_name, username, password, user_domain_name=None, project_domain_name=None, driver_name=None): super(OpenstackNetWorkDriver, self).__init__() self.provider = "OPENSTACK" self.auth_url = auth_url self.project_domain_name = project_domain_name self.user_domain_name = user_domain_name self.project_name = project_name self.username = username self.password = password if driver_name: self.driver_name = driver_name else: self.driver_name = "default" self._setup() def _setup(self): self.client = client.Client( username=self.username, password=self.password, tenant_name=self.project_name, auth_url=self.auth_url ) def create(self): raise NotImplementedError def show(self): raise NotImplementedError def list(self): raise NotImplementedError def update(self): raise NotImplementedError def delete(self): raise NotImplementedError
Allow the package to be built without Sphinx being required.
import os from distutils.core import setup try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} except ImportError: print "Sphinx not installed--needed to build documentation" # default cmdclass to None to avoid cmdclass = {} import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass=cmdclass, )
import os from distutils.core import setup from sphinx.setup_command import BuildDoc import django_assets def find_packages(root): # so we don't depend on setuptools; from the Storm ORM setup.py packages = [] for directory, subdirectories, files in os.walk(root): if '__init__.py' in files: packages.append(directory.replace(os.sep, '.')) return packages setup( name = 'django-assets', version=".".join(map(str, django_assets.__version__)), description = 'Media asset management for the Django web framework.', long_description = 'Merges, minifies and compresses Javascript and ' 'CSS files, supporting a variety of different filters, including ' 'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting ' 'in CSS files.', author = 'Michael Elsdoerfer', author_email = '[email protected]', license = 'BSD', url = 'http://launchpad.net/django-assets', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], packages = find_packages('django_assets'), cmdclass={'build_sphinx': BuildDoc}, )
Remove Input in favour of Request
<?php namespace Forma; class Helpers { public static function url($string) { if (static::isLaravel()) { return \URL::to($string); } return $string; } public static function hasLang($string) { if (static::isLaravel()) { return \Lang::has($string); } return false; } public static function lang($string) { if (static::isLaravel()) { return \Lang::get($string); } return $string; } public static function input($string) { if (static::isLaravel()) { return \Request::get($string); } return isset($_REQUEST[$string]) ? $_REQUEST[$string] : false; } public static function inputOld($string) { if (static::isLaravel()) { return \Request::old($string); } return false; } public static function isLaravel() { return class_exists('Illuminate\Foundation\Application'); } }
<?php namespace Forma; class Helpers { public static function url($string) { if (static::isLaravel()) { return \URL::to($string); } return $string; } public static function hasLang($string) { if (static::isLaravel()) { return \Lang::has($string); } return false; } public static function lang($string) { if (static::isLaravel()) { return \Lang::get($string); } return $string; } public static function input($string) { if (static::isLaravel()) { return \Input::get($string); } return isset($_REQUEST[$string]) ? $_REQUEST[$string] : false; } public static function inputOld($string) { if (static::isLaravel()) { return \Input::old($string); } return false; } public static function isLaravel() { return class_exists('Illuminate\Foundation\Application'); } }
Use correct method for broadCast
var Promise = require('bluebird'), dbUtils = require('utils/database'), socketUtils = require('utils/socket'); module.exports = { all : All, add : Add, rename : Rename, delete : Delete }; function All(request,reply) { dbUtils.list() .then(function(data){ reply.data = data; reply.next(); socketUtils.allDbInfo(); }) .catch(function(err){ reply.next(err); }) } function Add(request,reply) { reply('Successfully started db creation'); dbUtils.connect(request.payload.database) .then(function(){ return dbUtils.initDB(request.payload.database); }) .then(function(){ socketUtils.broadCast('db-create',{db_name : request.payload.database, stats : {}}); return dbUtils.dbInfo(request.payload.database); }) .then(function(data){ data.verified = true; data.name = request.payload.database; socketUtils.broadCast('db-info',data); }); } function Rename(request,reply) { } function Delete(request,reply) { var db = dbUtils.getDb(); db[request.query.database].dropDatabase(); db[request.query.database] = null; setTimeout(function(){ socketUtils.broadCast('db-delete',request.query.database); },5000); reply.next(); }
var Promise = require('bluebird'), dbUtils = require('utils/database'), socketUtils = require('utils/socket'); module.exports = { all : All, add : Add, rename : Rename, delete : Delete }; function All(request,reply) { dbUtils.list() .then(function(data){ reply.data = data; reply.next(); socketUtils.allDbInfo(); }) .catch(function(err){ reply.next(err); }) } function Add(request,reply) { reply('Successfully started db creation'); dbUtils.connect(request.payload.database) .then(function(){ return dbUtils.initDB(request.payload.database); }) .then(function(){ socketUtils.broadCast('db-create',{db_name : request.payload.database, stats : {}}); return dbUtils.dbInfo(request.payload.database); }) .then(function(data){ data.verified = true; data.name = request.payload.database; socketUtils.broadCast('db-info',data); }); } function Rename(request,reply) { } function Delete(request,reply) { var db = dbUtils.getDb(); db[request.query.database].dropDatabase(); db[request.query.database] = null; setTimeout(function(){ socketUtils.broadcast('db-delete',request.query.database); },5000); reply.next(); }
Add tags - that was too easy
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'description': {'type': 'string'}, 'tags': {'type': 'array'}, }, 'additionalProperties': False, } def __init__(self, id=None, name=None, description=None, tags=None): self.id = id or str(uuid.uuid4()) self.name = name self.description = description self.tags = tags or [] @classmethod def from_dict(self, data): self.validate(data) return Change(**data) def to_dict(self): def _generate_set_attributes(): for k in Change.schema['properties'].keys(): val = getattr(self, k) if val is not None: yield (k, val) return dict(_generate_set_attributes()) def __str__(self): return "<Change id=%s name=%s>" % (self.id, self.name) @classmethod def validate(cls, data): try: jsonschema.validate(data, cls.schema) except jsonschema.ValidationError as exc: raise changeling.exception.ValidationError(exc) def is_valid(self): try: self.validate(self.to_dict()) except changeling.exception.ValidationError: return False else: return True
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'description': {'type': 'string'}, }, 'additionalProperties': False, } def __init__(self, id=None, name=None, description=None): self.id = id or str(uuid.uuid4()) self.name = name self.description = description @classmethod def from_dict(self, data): self.validate(data) return Change(**data) def to_dict(self): def _generate_set_attributes(): for k in Change.schema['properties'].keys(): val = getattr(self, k) if val is not None: yield (k, val) return dict(_generate_set_attributes()) def __str__(self): return "<Change id=%s name=%s>" % (self.id, self.name) @classmethod def validate(cls, data): try: jsonschema.validate(data, cls.schema) except jsonschema.ValidationError as exc: raise changeling.exception.ValidationError(exc) def is_valid(self): try: self.validate(self.to_dict()) except changeling.exception.ValidationError: return False else: return True
Raise a `RuntimeError` if the device cannot be opened
import threading from robotd.native import _cvcapture class CaptureDevice(object): def __init__(self, path=None): if path is not None: argument_c = _cvcapture.ffi.new( 'char[]', path.encode('utf-8'), ) else: argument_c = _cvcapture.ffi.NULL self.instance = _cvcapture.lib.cvopen(argument_c) if self.instance == _cvcapture.ffi.NULL: raise RuntimeError("Unable to open capture device") self.lock = threading.Lock() def capture(self, width, height): if self.instance is None: raise RuntimeError("capture device is closed") capture_buffer = _cvcapture.ffi.new( 'uint8_t[{}]'.format(width * height), ) with self.lock: status = _cvcapture.lib.cvcapture( self.instance, capture_buffer, width, height, ) if status == 0: raise RuntimeError("cvcapture() failed") return bytes(_cvcapture.ffi.buffer(capture_buffer)) def __enter__(self): return self def __exit__(self, exc_value, exc_type, exc_traceback): self.close() def close(self): if self.instance is not None: with self.lock: _cvcapture.lib.cvclose(self.instance) self.instance = None __del__ = close
import threading from robotd.native import _cvcapture class CaptureDevice(object): def __init__(self, path=None): if path is not None: argument_c = _cvcapture.ffi.new( 'char[]', path.encode('utf-8'), ) else: argument_c = _cvcapture.ffi.NULL self.instance = _cvcapture.lib.cvopen(argument_c) self.lock = threading.Lock() def capture(self, width, height): if self.instance is None: raise RuntimeError("capture device is closed") capture_buffer = _cvcapture.ffi.new( 'uint8_t[{}]'.format(width * height), ) with self.lock: status = _cvcapture.lib.cvcapture( self.instance, capture_buffer, width, height, ) if status == 0: raise RuntimeError("cvcapture() failed") return bytes(_cvcapture.ffi.buffer(capture_buffer)) def __enter__(self): return self def __exit__(self, exc_value, exc_type, exc_traceback): self.close() def close(self): if self.instance is not None: with self.lock: _cvcapture.lib.cvclose(self.instance) self.instance = None __del__ = close
BB-7975: Add to configuration select with segment lists - cs fix
<?php namespace Oro\Bundle\SegmentBundle\Form\Type; use Doctrine\Common\Persistence\ManagerRegistry; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\OptionsResolver\OptionsResolver; class SegmentChoiceType extends AbstractType { /** @var ManagerRegistry */ protected $registry; /** @var string */ protected $entityClass; /** * @param ManagerRegistry $registry * @param string $entityClass */ public function __construct(ManagerRegistry $registry, $entityClass) { $this->registry = $registry; $this->entityClass = $entityClass; } /** * {@inheritDoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('placeholder', 'oro.segment.form.segment_choice.placeholder'); $resolver->setRequired('entityClass'); $resolver->setNormalizer( 'choices', function (OptionsResolver $options) { $repo = $this->registry->getManagerForClass($this->entityClass)->getRepository($this->entityClass); return $repo->findByEntity($options['entityClass']); } ); $resolver->setAllowedTypes('entityClass', ['null', 'string']); } /** * {@inheritDoc} */ public function getParent() { return ChoiceType::class; } }
<?php namespace Oro\Bundle\SegmentBundle\Form\Type; use Doctrine\Common\Persistence\ManagerRegistry; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\OptionsResolver\OptionsResolver; class SegmentChoiceType extends AbstractType { /** @var ManagerRegistry */ protected $registry; /** @var string */ protected $entityClass; /** * SegmentNameChoiceType constructor. * @param ManagerRegistry $registry * @param string $entityClass */ public function __construct(ManagerRegistry $registry, $entityClass) { $this->registry = $registry; $this->entityClass = $entityClass; } /** * {@inheritDoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('placeholder', 'oro.segment.form.segment_choice.placeholder'); $resolver->setRequired('entityClass'); $resolver->setNormalizer( 'choices', function (OptionsResolver $options) { $repo = $this->registry->getManagerForClass($this->entityClass)->getRepository($this->entityClass); return $repo->findByEntity($options['entityClass']); } ); $resolver->setAllowedTypes('entityClass', ['null', 'string']); } /** * {@inheritDoc} */ public function getParent() { return ChoiceType::class; } }
Add comment of things to do
/* * Copyright 2016-2018 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.talsmasoftware.umldoclet; import nl.talsmasoftware.umldoclet.javadoc.DocletConfig; import nl.talsmasoftware.umldoclet.uml.UMLDiagram; import org.junit.Test; import java.util.spi.ToolProvider; public class UMLDocletTest { ToolProvider javadoc = ToolProvider.findFirst("javadoc").get(); @Test public void testDoclet() { javadoc.run(System.out, System.err, "-sourcepath", "src/main/java", "-d", "target/doclet-test", "-doclet", UMLDoclet.class.getName(), // Configuration.class.getPackageName(), UMLDoclet.class.getPackageName(), DocletConfig.class.getPackageName(), UMLDiagram.class.getPackageName() ); // TODO Actually test things! } }
/* * Copyright 2016-2018 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.talsmasoftware.umldoclet; import nl.talsmasoftware.umldoclet.javadoc.DocletConfig; import nl.talsmasoftware.umldoclet.uml.UMLDiagram; import org.junit.Test; import java.util.spi.ToolProvider; public class UMLDocletTest { ToolProvider javadoc = ToolProvider.findFirst("javadoc").get(); @Test public void testDoclet() { javadoc.run(System.out, System.err, "-sourcepath", "src/main/java", "-d", "target/doclet-test", "-doclet", UMLDoclet.class.getName(), // Configuration.class.getPackageName(), UMLDoclet.class.getPackageName(), DocletConfig.class.getPackageName(), UMLDiagram.class.getPackageName() ); } }
Add y log option and title offset
import matplotlib.pyplot as plt #class RgChart(object): #__metaclass__ = ABCMeta class RgChart(object): TITLE_Y_OFFSET = 1.08 def with_grids(self): self._ax.xaxis.grid(True) self._ax.yaxis.grid(True) return self def save_as(self, filename): self._create_plot() self._fig.savefig(filename) plt.close(self._fig) # close on save to avoid memory issues def with_ygrid(self): self._ax.yaxis.grid(True) return self def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET): if title is None: plt.title(self._title, y = y_offset) else: plt.title(title, y = y_offset) return self def with_xlabel(self, xlabel = None): if xlabel is None: plt.xlabel(self._xlabel) else: plt.xlabel(xlabel) return self def with_ylabel(self, ylabel = None): if ylabel is None: plt.ylabel(self._ylabel) else: plt.ylabel(ylabel) return self def with_ylog(self): self._ax.set_yscale('log') return self def with_ylim(self, lim): self._ax.set_ylim(lim) return self def wo_xticks(self): self._ax.get_xaxis().set_ticks([]) return self def wo_yticks(self): self._ax.get_yaxis().set_ticks([]) return self def _create_plot(self): pass
import matplotlib.pyplot as plt #class RgChart(object): #__metaclass__ = ABCMeta class RgChart(object): def with_grids(self): self._ax.xaxis.grid(True) self._ax.yaxis.grid(True) return self def save_as(self, filename): self._create_plot() self._fig.savefig(filename) plt.close(self._fig) # close on save to avoid memory issues def with_ygrid(self): self._ax.yaxis.grid(True) return self def with_title(self, title = None): if title is None: plt.title(self._title) else: plt.title(title) return self def with_xlabel(self, xlabel = None): if xlabel is None: plt.xlabel(self._xlabel) else: plt.xlabel(xlabel) return self def with_ylabel(self, ylabel = None): if ylabel is None: plt.ylabel(self._ylabel) else: plt.ylabel(ylabel) return self def with_ylim(self, lim): self._ax.set_ylim(lim) return self def wo_xticks(self): self._ax.get_xaxis().set_ticks([]) return self def wo_yticks(self): self._ax.get_yaxis().set_ticks([]) return self def _create_plot(self): pass
Set user as the default role for new accounts
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\User; use App\Providers\RouteServiceProvider; use Illuminate\Auth\Events\Registered; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Inertia\Inertia; class RegisteredUserController extends Controller { /** * Display the registration view. * * @return \Illuminate\View\View */ public function create() { return Inertia::render('Auth/Register', [ 'status' => session('errors') ? session('errors')->default->messages() : false ]); } /** * Handle an incoming registration request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse * * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|confirmed|min:8', ]); Auth::login($user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ])); $user->assignRole('user'); event(new Registered($user)); return redirect(RouteServiceProvider::HOME); } }
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\User; use App\Providers\RouteServiceProvider; use Illuminate\Auth\Events\Registered; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Inertia\Inertia; class RegisteredUserController extends Controller { /** * Display the registration view. * * @return \Illuminate\View\View */ public function create() { return Inertia::render('Auth/Register', [ 'status' => session('errors') ? session('errors')->default->messages() : false ]); } /** * Handle an incoming registration request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse * * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|confirmed|min:8', ]); Auth::login($user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ])); event(new Registered($user)); return redirect(RouteServiceProvider::HOME); } }
Use new Date() in place of Date.now() to avoid any difference of behavior when using datejs
// // Server side activity detection for the session timeout // // Meteor settings: // - staleSessionInactivityTimeout: the amount of time (in ms) after which, if no activity is noticed, a session will be considered stale // - staleSessionPurgeInterval: interval (in ms) at which stale sessions are purged i.e. found and forcibly logged out // var staleSessionPurgeInterval = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionPurgeInterval || (1*60*1000); // 1min var inactivityTimeout = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionInactivityTimeout || (30*60*1000); // 30mins // // provide a user activity heartbeat method which stamps the user record with a timestamp of the last // received activity heartbeat. // Meteor.methods({ heartbeat: function(options) { if (!this.userId) { return; } var user = Meteor.users.findOne(this.userId); if (user) { Meteor.users.update(user._id, {$set: {heartbeat: new Date()}}); } } }); // // periodically purge any stale sessions, removing their login tokens and clearing out the stale heartbeat. // Meteor.setInterval(function() { var now = new Date(), overdueTimestamp = new Date(now-inactivityTimeout); Meteor.users.update({heartbeat: {$lt: overdueTimestamp}}, {$set: {'services.resume.loginTokens': []}, $unset: {heartbeat:1}}, {multi: true}); }, staleSessionPurgeInterval);
// // Server side activity detection for the session timeout // // Meteor settings: // - staleSessionInactivityTimeout: the amount of time (in ms) after which, if no activity is noticed, a session will be considered stale // - staleSessionPurgeInterval: interval (in ms) at which stale sessions are purged i.e. found and forcibly logged out // var staleSessionPurgeInterval = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionPurgeInterval || (1*60*1000); // 1min var inactivityTimeout = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionInactivityTimeout || (30*60*1000); // 30mins // // provide a user activity heartbeat method which stamps the user record with a timestamp of the last // received activity heartbeat. // Meteor.methods({ heartbeat: function(options) { if (!this.userId) { return; } var user = Meteor.users.findOne(this.userId); if (user) { Meteor.users.update(user._id, {$set: {heartbeat: Date.now()}}); } } }); // // periodically purge any stale sessions, removing their login tokens and clearing out the stale heartbeat. // Meteor.setInterval(function() { var now = new Date(), overdueTimestamp = new Date(now-inactivityTimeout); Meteor.users.update({heartbeat: {$lt: overdueTimestamp}}, {$set: {'services.resume.loginTokens': []}, $unset: {heartbeat:1}}, {multi: true}); }, staleSessionPurgeInterval);
Change dev status to beta, not pre-alpha There's no RC classifier, so beta looks like the closest one we can use.
#!/usr/bin/env python from setuptools import setup, find_packages with open('README.rst') as readme_file: README = readme_file.read() install_requires = [ 'click==6.6', 'botocore>=1.5.40,<2.0.0', 'typing==3.5.3.0', 'six>=1.10.0,<2.0.0', 'pip>=9,<10' ] setup( name='chalice', version='0.10.1', description="Microframework", long_description=README, author="James Saryerwinnie", author_email='[email protected]', url='https://github.com/jamesls/chalice', packages=find_packages(exclude=['tests']), install_requires=install_requires, license="Apache License 2.0", package_data={'chalice': ['*.json']}, include_package_data=True, zip_safe=False, keywords='chalice', entry_points={ 'console_scripts': [ 'chalice = chalice.cli:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
#!/usr/bin/env python from setuptools import setup, find_packages with open('README.rst') as readme_file: README = readme_file.read() install_requires = [ 'click==6.6', 'botocore>=1.5.40,<2.0.0', 'typing==3.5.3.0', 'six>=1.10.0,<2.0.0', 'pip>=9,<10' ] setup( name='chalice', version='0.10.1', description="Microframework", long_description=README, author="James Saryerwinnie", author_email='[email protected]', url='https://github.com/jamesls/chalice', packages=find_packages(exclude=['tests']), install_requires=install_requires, license="Apache License 2.0", package_data={'chalice': ['*.json']}, include_package_data=True, zip_safe=False, keywords='chalice', entry_points={ 'console_scripts': [ 'chalice = chalice.cli:main', ] }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
Add homepage to plugin details
<?php namespace PKleindienst\BlogSearch; use System\Classes\PluginBase; /** * blogSearch Plugin Information File */ class Plugin extends PluginBase { /** * @var array Plugin dependencies */ public $require = ['RainLab.Blog']; /** * Returns information about this plugin. * * @return array */ public function pluginDetails() { return [ 'name' => 'Blog Search', 'description' => 'Adds a search function to the blog', 'author' => 'Pascal Kleindienst', 'icon' => 'icon-search', 'homepage' => 'https://github.com/PascalKleindienst/october-blogsearch-extension' ]; } /** * @return array */ public function registerComponents() { return [ 'PKleindienst\BlogSearch\Components\SearchForm' => 'searchForm', 'PKleindienst\BlogSearch\Components\SearchResult' => 'searchResult' ]; } /** * Register new Twig variables * @return array */ public function registerMarkupTags() { // Check the translate plugin is installed if (class_exists('RainLab\Translate\Behaviors\TranslatableModel')) { return []; } return [ 'filters' => [ '_' => ['Lang', 'get'], '__' => ['Lang', 'choice'] ] ]; } }
<?php namespace PKleindienst\BlogSearch; use System\Classes\PluginBase; /** * blogSearch Plugin Information File */ class Plugin extends PluginBase { /** * @var array Plugin dependencies */ public $require = [ 'RainLab.Blog' ]; /** * Returns information about this plugin. * * @return array */ public function pluginDetails() { return [ 'name' => 'Blog Search', 'description' => 'Adds a search function to the blog', 'author' => 'Pascal Kleindienst', 'icon' => 'icon-search' ]; } /** * @return array */ public function registerComponents() { return [ 'PKleindienst\BlogSearch\Components\SearchForm' => 'searchForm', 'PKleindienst\BlogSearch\Components\SearchResult' => 'searchResult', ]; } /** * Register new Twig variables * @return array */ public function registerMarkupTags() { // Check the translate plugin is installed if (class_exists('RainLab\Translate\Behaviors\TranslatableModel')) { return []; } return [ 'filters' => [ '_' => ['Lang', 'get'], '__' => ['Lang', 'choice'], ] ]; } }
Refactor REST controller to use overall @RequestMapping
package com.elderstudios.controller; import com.elderstudios.domain.GuestBookEntry; import com.elderstudios.service.GuestBookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.persistence.criteria.CriteriaBuilder; import java.util.List; /** * Created by tony on 04/07/17. */ @RestController @RequestMapping ("/api") public class GuestBookRestController { //private static final String prefix = "api"; @Autowired private GuestBookService guestBookService; @GetMapping ("/comments") public List <GuestBookEntry> apiAllComments () { return this.guestBookService.findAllEntries (); } @GetMapping ("/find/{id}") public List <GuestBookEntry> apiCommentById (@PathVariable ("id") Integer id) { return this.guestBookService.getGuestBookEntryById (id); } @GetMapping ("/users") public List <String> apiGetDistinctUsers () { return this.guestBookService.findDistinctUsers (); } @GetMapping ("/comment_count") public Integer getNumberOfComments () { return this.guestBookService.getNumberOfComments (); } @GetMapping ("/average_length") public Double getAverageCommentLength () { return this.guestBookService.getAverageCommentLength (); } @GetMapping ("/longest_comment") public List <String> getLongestComment () { return this.guestBookService.getLongestComment (); } }
package com.elderstudios.controller; import com.elderstudios.domain.GuestBookEntry; import com.elderstudios.service.GuestBookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.persistence.criteria.CriteriaBuilder; import java.util.List; /** * Created by tony on 04/07/17. */ @RestController public class GuestBookRestController { private static final String prefix = "api"; @Autowired private GuestBookService guestBookService; @GetMapping (prefix + "/comments") public List <GuestBookEntry> apiAllComments () { return this.guestBookService.findAllEntries (); } @GetMapping (prefix + "/find/{id}") public List <GuestBookEntry> apiCommentById (@PathVariable ("id") Integer id) { return this.guestBookService.getGuestBookEntryById (id); } @GetMapping (prefix + "/users") public List <String> apiGetDistinctUsers () { return this.guestBookService.findDistinctUsers (); } @GetMapping (prefix + "/comment_count") public Integer getNumberOfComments () { return this.guestBookService.getNumberOfComments (); } @GetMapping (prefix + "/average_length") public Double getAverageCommentLength () { return this.guestBookService.getAverageCommentLength (); } @GetMapping (prefix + "/longest_comment") public List <String> getLongestComment () { return this.guestBookService.getLongestComment (); } }
Add module for conditional content
/* globals _ */ (function () { 'use strict'; moj.Modules.Conditional = { el: '.js-Conditional', init: function () { _.bindAll(this, 'render'); this.cacheEls(); this.bindEvents(); }, bindEvents: function () { this.$conditionals.on('change deselect', this.toggle); moj.Events.on('render', this.render); }, cacheEls: function () { this.$conditionals = $(this.el); }, render: function () { this.$conditionals.each(this.toggle); }, toggle: function (e) { var $el = $(this), $conditionalEl = $('#' + $el.data('conditionalEl')); // trigger a deselect event if a change event occured if (e.type === 'change') { $('input[name="' + $el.attr('name') + '"]').not($el).trigger('deselect'); } // if a conditional element has been set, run the checks if ($el.data('conditionalEl')) { $el.attr('aria-control', $el.data('conditionalEl')); // if checked show/hide the extra content if($el.is(':checked')){ $conditionalEl.show(); $conditionalEl.attr('aria-expanded', 'true').attr('aria-hidden', 'false'); } else { $conditionalEl.hide(); $conditionalEl.attr('aria-expanded', 'false').attr('aria-hidden', 'true'); } } } }; }());
(function () { 'use strict'; moj.Modules.Conditional = { el: '.js-Conditional', init: function () { var _this = this; this.cacheEls(); this.bindEvents(); this.$conditionals.each(function () { _this.toggleEl($(this)); }); }, bindEvents: function () { var _this = this; // set focused selector to parent label this.$conditionals .on('change', function () { _this.toggleEl($(this)); // trigger a deselect event $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); }) .on('deselect', function () { _this.toggleEl($(this)); }); }, cacheEls: function () { this.$conditionals = $(this.el); }, toggleEl: function (el) { var $el = el, $conditionalEl = $('#' + $el.data('conditionalEl')); if ($el.data('conditionalEl')) { $el.attr('aria-control', $el.data('conditionalEl')); if($el.is(':checked')){ $conditionalEl.show(); $conditionalEl.attr('aria-expanded', 'true').attr('aria-hidden', 'false'); } else { $conditionalEl.hide(); $conditionalEl.attr('aria-expanded', 'false').attr('aria-hidden', 'true'); } } } }; }());
Allow users to manually zoom in on mobile devices.
<!DOCTYPE html> <html lang="<?= LANG ?>"> <head> <title><?= PageTitle() ?></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="copyright" content="<?= T('copyright') ?>"> <meta name="description" content="<?= PageDescription() ?>"> <meta name="keywords" content="<?= PageKeywords() ?>"> <link rel="icon" type="image/x-icon" href="<?= URL('favicon.ico') ?>?"> <link rel="stylesheet" type="text/css" href="<?= URL('css/style.css') ?>"> <!-- TODO: Generate hreflang links for every language. --> <?php /* $langSites = [ 'https://www.vibrobox.com/' => ['x-default', 'en'], 'https://www.vibrobox.ru/' => ['ru', 'uk', 'kk'], 'https://www.vibrobox.by/' => ['be'], ]; ?> <?php foreach ($langSites as $url => $langs) : foreach ($langs as $lang) : ?> <link href="<?= $url ?>" hreflang="<?= $lang ?>" rel="alternate"> <?php endforeach; endforeach; */?> <?php foreach (PageCSS() as $url) : ?> <link rel="stylesheet" type="text/css" href="<?= $url ?>"> <?php endforeach; ?> <!-- TODO: Move JS scripts to the footer. --> <?php foreach (PageJS() as $url) : ?> <script defer type="text/javascript" src="<?= $url ?>"> <?php endforeach; ?> </head>
<!DOCTYPE html> <html lang="<?= LANG ?>"> <head> <title><?= PageTitle() ?></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <meta name="copyright" content="<?= T('copyright') ?>"> <meta name="description" content="<?= PageDescription() ?>"> <meta name="keywords" content="<?= PageKeywords() ?>"> <link rel="icon" type="image/x-icon" href="<?= URL('favicon.ico') ?>?"> <link rel="stylesheet" type="text/css" href="<?= URL('css/style.css') ?>"> <!-- TODO: Generate hreflang links for every language. --> <?php /* $langSites = [ 'https://www.vibrobox.com/' => ['x-default', 'en'], 'https://www.vibrobox.ru/' => ['ru', 'uk', 'kk'], 'https://www.vibrobox.by/' => ['be'], ]; ?> <?php foreach ($langSites as $url => $langs) : foreach ($langs as $lang) : ?> <link href="<?= $url ?>" hreflang="<?= $lang ?>" rel="alternate"> <?php endforeach; endforeach; */?> <?php foreach (PageCSS() as $url) : ?> <link rel="stylesheet" type="text/css" href="<?= $url ?>"> <?php endforeach; ?> <!-- TODO: Move JS scripts to the footer. --> <?php foreach (PageJS() as $url) : ?> <script defer type="text/javascript" src="<?= $url ?>"> <?php endforeach; ?> </head>
Drop type-hint for Response to support multiple Guzzle versions
<?php namespace Hub\Client\Common; use Hub\Client\Exception\BadRequestException; use Hub\Client\Exception\NotFoundException; use Hub\Client\Exception\NotAuthorizedException; use RuntimeException; class ErrorResponseHandler { public static function handle($response) { if ($response->getStatusCode() == 401) { throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed'); } $xml = $response->getBody(); $rootNode = @simplexml_load_string($xml); if ($rootNode) { if ($rootNode->getName()=='error') { switch ((string)$rootNode->status) { case 400: throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message); break; case 404: throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message); break; case 403: throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message); break; default: throw new RuntimeException( "Unsupported response status code returned: " . (string)$rootNode->status . ' / ' . (string)$rootNode->code ); break; } } throw new RuntimeException( "Failed to parse response. It's valid XML, but not the expected error root element" ); } throw new RuntimeException("Failed to parse response: " . $xml); } }
<?php namespace Hub\Client\Common; use Hub\Client\Exception\BadRequestException; use Hub\Client\Exception\NotFoundException; use Hub\Client\Exception\NotAuthorizedException; use GuzzleHttp\Psr7\Response; use RuntimeException; class ErrorResponseHandler { public static function handle(Response $response) { if ($response->getStatusCode() == 401) { throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed'); } $xml = $response->getBody(); $rootNode = @simplexml_load_string($xml); if ($rootNode) { if ($rootNode->getName()=='error') { switch ((string)$rootNode->status) { case 400: throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message); break; case 404: throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message); break; case 403: throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message); break; default: throw new RuntimeException( "Unsupported response status code returned: " . (string)$rootNode->status . ' / ' . (string)$rootNode->code ); break; } } throw new RuntimeException( "Failed to parse response. It's valid XML, but not the expected error root element" ); } throw new RuntimeException("Failed to parse response: " . $xml); } }
Add isset check to SQL Pending user
<?php namespace Auth; class SQLPendingUser extends PendingUser { private $hash; private $time; private $blob; private $table; public function __construct($data, $table = false) { $this->hash = $data['hash']; $this->time = new \DateTime($data['time']); $this->blob = json_decode($data['data']); $this->table = $table; } public function __get($propName) { if(is_array($this->blob->{$propName})) { return $this->blob->{$propName}[0]; } return $this->blob->{$propName}; } public function __set($propName, $value) { } public function __isset($propName) { return isset($this->block->{$propName}); } public function getHash() { return $this->hash; } public function getRegistrationTime() { return $this->time; } public function getPassword() { if(is_array($this->blob->password)) { return $this->blob->password[0]; } return $this->blob->password; } public function offsetGet($offset) { return $this->blob->$offset; } public function delete() { $this->table->delete(new \Data\Filter("hash eq '{$this->hash}'")); } }
<?php namespace Auth; class SQLPendingUser extends PendingUser { private $hash; private $time; private $blob; private $table; public function __construct($data, $table = false) { $this->hash = $data['hash']; $this->time = new \DateTime($data['time']); $this->blob = json_decode($data['data']); $this->table = $table; } public function __get($propName) { if(is_array($this->blob->{$propName})) { return $this->blob->{$propName}[0]; } return $this->blob->{$propName}; } public function __set($propName, $value) { } public function getHash() { return $this->hash; } public function getRegistrationTime() { return $this->time; } public function getPassword() { if(is_array($this->blob->password)) { return $this->blob->password[0]; } return $this->blob->password; } public function offsetGet($offset) { return $this->blob->$offset; } public function delete() { $this->table->delete(new \Data\Filter("hash eq '{$this->hash}'")); } }
fix: Use better help for --elb-subnet See also: PSOBAT-1359
"""Create DNS record.""" import argparse import logging from ..args import add_debug from ..consts import LOGGING_FORMAT from .create_dns import SpinnakerDns def main(): """Run newer stuffs.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) parser.add_argument("--app", help="The application name to create", required=True) parser.add_argument("--region", help="The region to create the security group", required=True) parser.add_argument("--env", help="The environment to create the security group", required=True) parser.add_argument("--elb-subnet", help="Subnetnet type, e.g. external, internal", required=True) args = parser.parse_args() logging.getLogger(__package__.split('.')[0]).setLevel(args.debug) log.debug('Parsed arguments: %s', args) # Dictionary containing application info. This is passed to the class for processing appinfo = { 'app': args.app, 'region': args.region, 'env': args.env, 'elb_subnet': args.elb_subnet } spinnakerapps = SpinnakerDns(app_info=appinfo) spinnakerapps.create_elb_dns() if __name__ == "__main__": main()
"""Create DNS record.""" import argparse import logging from ..args import add_debug from ..consts import LOGGING_FORMAT from .create_dns import SpinnakerDns def main(): """Run newer stuffs.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) parser.add_argument("--app", help="The application name to create", required=True) parser.add_argument("--region", help="The region to create the security group", required=True) parser.add_argument("--env", help="The environment to create the security group", required=True) parser.add_argument("--elb-subnet", help="The environment to create the security group", required=True) args = parser.parse_args() logging.getLogger(__package__.split('.')[0]).setLevel(args.debug) log.debug('Parsed arguments: %s', args) # Dictionary containing application info. This is passed to the class for processing appinfo = { 'app': args.app, 'region': args.region, 'env': args.env, 'elb_subnet': args.elb_subnet } spinnakerapps = SpinnakerDns(app_info=appinfo) spinnakerapps.create_elb_dns() if __name__ == "__main__": main()
Add only the value to a members extra info Signed-off-by: Gawain Lynch <[email protected]>
<?php namespace Bolt\Extension\Bolt\Members; use Bolt\Extension\Bolt\ClientLogin\ClientRecords; use Bolt\Extension\Bolt\ClientLogin\Session; /** * Members Profiles * * @author Gawain Lynch <[email protected]> */ class MembersProfiles { public function __construct(\Bolt\Application $app) { $this->app = $app; } public function getMembersProfiles($userid) { $records = new MembersRecords($this->app); $member = $records->getMember('id', $userid); if ($member) { $member['avatar'] = $records->getMemberMetaValue($userid, 'avatar'); $member['location'] = $records->getMemberMetaValue($userid, 'location'); return $member; } return $this->getDeletedUser(); } private function getDeletedUser() { return array( 'id' => -1, 'username' => 'deleted', 'email' => '', 'displayname' => 'Deleted User', 'lastseen' => '0000-00-00 00:00:00', 'lastip' => '', 'enabled' => 0, 'roles' => '', 'avatar' => 'http://placehold.it/350x150&text=Deleted+User', 'location' => 'Unknown' ); } }
<?php namespace Bolt\Extension\Bolt\Members; use Bolt\Extension\Bolt\ClientLogin\ClientRecords; use Bolt\Extension\Bolt\ClientLogin\Session; /** * Members Profiles * * @author Gawain Lynch <[email protected]> */ class MembersProfiles { public function __construct(\Bolt\Application $app) { $this->app = $app; } public function getMembersProfiles($userid) { $records = new MembersRecords($this->app); $member = $records->getMember('id', $userid); if ($member) { $member['avatar'] = $records->getMemberMeta($userid, 'avatar'); $member['location'] = $records->getMemberMeta($userid, 'location'); return $member; } return $this->getDeletedUser(); } private function getDeletedUser() { return array( 'id' => -1, 'username' => 'deleted', 'email' => '', 'displayname' => 'Deleted User', 'lastseen' => '0000-00-00 00:00:00', 'lastip' => '', 'enabled' => 0, 'roles' => '', 'avatar' => 'http://placehold.it/350x150&text=Deleted+User', 'location' => 'Unknown' ); } }
Read requirements from the .txt file
#! /usr/bin/env python from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import os import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings') class PyTest(TestCommand): user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')] test_args = [] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) with open('requirements.txt', 'r') as req_file: requirements = req_file.readlines() setup( name='saleor', author='Mirumee Software', author_email='[email protected]', description="A fork'n'play e-commerce in Django", license='BSD', version='0.1.0a0', url='http://getsaleor.com/', packages=find_packages(), include_package_data=True, install_requires=requirements, cmdclass={ 'test': PyTest}, entry_points={ 'console_scripts': ['saleor = saleor:manage']})
#! /usr/bin/env python from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import os import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings') class PyTest(TestCommand): user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')] test_args = [] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) with open('requirements.in', 'r') as req_file: requirements = req_file.readlines() setup( name='saleor', author='Mirumee Software', author_email='[email protected]', description="A fork'n'play e-commerce in Django", license='BSD', version='0.1.0a0', url='http://getsaleor.com/', packages=find_packages(), include_package_data=True, install_requires=requirements, cmdclass={ 'test': PyTest}, entry_points={ 'console_scripts': ['saleor = saleor:manage']})
Make sure a transaction completes exceptionally if it fails to start
package peergos.shared.storage; import peergos.shared.crypto.hash.*; import java.util.concurrent.*; import java.util.function.*; public class Transaction { /** Run a series of operations under a transaction, ensuring that it is closed correctly * * @param owner * @param processor * @param ipfs * @param <V> * @return */ public static <V> CompletableFuture<V> run(PublicKeyHash owner, Function<TransactionId, CompletableFuture<V>> processor, ContentAddressedStorage ipfs) { CompletableFuture<V> res = new CompletableFuture<>(); ipfs.startTransaction(owner).thenCompose(tid -> processor.apply(tid) .thenCompose(v -> ipfs.closeTransaction(owner, tid) .thenApply(x -> res.complete(v))) .exceptionally(t -> { ipfs.closeTransaction(owner, tid) .thenApply(x -> res.completeExceptionally(t)) .exceptionally(e -> res.completeExceptionally(e)); return false; })).exceptionally(e -> res.completeExceptionally(e)); return res; } }
package peergos.shared.storage; import peergos.shared.crypto.hash.*; import java.util.concurrent.*; import java.util.function.*; public class Transaction { /** Run a series of operations under a transaction, ensuring that it is closed correctly * * @param owner * @param processor * @param ipfs * @param <V> * @return */ public static <V> CompletableFuture<V> run(PublicKeyHash owner, Function<TransactionId, CompletableFuture<V>> processor, ContentAddressedStorage ipfs) { CompletableFuture<V> res = new CompletableFuture<>(); ipfs.startTransaction(owner).thenCompose(tid -> processor.apply(tid) .thenCompose(v -> ipfs.closeTransaction(owner, tid) .thenApply(x -> res.complete(v))) .exceptionally(t -> { ipfs.closeTransaction(owner, tid) .thenApply(x -> res.completeExceptionally(t)) .exceptionally(e -> res.completeExceptionally(e)); return false; })); return res; } }
Return a comma-separated string of all ips in the X-Forwarded-For header. This mimics the behavior of the sample app https://cryptic-ridge-9197.herokuapp.com/api/whoami/ when the user supplies its own header.
'use strict'; const express = require('express'); const app = express(); // Settings app.enable('trust proxy'); app.set('json spaces', 1); // Static files app.use(express.static(process.cwd() + '/public')); app.route('/') .get((req, res) => { res.sendFile(process.cwd() + '/public/index.html'); }); app.route('/api/whoami') .get((req, res) => { let result = {}; result.ipaddress = req.ips.join(', '); // Mimic behavior of sample app. // We take the first language in the 'accept-language' header as the language. try { result.language = req.get('accept-language').split(',')[0]; } catch (e) { // We couldn't detect the language. Possibly because the header is not set. console.log(e); } // We define the software to be the content of the first parenthesis in the user-agent header. try { result.software = req.get('user-agent').match(/\((.*?)\)/)[1]; } catch (e) { // The header wasn't in the format we assumed. Return the whole user-agent header instead. console.log(e); result.software = req.get('user-agent'); } res.json(result); }); const port = process.env.PORT || 8080; app.listen(port, function() { console.log('Node.js listening on port ' + port + '...'); });
'use strict'; const express = require('express'); const app = express(); // Settings app.enable('trust proxy'); app.set('json spaces', 1); // Static files app.use(express.static(process.cwd() + '/public')); app.route('/') .get((req, res) => { res.sendFile(process.cwd() + '/public/index.html'); }); app.route('/api/whoami') .get((req, res) => { let result = {}; result.ipaddress = req.ip; // We take the first language in the 'accept-language' header as the language. try { result.language = req.get('accept-language').split(',')[0]; } catch (e) { // We couldn't detect the language. Possibly because the header is not set. console.log(e); } // We define the software to be the content of the first parenthesis in the user-agent header. try { result.software = req.get('user-agent').match(/\((.*?)\)/)[1]; } catch (e) { // The header wasn't in the format we assumed. Return the whole user-agent header instead. console.log(e); result.software = req.get('user-agent'); } res.json(result); }); const port = process.env.PORT || 8080; app.listen(port, function() { console.log('Node.js listening on port ' + port + '...'); });
Add correct protocol to the Pandas client @nicolajkirchhof Is this what you were talking about?
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' protocol = 'json' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(30)), index=pd.date_range(start='2014-11-16', periods=30, freq='H')) print("Create database: " + dbname) client.create_database(dbname) print("Write DataFrame") client.write_points(df, 'demo') print("Write DataFrame with Tags") client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'}) print("Read DataFrame") client.query("select * from demo") print("Delete database: " + dbname) client.delete_database(dbname) def parse_args(): parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname of InfluxDB http API') parser.add_argument('--port', type=int, required=False, default=8086, help='port of InfluxDB http API') return parser.parse_args() if __name__ == '__main__': args = parse_args() main(host=args.host, port=args.port)
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(30)), index=pd.date_range(start='2014-11-16', periods=30, freq='H')) print("Create database: " + dbname) client.create_database(dbname) print("Write DataFrame") client.write_points(df, 'demo') print("Write DataFrame with Tags") client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'}) print("Read DataFrame") client.query("select * from demo") print("Delete database: " + dbname) client.delete_database(dbname) def parse_args(): parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname of InfluxDB http API') parser.add_argument('--port', type=int, required=False, default=8086, help='port of InfluxDB http API') return parser.parse_args() if __name__ == '__main__': args = parse_args() main(host=args.host, port=args.port)
Refactor test for new view added with upgrade
import json from django.test import TestCase from django_extensions.management.commands.show_urls import Command class UrlTests(TestCase): def is_exception(self, url): exceptions = [".txt", ".ics", ".geojson"] for exception in exceptions: if exception in url: return True return False def test_trailing_slashes(self): c = Command() data = json.loads( c.handle( **{ "unsorted": False, "language": None, "decorator": [], "format_style": "json", "urlconf": "ROOT_URLCONF", "no_color": True, } ) ) urls = [rec["url"] for rec in data] urls.remove("/admin/<url>") for url in urls: if self.is_exception(url): continue assert url[-1] == "/", url + " does not end with /"
import json from django.test import TestCase from django_extensions.management.commands.show_urls import Command class UrlTests(TestCase): def is_exception(self, url): exceptions = [".txt", ".ics", ".geojson"] for exception in exceptions: if exception in url: return True return False def test_trailing_slashes(self): c = Command() data = json.loads( c.handle( **{ "unsorted": False, "language": None, "decorator": [], "format_style": "json", "urlconf": "ROOT_URLCONF", "no_color": True, } ) ) urls = [rec["url"] for rec in data] for url in urls: if self.is_exception(url): continue assert url[-1] == "/" or ">", url + " does not end with /"
Remove test that was removed with 'redundant abstract' diagnostic
package org.jetbrains.kotlin.ui.tests.editors.quickfix.autoimport; import org.junit.Test; public class KotlinAbstractModifierQuickFixTest extends KotlinQuickFixTestCase { @Override protected String getTestDataRelativePath() { return "../common_testData/ide/quickfix/abstract/"; } @Test public void abstractFunctionInNonAbstractClass() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass1() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass2() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass3() { doAutoTest(); } @Test public void abstractPropertyInPrimaryConstructorParameters() { doAutoTest(); } @Test public void abstractPropertyNotInClass() { doAutoTest(); } @Test public void abstractPropertyWithGetter1() { doAutoTest(); } @Test public void abstractPropertyWithInitializer1() { doAutoTest(); } @Test public void abstractPropertyWithSetter() { doAutoTest(); } @Test public void mustBeInitializedOrBeAbstract() { doAutoTest(); } @Test public void nonMemberAbstractFunction() { doAutoTest(); } @Test public void notImplementedMember() { doAutoTest(); } @Test public void notImplementedMemberFromAbstractClass() { doAutoTest(); } @Test public void replaceOpen() { doAutoTest(); } }
package org.jetbrains.kotlin.ui.tests.editors.quickfix.autoimport; import org.junit.Test; public class KotlinAbstractModifierQuickFixTest extends KotlinQuickFixTestCase { @Override protected String getTestDataRelativePath() { return "../common_testData/ide/quickfix/abstract/"; } @Test public void abstractFunctionInNonAbstractClass() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass1() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass2() { doAutoTest(); } @Test public void abstractPropertyInNonAbstractClass3() { doAutoTest(); } @Test public void abstractPropertyInPrimaryConstructorParameters() { doAutoTest(); } @Test public void abstractPropertyNotInClass() { doAutoTest(); } @Test public void abstractPropertyWithGetter1() { doAutoTest(); } @Test public void abstractPropertyWithInitializer1() { doAutoTest(); } @Test public void abstractPropertyWithSetter() { doAutoTest(); } @Test public void mustBeInitializedOrBeAbstract() { doAutoTest(); } @Test public void nonMemberAbstractFunction() { doAutoTest(); } @Test public void notImplementedMember() { doAutoTest(); } @Test public void notImplementedMemberFromAbstractClass() { doAutoTest(); } @Test public void redundantAbstract() { doAutoTest(); } @Test public void replaceOpen() { doAutoTest(); } }
Fix typo in associative array
<?php /** * Service for the Salesforce data API. * * @license http://opensource.org/licenses/MIT The MIT License (MIT) */ namespace Salesforce\Service; use GuzzleHttp\ClientInterface as HttpClientInterface; use skyflow\Domain\OAuthUser; use skyflow\Service\OAuthServiceInterface; use skyflow\Service\RestOAuthAuthenticatedService; use Salesforce\Domain\SalesforceUser; /** * Service for the Salesforce data API. */ class SalesforceDataService extends RestOAuthAuthenticatedService { /** * Send a SOQL query to Salesforce data API. * * @param string $query The SOQL query string. * @return string Response as string encoded in JSON format. */ public function query($query) { $response = $this->httpGet( "/query", array( "q" => rtrim($query, ';') ), array( 'Authorization' => 'OAuth ' . $this->getUser()->getAccessToken() ) ); return $response->json(); } /** * Get SObjects metadata. * * @return string Response as string encoded in JSON format. */ public function sobjects() { $response = $this->httpGet( "/sobjects", array(), array( 'Authorization' => 'OAuth ' . $this->getUser()->getAccessToken() ) ); return $response->json(); } }
<?php /** * Service for the Salesforce data API. * * @license http://opensource.org/licenses/MIT The MIT License (MIT) */ namespace Salesforce\Service; use GuzzleHttp\ClientInterface as HttpClientInterface; use skyflow\Domain\OAuthUser; use skyflow\Service\OAuthServiceInterface; use skyflow\Service\RestOAuthAuthenticatedService; use Salesforce\Domain\SalesforceUser; /** * Service for the Salesforce data API. */ class SalesforceDataService extends RestOAuthAuthenticatedService { /** * Send a SOQL query to Salesforce data API. * * @param string $query The SOQL query string. * @return string Response as string encoded in JSON format. */ public function query($query) { $response = $this->httpGet( "/query", array( "q" => rtrim($query, ';') ), array( 'Authorization', 'OAuth ' . $this->getUser()->getAccessToken() ) ); return $response->json(); } /** * Get SObjects metadata. * * @return string Response as string encoded in JSON format. */ public function sobjects() { $response = $this->httpGet( "/sobjects", array(), array( 'Authorization', 'OAuth ' . $this->getUser()->getAccessToken() ) ); return $response->json(); } }
Fix class property, prefer non-static
<?php namespace GB2260; class GB2260 { protected $data; public function __construct() { $this->data = require 'data.php'; } public function get($code) { $code = preg_replace('/(00)+$/', '', $code); $codeLength = strlen($code); if ($codeLength < 2 || $codeLength > 6 || $codeLength % 2 !== 0) { throw new \Exception('Invalid code'); } $provinceCode = substr($code, 0, 2) . '0000'; if (!isset($this->data[$provinceCode])) { return null; } $province = $this->data[$provinceCode]; if ($codeLength === 2) { return $province; } $prefectureCode = substr($code, 0, 4) . '00'; if (!isset($this->data[$prefectureCode])) { return null; } $area = $this->data[$prefectureCode]; if ($codeLength === 4) { return $province . ' ' . $area; } if (!isset($this->data[$code])) { return null; } $name = $this->data[$code]; return $province . ' ' . $area . ' ' . $name; } }
<?php namespace GB2260; class GB2260 { protected static $_data; public function __construct() { self::$_data = require 'data.php'; } public function get($code) { $code = preg_replace('/(00)+$/', '', $code); $codeLength = strlen($code); if ($codeLength < 2 || $codeLength > 6 || $codeLength % 2 !== 0) { throw new \Exception('Invalid code'); } $provinceCode = substr($code, 0, 2) . '0000'; if (!isset(self::$_data[$provinceCode])) { return null; } $province = self::$_data[$provinceCode]; if ($codeLength === 2) { return $province; } $prefectureCode = substr($code, 0, 4) . '00'; if (!isset(self::$_data[$prefectureCode])) { return null; } $area = self::$_data[$prefectureCode]; if ($codeLength === 4) { return $province . ' ' . $area; } if (!isset(self::$_data[$code])) { return null; } $name = self::$_data[$code]; return $province . ' ' . $area . ' ' . $name; } }
Fix index names in migrations This can be reverted when we upgrade to Laravel 5.7.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Database\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { // Delete rows with non-existent entities so that we will be able to create // foreign keys without any issues. $schema->getConnection() ->table('post_likes') ->whereNotExists(function ($query) { $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id'); }) ->orWhereNotExists(function ($query) { $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id'); }) ->delete(); $schema->table('post_likes', function (Blueprint $table) use ($schema) { $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); Migration::fixIndexNames($schema, $table); }); }, 'down' => function (Builder $schema) { $schema->table('post_likes', function (Blueprint $table) use ($schema) { $table->dropForeign(['post_id', 'user_id']); Migration::fixIndexNames($schema, $table); }); } ];
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { // Delete rows with non-existent entities so that we will be able to create // foreign keys without any issues. $schema->getConnection() ->table('post_likes') ->whereNotExists(function ($query) { $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id'); }) ->orWhereNotExists(function ($query) { $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id'); }) ->delete(); $schema->table('post_likes', function (Blueprint $table) { $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); }, 'down' => function (Builder $schema) { $schema->table('post_likes', function (Blueprint $table) { $table->dropForeign(['post_id', 'user_id']); }); } ];
Remove commonjs in top level
import commonjs from '@rollup/plugin-commonjs'; import glslify from 'rollup-plugin-glslify'; import resolve from '@rollup/plugin-node-resolve'; import copy from "rollup-plugin-copy"; export default { input: ['source/gltf-sample-viewer.js'], output: [ { file: 'dist/gltf-viewer.js', format: 'cjs', sourcemap: true }, { file: 'dist/gltf-viewer.module.js', format: 'esm', sourcemap: true, } ], plugins: [ glslify(), copy({ targets: [ { src: [ "assets/images/lut_charlie.png", "assets/images/lut_ggx.png", "assets/images/lut_sheen_E.png", ], dest: "dist/assets" }, { src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" } ] }), ] };
import commonjs from '@rollup/plugin-commonjs'; import glslify from 'rollup-plugin-glslify'; import resolve from '@rollup/plugin-node-resolve'; import copy from "rollup-plugin-copy"; export default { input: ['source/gltf-sample-viewer.js'], output: [ { file: 'dist/gltf-viewer.js', format: 'cjs', sourcemap: true }, { file: 'dist/gltf-viewer.module.js', format: 'esm', sourcemap: true, } ], plugins: [ glslify(), copy({ targets: [ { src: [ "assets/images/lut_charlie.png", "assets/images/lut_ggx.png", "assets/images/lut_sheen_E.png", ], dest: "dist/assets" }, { src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" } ] }), commonjs(), ] };
Remove host and port attributes from Neo4j
import requests from py2neo import Graph, authenticate class Neo4j: def __init__(self, host, port, username=None, password=None): self.username = username self.password = password self.host_port = "{host}:{port}".format(host=host, port=port) self.url = "http://{host_port}/db/data/".format(host_port=self.host_port) def connection(self): if self.username and self.password: authenticate(self.host_port, self.username, self.password) graph = Graph(self.url) return graph def cypher(self, query): tx = self.connection().cypher.begin() try: tx.append(query) results = tx.process() tx.commit() except Exception as e: results = e except KeyboardInterrupt: tx.rollback() results = "" return results def labels(self): return sorted(list(self.connection().node_labels)) def relationship_types(self): return sorted(list(self.connection().relationship_types)) def properties(self): url = self.url + "propertykeys" r = requests.get(url, auth=(self.username, self.password)) props = r.json() return sorted(props)
import requests from py2neo import Graph, authenticate class Neo4j: def __init__(self, host, port, username=None, password=None): self.host = host self.port = port self.username = username self.password = password self.host_port = "{host}:{port}".format(host=host, port=port) self.url = "http://{host_port}/db/data/".format(host_port=self.host_port) def connection(self): if self.username and self.password: authenticate(self.host_port, self.username, self.password) graph = Graph(self.url) return graph def cypher(self, query): tx = self.connection().cypher.begin() try: tx.append(query) results = tx.process() tx.commit() except Exception as e: results = e except KeyboardInterrupt: tx.rollback() results = "" return results def labels(self): return sorted(list(self.connection().node_labels)) def relationship_types(self): return sorted(list(self.connection().relationship_types)) def properties(self): url = self.url + "propertykeys" r = requests.get(url, auth=(self.username, self.password)) props = r.json() return sorted(props)
Fix test generating graph file
from jg.__main__ import main, generate_template_graph from mock import patch FIXTURE_GRAPH = ( 'digraph {\n' '\t"snippets/sub/analytics.html"\n' '\t"snippets/ga.html"\n' '\t\t"snippets/ga.html" -> "snippets/sub/analytics.html"\n' '\t"header.html"\n' '\t"analytics.html"\n' '\t"custom_index.html"\n' '\t\t"custom_index.html" -> "index.html"\n' '\t\t"custom_index.html" -> "snippets/ga.html"\n' '\t"index.html"\n' '\t\t"index.html" -> "header.html"\n' '\t\t"index.html" -> "footer.html"\n' '\t"footer.html"\n}') def test_main_generates_graph_for_given_directory(): output_filename = 'graph.dot' with patch('jg.__main__.write') as write: exit_code = main(['./tests/fixtures', output_filename]) write.assert_called_with(FIXTURE_GRAPH, output_filename) assert exit_code == 0 def test_parses_all_templates_in_given_root_directory(): dot = generate_template_graph(root_path='./tests/fixtures') assert dot.source == FIXTURE_GRAPH
from jg.__main__ import main, generate_template_graph from mock import patch FIXTURE_GRAPH = ( 'digraph {\n' '\t"snippets/sub/analytics.html"\n' '\t"snippets/ga.html"\n' '\t\t"snippets/ga.html" -> "snippets/sub/analytics.html"\n' '\t"header.html"\n' '\t"analytics.html"\n' '\t"custom_index.html"\n' '\t\t"custom_index.html" -> "index.html"\n' '\t\t"custom_index.html" -> "snippets/ga.html"\n' '\t"index.html"\n' '\t\t"index.html" -> "header.html"\n' '\t\t"index.html" -> "footer.html"\n' '\t"footer.html"\n}') def test_main_generates_graph_for_given_directory(): output_filename = 'graph.dot' with patch('jg.__main__.write') as write: exit_code = main(['./tests/fixtures', output_filename]) write.assert_called_with(FIXTURE_GRAPH, output_filename) assert exit_code == 0 def test_parses_all_templates_in_given_root_directory(): dot = generate_template_graph(root_path='./tests/fixtures') dot.render('t1.dot') assert dot.source == FIXTURE_GRAPH
Remove version requirement, add pathlib
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click', 'pathlib'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click>=6.0'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, )
Support large meshes on Fermi-class hardware.
# -*- coding: utf-8 -*- import numpy as np from pyfr.backends.cuda.provider import CudaKernelProvider from pyfr.backends.cuda.queue import CudaComputeKernel from pyfr.nputil import npdtype_to_ctype class CudaBlasExtKernels(CudaKernelProvider): def __init__(self, backend): super(CudaBlasExtKernels, self).__init__() def axnpby(self, y, *xn): if any(y.traits != x.traits for x in xn): raise ValueError('Incompatible matrix types') opts = dict(n=len(xn), dtype=npdtype_to_ctype(y.dtype)) fn = self._get_function('blasext', 'axnpby', [np.int32] + [np.intp, y.dtype]*(1 + len(xn)), opts) # Determine the total element count in the matrices cnt = y.leaddim*y.majdim # Compute a suitable block and grid block = (1024, 1, 1) grid = self._get_grid_for_block(block, cnt) class AxnpbyKernel(CudaComputeKernel): def run(self, scomp, scopy, beta, *alphan): args = [i for axn in zip(xn, alphan) for i in axn] fn.prepared_async_call(grid, block, scomp, cnt, y, beta, *args) return AxnpbyKernel()
# -*- coding: utf-8 -*- import numpy as np from pyfr.backends.cuda.provider import CudaKernelProvider from pyfr.backends.cuda.queue import CudaComputeKernel from pyfr.nputil import npdtype_to_ctype class CudaBlasExtKernels(CudaKernelProvider): def __init__(self, backend): super(CudaBlasExtKernels, self).__init__() def axnpby(self, y, *xn): if any(y.traits != x.traits for x in xn): raise ValueError('Incompatible matrix types') opts = dict(n=len(xn), dtype=npdtype_to_ctype(y.dtype)) fn = self._get_function('blasext', 'axnpby', [np.int32] + [np.intp, y.dtype]*(1 + len(xn)), opts) # Determine the total element count in the matrices cnt = y.leaddim*y.majdim # Compute a suitable block and grid block = (512, 1, 1) grid = self._get_grid_for_block(block, cnt) class AxnpbyKernel(CudaComputeKernel): def run(self, scomp, scopy, beta, *alphan): args = [i for axn in zip(xn, alphan) for i in axn] fn.prepared_async_call(grid, block, scomp, cnt, y, beta, *args) return AxnpbyKernel()
Revert watch if not production
const path = require('path'); const webpack = require('webpack'); const production = process.env.NODE_ENV === 'production'; const plugins = [ new webpack.ProvidePlugin({ $ : 'jquery', jQuery : 'jquery', 'window.jQuery': 'jquery', }), ]; const productionPlugins = production ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.UglifyJsPlugin({ include : /\.js$/, minimize : true, sourceMap: true, compress : { warnings: false, }, }), ] : []; module.exports = { entry: { bot : path.join(__dirname, 'src', 'botPage', 'view'), index: path.join(__dirname, 'src', 'indexPage'), }, output: { filename : production ? '[name].min.js' : '[name].js', sourceMapFilename: production ? '[name].min.js.map' : '[name].js.map', }, devtool : 'source-map', watch : !production, target : 'web', externals: { ws : 'WebSocket', CIQ: 'CIQ', }, module: { rules: [ { test : /\.(js|jsx)$/, exclude: /node_modules/, use : 'babel-loader', }, ], }, plugins: plugins.concat(productionPlugins), };
const path = require('path'); const webpack = require('webpack'); const production = process.env.NODE_ENV === 'production'; const plugins = [ new webpack.ProvidePlugin({ $ : 'jquery', jQuery : 'jquery', 'window.jQuery': 'jquery', }), ]; const productionPlugins = production ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.UglifyJsPlugin({ include : /\.js$/, minimize : true, sourceMap: true, compress : { warnings: false, }, }), ] : []; module.exports = { entry: { bot : path.join(__dirname, 'src', 'botPage', 'view'), index: path.join(__dirname, 'src', 'indexPage'), }, output: { filename : production ? '[name].min.js' : '[name].js', sourceMapFilename: production ? '[name].min.js.map' : '[name].js.map', }, devtool : 'source-map', watch : false, target : 'web', externals: { ws : 'WebSocket', CIQ: 'CIQ', }, module: { rules: [ { test : /\.(js|jsx)$/, exclude: /node_modules/, use : 'babel-loader', }, ], }, plugins: plugins.concat(productionPlugins), };
[test-studio] Add example of using custom icon for list item
import React from 'react' import S from '@sanity/desk-tool/structure-builder' import RefreshIcon from 'part:@sanity/base/sync-icon' import JsonDocumentDump from './components/JsonDocumentDump' // For testing. Bump the timeout to introduce som lag const delay = val => new Promise(resolve => setTimeout(resolve, 10, val)) export default () => S.list() .id('root') .title('Content') .items([ S.listItem() .id('docList') .title('Anything with a title') .icon(() => <span style={{fontSize: '2em'}}>T</span>) .child(() => delay( S.documentList({ id: 'title-list', title: 'Titles!', options: { filter: 'defined(title)' } }) ) ), S.listItem() .id('circular') .title('Singleton?') .child(delay(S.editor({id: 'editor', options: {id: 'circular', type: 'referenceTest'}}))), S.documentListItem() .id('grrm') .schemaType('author') .child( S.component() .id('dump') .component(JsonDocumentDump) .menuItems([ S.menuItem() .title('Reload') .action('reload') .icon(RefreshIcon) .showAsAction(true) ]) ), ...S.documentTypeListItems() ])
import S from '@sanity/desk-tool/structure-builder' import RefreshIcon from 'part:@sanity/base/sync-icon' import JsonDocumentDump from './components/JsonDocumentDump' // For testing. Bump the timeout to introduce som lag const delay = val => new Promise(resolve => setTimeout(resolve, 10, val)) export default () => S.list() .id('root') .title('Content') .items([ S.listItem() .id('docList') .title('Anything with a title') .child(() => delay( S.documentList({ id: 'title-list', title: 'Titles!', options: { filter: 'defined(title)' } }) ) ), S.listItem() .id('circular') .title('Singleton?') .child(delay(S.editor({id: 'editor', options: {id: 'circular', type: 'referenceTest'}}))), S.documentListItem() .id('grrm') .schemaType('author') .child( S.component() .id('dump') .component(JsonDocumentDump) .menuItems([ S.menuItem() .title('Reload') .action('reload') .icon(RefreshIcon) .showAsAction(true) ]) ), ...S.documentTypeListItems() ])
Add ability to set karma file through env
module.exports = function(config) { const { KARMA_FILE = 'src/**/*.spec.js' } = process.env; const FILE = KARMA_FILE || 'src/**/*.spec.js'; config.set({ basePath: '', frameworks: ['mocha'], webpack: { mode: 'development', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/env'], plugins: ['@babel/plugin-proposal-export-default-from'] } } }, { test: /\.html$/, use: { loader: 'raw-loader' } } ] } }, files: [ 'app/bootstrap/css/bootstrap.min.css', 'app/fontawesome/css/font-awesome.min.css', 'dist/formio.full.min.css', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, { pattern: 'dist/icons/*', watched: false, included: false, served: true, nocache: false }, FILE ], exclude: [ ], preprocessors: { [FILE]: ['webpack'] }, browserNoActivityTimeout: 30000, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha'], webpack: { mode: 'development', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/env'], plugins: ['@babel/plugin-proposal-export-default-from'] } } }, { test: /\.html$/, use: { loader: 'raw-loader' } } ] } }, files: [ 'app/bootstrap/css/bootstrap.min.css', 'app/fontawesome/css/font-awesome.min.css', 'dist/formio.full.min.css', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, { pattern: 'dist/icons/*', watched: false, included: false, served: true, nocache: false }, 'src/**/*.spec.js' ], exclude: [ ], preprocessors: { 'src/**/*.spec.js': ['webpack'] }, browserNoActivityTimeout: 30000, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }); };
Move 'allowed' to noop group
<?php namespace Pheasant\Database; class MysqlPlatform { public function columnSql($column, $type, $options) { return trim(sprintf('`%s` %s %s', $column, $type, $this->_options($options))); } /** * Returns mysql column options for a given {@link Options} * @return string */ private function _options($options) { $result = array(); // certain parameters have to occur first if (isset($options->unsigned)) { $result []= 'unsigned'; } if (isset($options->zerofill)) { $result []= 'zerofill'; } foreach ($options as $key=>$value) { switch ($key) { case 'primary': $result [] = 'primary key'; break; case 'required': case 'notnull': $result [] = 'not null'; break; case 'default': $result []= sprintf("default '%s'", $value); break; case 'sequence': case 'unsigned': case 'zerofill': case 'allowed': break; default: $result []= $key; break; } } return implode(' ', $result); } }
<?php namespace Pheasant\Database; class MysqlPlatform { public function columnSql($column, $type, $options) { return trim(sprintf('`%s` %s %s', $column, $type, $this->_options($options))); } /** * Returns mysql column options for a given {@link Options} * @return string */ private function _options($options) { $result = array(); // certain parameters have to occur first if (isset($options->unsigned)) { $result []= 'unsigned'; } if (isset($options->zerofill)) { $result []= 'zerofill'; } foreach ($options as $key=>$value) { if ($key == 'allowed') { continue; } switch ($key) { case 'primary': $result [] = 'primary key'; break; case 'required': case 'notnull': $result [] = 'not null'; break; case 'default': $result []= sprintf("default '%s'", $value); break; case 'sequence': case 'unsigned': case 'zerofill': break; default: $result []= $key; break; } } return implode(' ', $result); } }
Set cookie to http only
require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const login = require('./login.js'); const getPullRequests = require('./getPullRequests.js'); const Maybe = require('folktale/maybe'); const app = express(); app.use(bodyParser.json()); app.use(cookieParser()); app.post('/api/login', (req, res) => { const {username, password, server} = req.body; const loginObj = { username, password, server }; login(loginObj).then(() => { res.cookie('login', loginObj, { httpOnly: true }); res.sendStatus(200); }, (error) => { res.sendStatus(error.statusCode); }); }); app.post('/api/logout', (req, res) => { res.clearCookie('login'); res.sendStatus(200); }); app.get('/api/pullrequests', (req, res) => { Maybe.fromNullable(req.cookies.login).matchWith({ Just: ({value}) => { getPullRequests(value).then(data => res.json(data), error => { console.log('index.js', '40', '', error); res.sendStatus(500); }); }, Nothing: () => res.sendStatus(401) }); }); app.set('port', process.env.PORT); app.listen(app.get('port'));
require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const login = require('./login.js'); const getPullRequests = require('./getPullRequests.js'); const Maybe = require('folktale/maybe'); const app = express(); app.use(bodyParser.json()); app.use(cookieParser()); app.post('/api/login', (req, res) => { const {username, password, server} = req.body; const loginObj = { username, password, server }; login(loginObj).then(() => { res.cookie('login', loginObj, { maxAge: 900000, httpOnly: false }); res.sendStatus(200); }, (error) => { res.sendStatus(error.statusCode); }); }); app.post('/api/logout', (req, res) => { res.clearCookie('login'); res.sendStatus(200); }); app.get('/api/pullrequests', (req, res) => { Maybe.fromNullable(req.cookies.login).matchWith({ Just: ({value}) => { getPullRequests(value).then(data => res.json(data), error => { console.log('index.js', '40', '', error); res.sendStatus(500); }); }, Nothing: () => res.sendStatus(401) }); }); app.set('port', process.env.PORT); app.listen(app.get('port'));
Make the example camera matrices sane
window.addEvent("domready", function() { var BasicApp = new Class({ Extends: App, initialize: function(element, options) { this.parent(element, options); this.renderer = new BasicRenderer(); this.camera = new Camera(); this.camera.perspective(45, this.options.width/this.options.height, 0.1, 100); this.camera.lookAt([0, 0, 5], [0, 0, 0], [0, 1, 0]); this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW, gl.STATIC_DRAW, gl.STATIC_DRAW); this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]); this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]); }, draw: function() { this.clear(); this.renderer.renderMesh(this.triangle, this.camera); } }); var app = new BasicApp(document.body); app.run(); });
window.addEvent("domready", function() { var BasicApp = new Class({ Extends: App, initialize: function(element, options) { this.parent(element, options); this.renderer = new BasicRenderer(); this.camera = new Camera(); this.camera.perspective(45, this.options.width/this.options.height, -1, 1); this.camera.lookAt([0, 0, 0], [0, 0, -5], [0, 1, 0]); this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW, gl.STATIC_DRAW, gl.STATIC_DRAW); this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]); this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]); }, draw: function() { this.clear(); this.renderer.renderMesh(this.triangle, this.camera); } }); var app = new BasicApp(document.body); app.run(); });
Move sheet_by_name after expected interfaces.
from django.conf import settings import xlrd import os base_loader_error = 'The Loader class can only be used by extending it.' extensions = getattr( settings, 'IMPORTER_EXTENSIONS', { 'excel': ('.xls', '.xlsx'), } ) class Loader(object): def __init__(self, file_info, autoload=True): self.filename = file_info.path if autoload is True: return self.open() def open(self): raise NotImplementedError(base_loader_error) def close(self): pass @classmethod def sniff(cls, file_info): raise NotImplementedError(base_loader_error) class ExcelLoader(Loader): supports_sheets = True type_name = 'excel' def open(self): self.backend = xlrd.open_workbook(self.filename) self.sheet_names = self.backend.sheet_names() self.sheet_count = len(self.sheet_names) def close(self): self.backend.release_resources() @classmethod def sniff(cls, file_info): # TODO: Find a way to really sniff the file. if not 'excel' in extensions: return False return os.path.splitext(file_info.path)[-1] in extensions['excel'] def sheet_by_name(self, name): """ Returns a sheet based on it's name. """ return self.backend.sheet_by_name(name) # TODO: Finish Loader for importing from CSV data. class CSVLoader(Loader): supports_sheets = False
from django.conf import settings import xlrd import os base_loader_error = 'The Loader class can only be used by extending it.' extensions = getattr( settings, 'IMPORTER_EXTENSIONS', { 'excel': ('.xls', '.xlsx'), } ) class Loader(object): def __init__(self, file_info, autoload=True): self.filename = file_info.path if autoload is True: return self.open() def open(self): raise NotImplementedError(base_loader_error) def close(self): pass @classmethod def sniff(cls, file_info): raise NotImplementedError(base_loader_error) class ExcelLoader(Loader): supports_sheets = True type_name = 'excel' def open(self): self.backend = xlrd.open_workbook(self.filename) self.sheet_names = self.backend.sheet_names() self.sheet_count = len(self.sheet_names) def sheet_by_name(self, name): """ Returns a sheet based on it's name. """ return self.backend.sheet_by_name(name) def close(self): self.backend.release_resources() @classmethod def sniff(cls, file_info): # TODO: Find a way to really sniff the file. if not 'excel' in extensions: return False return os.path.splitext(file_info.path)[-1] in extensions['excel'] # TODO: Finish Loader for importing from CSV data. class CSVLoader(Loader): supports_sheets = False
Use correct environment for Intercom Whoops ¯\_(ツ)_/¯
@if (app()->environment('production') && $appId = config('services.intercom.app_id')) <script> window.intercomSettings = { @if (Auth::check()) user_id: {{ Auth::user()->id() }}, user_hash: "{{ Auth::user()->intercomHash() }}", name: "{{ Auth::user()->name() }}", email: "{{ Auth::user()->emailAddress() }}", created_at: {{ Auth::user()->createdAt()->timestamp }}, @if ($githubUsername = Auth::user()->githubUsername()) github: "{{ $githubUsername }}", @endif @endif app_id: "{{ $appId }}" }; </script> <script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k7e25len';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script> @endif
@if (app()->environment('local') && $appId = config('services.intercom.app_id')) <script> window.intercomSettings = { @if (Auth::check()) user_id: {{ Auth::user()->id() }}, user_hash: "{{ Auth::user()->intercomHash() }}", name: "{{ Auth::user()->name() }}", email: "{{ Auth::user()->emailAddress() }}", created_at: {{ Auth::user()->createdAt()->timestamp }}, @if ($githubUsername = Auth::user()->githubUsername()) github: "{{ $githubUsername }}", @endif @endif app_id: "{{ $appId }}" }; </script> <script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k7e25len';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script> @endif
Change homepage landing to dashboard
package io.github.pbremer.icecreammanager.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SimpleGreetingController { public static final String HELLO = "Hello, team formally known as 'Team 6'!"; private static final Logger LOGGER = LoggerFactory .getLogger(SimpleGreetingController.class); //@RequestMapping("/") public String hello() { LOGGER.debug("At index"); // return HELLO; return "public/index"; } @RequestMapping(path={"/dashboard", "/"}) public String dashboard() { LOGGER.debug("At dashboard"); // return HELLO; return "public/dashboard"; } @RequestMapping("/alter") public String alter() { LOGGER.debug("At alter"); // return HELLO; return "public/alter"; } @RequestMapping("/inventory") public String inventory() { LOGGER.debug("At inventory"); // return HELLO; return "public/inventory"; } @RequestMapping("/uploadfile") public String uploadfile() { LOGGER.debug("At uploadfile"); // return HELLO; return "public/uploadfile"; } }
package io.github.pbremer.icecreammanager.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SimpleGreetingController { public static final String HELLO = "Hello, team formally known as 'Team 6'!"; private static final Logger LOGGER = LoggerFactory .getLogger(SimpleGreetingController.class); @RequestMapping("/") public String hello() { LOGGER.debug("At index"); // return HELLO; return "public/index"; } @RequestMapping("/dashboard") public String dashboard() { LOGGER.debug("At dashboard"); // return HELLO; return "public/dashboard"; } @RequestMapping("/alter") public String alter() { LOGGER.debug("At alter"); // return HELLO; return "public/alter"; } @RequestMapping("/inventory") public String inventory() { LOGGER.debug("At inventory"); // return HELLO; return "public/inventory"; } @RequestMapping("/uploadfile") public String uploadfile() { LOGGER.debug("At uploadfile"); // return HELLO; return "public/uploadfile"; } }
Remove t() from PHPdoc example to avoid confusion
<?php namespace Kanboard\Core\ExternalLink; /** * External Link Provider Interface * * @package externalLink * @author Frederic Guillot */ interface ExternalLinkProviderInterface { /** * Get provider name (label) * * @access public * @return string */ public function getName(); /** * Get link type (will be saved in the database) * * @access public * @return string */ public function getType(); /** * Get a dictionary of supported dependency types by the provider * * Example: * * [ * 'related' => 'Related', * 'child' => 'Child', * 'parent' => 'Parent', * 'self' => 'Self', * ] * * The dictionary key is saved in the database. * * @access public * @return array */ public function getDependencies(); /** * Set text entered by the user * * @access public * @param string $input */ public function setUserTextInput($input); /** * Return true if the provider can parse correctly the user input * * @access public * @return boolean */ public function match(); /** * Get the link found with the properties * * @access public * @return ExternalLinkInterface */ public function getLink(); }
<?php namespace Kanboard\Core\ExternalLink; /** * External Link Provider Interface * * @package externalLink * @author Frederic Guillot */ interface ExternalLinkProviderInterface { /** * Get provider name (label) * * @access public * @return string */ public function getName(); /** * Get link type (will be saved in the database) * * @access public * @return string */ public function getType(); /** * Get a dictionary of supported dependency types by the provider * * Example: * * [ * 'related' => t('Related'), * 'child' => t('Child'), * 'parent' => t('Parent'), * 'self' => t('Self'), * ] * * The dictionary key is saved in the database. * * @access public * @return array */ public function getDependencies(); /** * Set text entered by the user * * @access public * @param string $input */ public function setUserTextInput($input); /** * Return true if the provider can parse correctly the user input * * @access public * @return boolean */ public function match(); /** * Get the link found with the properties * * @access public * @return ExternalLinkInterface */ public function getLink(); }
Select path for page context.
"use strict"; import React, { Component, PropTypes } from 'react'; import { getItems } from '../../actions'; import PageItem from './PageItem'; export default class PageContext extends Component { constructor () { super(); this.state = { pages: [] }; } componentDidMount () { this._load(this.props); } componentWillReceiveProps (nextProps) { this._load(nextProps); } componentWillUnmount () { this._unmounted = true; } _load (props) { const { filter } = props; if (filter) { getItems('pages', { filter: filter, select: 'name path' }) .then(pages => { if (! this._unmounted) { this.setState({ pages: pages }); } }) .catch(error => console.log('!!! PageContext pages catch', error)); } } render () { const { pages } = this.state; let result = null; if (pages.length > 0) { const pageItems = pages.map(page => ( <li key={page._id}> <PageItem item={page} /> </li> )); result = ( <ul className="page-context list"> {pageItems} </ul> ); } return result; }; } PageContext.propTypes = { filter: PropTypes.object };
"use strict"; import React, { Component, PropTypes } from 'react'; import { getItems } from '../../actions'; import PageItem from './PageItem'; export default class PageContext extends Component { constructor () { super(); this.state = { pages: [] }; } componentDidMount () { this._load(this.props); } componentWillReceiveProps (nextProps) { this._load(nextProps); } componentWillUnmount () { this._unmounted = true; } _load (props) { const { filter } = props; if (filter) { getItems('pages', { filter: filter, select: 'name' }) .then(pages => { if (! this._unmounted) { this.setState({ pages: pages }); } }) .catch(error => console.log('!!! PageContext pages catch', error)); } } render () { const { pages } = this.state; let result = null; if (pages.length > 0) { const pageItems = pages.map(page => ( <li key={page._id}> <PageItem item={page} /> </li> )); result = ( <ul className="page-context list"> {pageItems} </ul> ); } return result; }; } PageContext.propTypes = { filter: PropTypes.object };