text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove unused fopenmp compile args | #!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
| #!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
Comment the new library requirement | """Mailmerge build and install configuration."""
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file:
README = readme_file.read()
setup(
name="mailmerge",
description="A simple, command line mail merge tool",
long_description=README,
version="1.9",
author="Andrew DeOrio",
author_email="awdeorio@umich.edu",
url="https://github.com/awdeorio/mailmerge/",
license="MIT",
packages=["mailmerge"],
keywords=["mail merge", "mailmerge", "email"],
install_requires=[
"chardet",
"click",
"configparser",
"jinja2",
# The attachments feature relies on a bug fix in the future library
"future>0.18.0",
"backports.csv;python_version<='2.7'",
"markdown",
"mock;python_version<='2.7'",
],
extras_require={
'dev': [
'check-manifest',
'codecov>=1.4.0',
'pdbpp',
'pycodestyle',
'pydocstyle',
'pylint',
'pytest',
'pytest-cov',
'tox',
]
},
# Python command line utilities will be installed in a PATH-accessible bin/
entry_points={
'console_scripts': [
'mailmerge = mailmerge.__main__:cli',
]
},
)
| """Mailmerge build and install configuration."""
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file:
README = readme_file.read()
setup(
name="mailmerge",
description="A simple, command line mail merge tool",
long_description=README,
version="1.9",
author="Andrew DeOrio",
author_email="awdeorio@umich.edu",
url="https://github.com/awdeorio/mailmerge/",
license="MIT",
packages=["mailmerge"],
keywords=["mail merge", "mailmerge", "email"],
install_requires=[
"chardet",
"click",
"configparser",
"jinja2",
"future>0.18.0",
"backports.csv;python_version<='2.7'",
"markdown",
"mock;python_version<='2.7'",
],
extras_require={
'dev': [
'check-manifest',
'codecov>=1.4.0',
'pdbpp',
'pycodestyle',
'pydocstyle',
'pylint',
'pytest',
'pytest-cov',
'tox',
]
},
# Python command line utilities will be installed in a PATH-accessible bin/
entry_points={
'console_scripts': [
'mailmerge = mailmerge.__main__:cli',
]
},
)
|
Increase the count so we don't spin forever | import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
count += 1
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
| import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
|
Fix missing import, add alias/deactivate method | import json
import random
import string
from flask import Flask, request, jsonify, render_template
from flask.ext.pymongo import PyMongo
from pymongo.errors import DuplicateKeyError
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'kasm'
mongo = PyMongo(app)
@app.route('/')
def hello_world():
return render_template('kasm.html')
@app.route('/alias/create', methods=['POST'])
def create_alias():
def id_generator(size, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in xrange(size))
#post_data = json.loads(request.data)
#email = post_data['email']
email = request.form['email']
inserted = False
while not inserted:
try:
alias = id_generator(8)
mongo.db.redirects.insert({'email': email, 'alias': alias})
except DuplicateKeyError:
pass
else:
inserted = True
to_return = {'email': email,
'encrypt': 'lolwut',
'original': email,
'response': 'success',
'username': alias,
}
return jsonify(to_return)
@app.route('alias/deactivate', methods=['POST'])
def deactivate_alias():
post_data = json.loads(request.data)
alias = post_data['alias']
result = mongo.db.redirects.update({'alias': alias},
{'$set': {'deactivated': True}})
to_return = {'alias': alias}
to_return['response'] = 'success' if result['n'] > 0 else 'fail'
return jsonify(to_return)
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True)
| import json
import random
import string
from flask import Flask, request, jsonify, render_template
from flask.ext.pymongo import PyMongo
from pymongo.errors import DuplicateKeyError
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'kasm'
mongo = PyMongo(app)
@app.route('/')
def hello_world():
return render_template('kasm.html')
@app.route('/create', methods=['POST'])
def create():
def id_generator(size, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in xrange(size))
#post_data = json.loads(request.data)
#email = post_data['email']
email = request.form['email']
inserted = False
while not inserted:
try:
alias = id_generator(8)
mongo.db.redirects.insert({'email': email, 'alias': alias})
except DuplicateKeyError:
pass
else:
inserted = True
to_return = {'email': email,
'encrypt': 'lolwut',
'original': email,
'response': 'success',
'username': alias,
}
return jsonify(to_return)
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True)
|
Add button to the template | 'use strict';
const request = require('request-promise');
const config = require('../../config');
const scraper = require('./scraper');
module.exports = {
getFirstMessagingEntry: (body) => {
const val = body.object == 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].id == config.Facebook.pageId &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0]
;
return val || null;
},
sendTextMessage: (sender, text) => {
const url = text;
const metadata = scraper(url);
return metadata.metadata().then((meta) => {
let messageData = {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [
{
title: 'Test',
image_url: meta.image,
subtitle: 'test',
buttons: [{
type: 'web_url',
url: url,
title: 'Click here'
}]
}
]
}
}
};
console.log(messageData);
return request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: config.Facebook.pageToken},
method: 'POST',
body: {
recipient: {id: sender},
message: messageData,
},
json: true
});
});
}
};
| 'use strict';
const request = require('request-promise');
const config = require('../../config');
const scraper = require('./scraper');
module.exports = {
getFirstMessagingEntry: (body) => {
const val = body.object == 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].id == config.Facebook.pageId &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0]
;
return val || null;
},
sendTextMessage: (sender, text) => {
const url = text;
const metadata = scraper(url);
return metadata.metadata().then((meta) => {
let messageData = {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [
{
title: 'Test',
image_url: meta.image,
subtitle: 'test',
buttons: []
}
]
}
}
};
console.log(messageData);
return request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: config.Facebook.pageToken},
method: 'POST',
body: {
recipient: {id: sender},
message: messageData,
},
json: true
});
});
}
};
|
Set pano popje when straatbeeld exsts | (function () {
'use strict';
angular
.module('atlas')
.controller('MapController', MapController);
MapController.$inject = ['store', 'crsConverter'];
function MapController (store, crsConverter) {
var vm = this;
store.subscribe(update);
update();
function update () {
var state = store.getState();
vm.markers = [];
if (state.search && state.search.location) {
vm.markers.push({
id: 'search',
geometry: convertLocationToGeoJSON(state.search.location),
useAutoFocus: false
});
}
if (state.detail && state.detail.geometry) {
vm.markers.push({
id: 'detail',
geometry: state.detail.geometry,
useAutoFocus: true
});
}
if (state.straatbeeld) {
vm.markers.push({
id: 'straatbeeld_orientation',
geometry: convertLocationToGeoJSON(state.straatbeeld.location),
orientation: state.straatbeeld.heading,
useAutoFocus: false
});
vm.markers.push({
id: 'straatbeeld_person',
geometry: convertLocationToGeoJSON(state.straatbeeld.location),
useAutoFocus: false
});
}
vm.mapState = state.map;
vm.showLayerSelection = state.layerSelection;
}
function convertLocationToGeoJSON (location) {
return {
type: 'Point',
coordinates: crsConverter.wgs84ToRd(location)
};
}
}
})();
| (function () {
'use strict';
angular
.module('atlas')
.controller('MapController', MapController);
MapController.$inject = ['store', 'crsConverter'];
function MapController (store, crsConverter) {
var vm = this;
store.subscribe(update);
update();
function update () {
var state = store.getState();
vm.markers = [];
if (state.search && state.search.location) {
vm.markers.push({
id: 'search',
geometry: convertLocationToGeoJSON(state.search.location),
useAutoFocus: false
});
}
if (state.detail && state.detail.geometry) {
vm.markers.push({
id: 'detail',
geometry: state.detail.geometry,
useAutoFocus: true
});
}
if (state.straatbeeld && angular.isArray(state.straatbeeld.location)) {
vm.markers.push({
id: 'straatbeeld_orientation',
geometry: convertLocationToGeoJSON(state.straatbeeld.location),
orientation: state.straatbeeld.heading,
useAutoFocus: false
});
vm.markers.push({
id: 'straatbeeld_person',
geometry: convertLocationToGeoJSON(state.straatbeeld.location),
useAutoFocus: false
});
}
vm.mapState = state.map;
vm.showLayerSelection = state.layerSelection;
}
function convertLocationToGeoJSON (location) {
return {
type: 'Point',
coordinates: crsConverter.wgs84ToRd(location)
};
}
}
})();
|
Change comp and swap count from int to long | package org.algorithmprac.sort;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
public abstract class AbstractCostAwareSorter extends AbstractSorter implements CostAwareSorter {
private final Stopwatch stopwatch = Stopwatch.createUnstarted();
private long cmpCount = 0;
private long swapCount = 0;
@Override
protected void preProcess(Comparable[] a) {
resetStatistics();
stopwatch.start();
}
private void resetStatistics() {
stopwatch.reset();
cmpCount = 0L;
swapCount = 0L;
}
@Override
protected void postProcess(Comparable[] a) {
stopwatch.stop();
}
@Override
public boolean less(Comparable v, Comparable w) {
++cmpCount;
return super.less(v, w);
}
@Override
public void swap(Comparable[] a, int i, int j) {
++swapCount;
super.swap(a, i, j);
}
public String getReadableCost() {
StringBuilder sb = new StringBuilder();
sb.append("cost is ");
sb.append(stopwatch.toString());
sb.append(", compare count is ");
sb.append(cmpCount);
sb.append(", swap count is ");
sb.append(swapCount);
return sb.toString();
}
public long getCost(TimeUnit timeUnit) {
return stopwatch.elapsed(timeUnit);
}
public long getCmpCount() {
return cmpCount;
}
public long getSwapCount() {
return swapCount;
}
}
| package org.algorithmprac.sort;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
public abstract class AbstractCostAwareSorter extends AbstractSorter implements CostAwareSorter {
private final Stopwatch stopwatch = Stopwatch.createUnstarted();
private int cmpCount = 0;
private int swapCount = 0;
@Override
protected void preProcess(Comparable[] a) {
resetStatistics();
stopwatch.start();
}
private void resetStatistics() {
stopwatch.reset();
cmpCount = 0;
swapCount = 0;
}
@Override
protected void postProcess(Comparable[] a) {
stopwatch.stop();
}
@Override
public boolean less(Comparable v, Comparable w) {
++cmpCount;
return super.less(v, w);
}
@Override
public void swap(Comparable[] a, int i, int j) {
++swapCount;
super.swap(a, i, j);
}
public String getReadableCost() {
StringBuilder sb = new StringBuilder();
sb.append("cost is ");
sb.append(stopwatch.toString());
sb.append(", compare count is ");
sb.append(cmpCount);
sb.append(", swap count is ");
sb.append(swapCount);
return sb.toString();
}
public long getCost(TimeUnit timeUnit) {
return stopwatch.elapsed(timeUnit);
}
public int getCmpCount() {
return cmpCount;
}
public int getSwapCount() {
return swapCount;
}
}
|
Update comment and optional instructions | import sys
from starlette.requests import Request
from starlette.types import Receive, Scope, Send
import rollbar
from .requests import store_current_request
from rollbar.contrib.asgi import ReporterMiddleware as ASGIReporterMiddleware
from rollbar.lib._async import RollbarAsyncError, try_report
class ReporterMiddleware(ASGIReporterMiddleware):
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
try:
store_current_request(scope, receive)
await self.app(scope, receive, send)
except Exception:
if scope['type'] == 'http':
request = Request(scope, receive, send)
# Consuming the request body in Starlette middleware is problematic.
# See: https://github.com/encode/starlette/issues/495#issuecomment-494008175
# Uncomment lines below if you know the risks.
#
# await request.body()
# await request.form()
exc_info = sys.exc_info()
try:
await try_report(exc_info, request)
except RollbarAsyncError:
rollbar.report_exc_info(exc_info, request)
raise
| import sys
from starlette.requests import Request
from starlette.types import Receive, Scope, Send
import rollbar
from .requests import store_current_request
from rollbar.contrib.asgi import ReporterMiddleware as ASGIReporterMiddleware
from rollbar.lib._async import RollbarAsyncError, try_report
class ReporterMiddleware(ASGIReporterMiddleware):
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
try:
store_current_request(scope, receive)
await self.app(scope, receive, send)
except Exception:
if scope['type'] == 'http':
request = Request(scope, receive, send)
# Consuming the request body in Starlette middleware is problematic.
# See: https://github.com/encode/starlette/issues/495#issuecomment-494008175
# Uncomment the line below if you know the risks.
#
# await request.body()
exc_info = sys.exc_info()
try:
await try_report(exc_info, request)
except RollbarAsyncError:
rollbar.report_exc_info(exc_info, request)
raise
|
Update author and maintainer information | # -*- coding: utf-8 -*-
import os
from setuptools import setup
import redis_shard
def read_file(*path):
base_dir = os.path.dirname(__file__)
file_path = (base_dir, ) + tuple(path)
return open(os.path.join(*file_path)).read()
setup(
name="redis-shard",
url="https://pypi.python.org/pypi/redis-shard",
license="BSD License",
author="Zhihu Inc.",
author_email="opensource@zhihu.com",
maintainer="Young King",
maintainer_email="y@zhihu.com",
description="Redis Sharding API",
long_description=(
read_file("README.rst") + "\n\n" +
"Change History\n" +
"==============\n\n" +
read_file("CHANGES.rst")),
version=redis_shard.__version__,
packages=["redis_shard"],
include_package_data=True,
zip_safe=False,
install_requires=['redis'],
tests_require=['Nose'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Operating System :: OS Independent",
"License :: OSI Approved :: BSD License",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
],
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
import redis_shard
def read_file(*path):
base_dir = os.path.dirname(__file__)
file_path = (base_dir, ) + tuple(path)
return open(os.path.join(*file_path)).read()
setup(
name="redis-shard",
url="https://pypi.python.org/pypi/redis-shard",
license="BSD",
author="Zhihu Inc.",
author_email="y@zhihu.com",
description="Redis Sharding API",
long_description=(
read_file("README.rst") + "\n\n" +
"Change History\n" +
"==============\n\n" +
read_file("CHANGES.rst")),
version=redis_shard.__version__,
packages=["redis_shard"],
include_package_data=True,
zip_safe=False,
install_requires=['redis'],
tests_require=['Nose'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Operating System :: OS Independent",
"License :: OSI Approved :: BSD License",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
],
)
|
Fix to allow overriding subject formatting | import logging
from subprocess import Popen, PIPE
class EximHandler(logging.Handler):
"""
A handler class which sends an email using exim for each logging event.
"""
def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"):
"""
Initialize the handler.
"""
logging.Handler.__init__(self)
self.toaddr = toaddr
self.subject = subject
self.exim_path = exim_path
def get_subject(self, record):
"""
Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method.
"""
return self.subject
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified address.
"""
subject = self.get_subject(record)
body = self.format(record)
try:
proc1 = Popen(
['echo', '-e', 'Subject: %s\n\n%s' % (subject, body)],
stdout=PIPE
)
proc2 = Popen(
[self.exim_path, '-odf', '-i', self.toaddr],
stdin=proc1.stdout, stdout=PIPE
)
# Allow proc1 to receive a SIGPIPE if proc2 exits.
proc1.stdout.close()
# Wait for proc2 to exit
proc2.communicate()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.handleError(record)
| import logging
from subprocess import Popen, PIPE
class EximHandler(logging.Handler):
"""
A handler class which sends an email using exim for each logging event.
"""
def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"):
"""
Initialize the handler.
"""
logging.Handler.__init__(self)
self.toaddr = toaddr
self.subject = subject
self.exim_path = exim_path
def getSubject(self, record):
"""
Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method.
"""
return self.subject
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified address.
"""
body = self.format(record)
try:
proc1 = Popen(
['echo', '-e', 'Subject: %s\n\n%s' % (self.subject, body)],
stdout=PIPE
)
proc2 = Popen(
[self.exim_path, '-odf', '-i', self.toaddr],
stdin=proc1.stdout, stdout=PIPE
)
# Allow proc1 to receive a SIGPIPE if proc2 exits.
proc1.stdout.close()
# Wait for proc2 to exit
proc2.communicate()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.handleError(record)
|
refactor(rasterize-list): Update test to improve speed by only writing and unlinking files once | 'use strict';
const expect = require('../../helpers/expect');
const fs = require('fs');
const sizeOf = require('image-size');
const RasterizeList = require('../../../src/utils/rasterize-list');
describe('RasterizeList', function() {
// Hitting the file system is slow
this.timeout(0);
context('when src and toRasterize', () => {
const src = 'node-tests/fixtures/icon.svg';
const toRasterize = [
{
size: 60,
name: 'icon-60',
path: 'tmp/icon-60.png'
}
];
let subject;
before(() => {
subject = RasterizeList({src: src, toRasterize: toRasterize});
});
after(() => {
toRasterize.forEach((rasterize) => {
fs.unlinkSync(rasterize.path);
});
});
it('returns a promise that resolves to an array', (done) => {
expect(subject).to.eventually.be.a('array').notify(done);
});
it('writes the files to rasterize at the right size', (done) => {
subject.then(() => {
toRasterize.forEach((rasterize) => {
expect(fs.existsSync(rasterize.path)).to.equal(true);
expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
});
done();
});
});
});
});
| 'use strict';
const expect = require('../../helpers/expect');
const fs = require('fs');
const sizeOf = require('image-size');
const RasterizeList = require('../../../src/utils/rasterize-list');
describe('RasterizeList', function() {
// Hitting the file system is slow
this.timeout(0);
context('when src and toRasterize', () => {
const src = 'node-tests/fixtures/icon.svg';
const toRasterize = [
{
size: 60,
name: 'icon-60',
path: 'tmp/icon-60.png'
}
];
afterEach(() => {
toRasterize.forEach((rasterize) => {
fs.unlinkSync(rasterize.path);
});
});
it('returns a promise that resolves to an array', (done) => {
expect(
RasterizeList({src: src, toRasterize: toRasterize})
).to.eventually.be.a('array').notify(done);
});
it('writes the files to rasterize at the right size', (done) => {
RasterizeList({src: src, toRasterize: toRasterize}).then(() => {
toRasterize.forEach((rasterize) => {
expect(fs.existsSync(rasterize.path)).to.equal(true);
expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
});
done();
});
});
});
});
|
Fix line endings in CSV and stdout typo | #!/usr/bin/env python
"""Calculate QuadKey for TSV file and append it as column
Usage:
calculate_quad_key.py <list_file>
calculate_quad_key.py (-h | --help)
calculate_quad_key.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(sys.stdout, delimiter='\t')
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line.strip(),
quad_tree(int(x), int(y), int(z))]
)
| #!/usr/bin/env python
"""Calculate QuadKey for TSV file and append it as column
Usage:
calculate_quad_key.py <list_file>
calculate_quad_key.py (-h | --help)
calculate_quad_key.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
import system
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(system.out)
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line,
quad_tree(int(x), int(y), int(z))]
)
|
Fix the relative path to vendor resources | <?php
namespace InfyOm\RoutesExplorer;
use Illuminate\Support\ServiceProvider;
class RoutesExplorerServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$configPath = __DIR__ . '/../config/routes_explorer.php';
$this->publishes([
$configPath => config_path('infyom/routes_explorer.php'),
]);
$migrationPath = __DIR__ . '/../stubs/migration.stub';
$fileName = date('Y_m_d_His') . '_' . 'create_api_calls_count_table.php';
$this->publishes([
$migrationPath => database_path('migrations/' . $fileName),
], 'migrations');
$viewPath = __DIR__ . '/../views/routes.blade.php';
$this->publishes([
$viewPath => resource_path('views/routes/routes.blade.php'),
], 'views');
$this->loadViewsFrom(__DIR__ . '/../views', 'infyomlabs');
if (config('infyom.routes_explorer.enable_explorer')) {
$this->app['router']->get(
config('infyom.routes_explorer.route'),
"\\InfyOm\\RoutesExplorer\\RoutesExplorer@showRoutes"
);
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
} | <?php
namespace InfyOm\RoutesExplorer;
use Illuminate\Support\ServiceProvider;
class RoutesExplorerServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$configPath = __DIR__ . './../config/routes_explorer.php';
$this->publishes([
$configPath => config_path('infyom/routes_explorer.php'),
]);
$migrationPath = __DIR__ . './../stubs/migration.stub';
$fileName = date('Y_m_d_His') . '_' . 'create_api_calls_count_table.php';
$this->publishes([
$migrationPath => database_path('migrations/' . $fileName),
], 'migrations');
$viewPath = __DIR__ . './../views/routes.blade.php';
$this->publishes([
$viewPath => resource_path('views/routes/routes.blade.php'),
], 'views');
$this->loadViewsFrom(__DIR__ . './../views', 'infyomlabs');
if (config('infyom.routes_explorer.enable_explorer')) {
$this->app['router']->get(
config('infyom.routes_explorer.route'),
"\\InfyOm\\RoutesExplorer\\RoutesExplorer@showRoutes"
);
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
} |
Update description of the blog sidebar snippet. | from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'blog-sidebar',
'name': 'Blog sidebar featured content.',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'profile-welcome',
'name': 'Welcome message in the profile',
'body': 'Lorem ipsum',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
| from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'blog-sidebar',
'name': 'Dynamic content',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'profile-welcome',
'name': 'Welcome message in the profile',
'body': 'Lorem ipsum',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
|
Replace forEach with while for wider reach | (function () {
function descend(path, o) {
var step = path.shift();
if (typeof(o[step]) === "undefined") {
throw new Error("Broken descend path");
}
while (path.length > 0) {
if (typeof(o[step]) !== "object") {
throw new Error("Invalid descend path");
}
return descend(path, o[step]);
}
return o[step];
}
define({
load: function (name, req, load, config) {
var mod, x;
if (name.indexOf("?") === -1) {
load.error("No params specified");
} else {
x = name.slice(0, name.indexOf("?")).split(",");
mod = name.slice(name.indexOf("?") + 1);
req([mod], function (inc) {
var ret = {};
var path;
try {
if (x.length > 1) {
while (x.length > 0) {
path = x.shift().split(".");
ret[path[path.length - 1]] = descend(path, inc);
}
} else {
path = x[0].split(".");
ret = descend(path, inc);
}
load(ret);
} catch (e) {
load.error(e.message);
}
});
}
}
});
}());
| (function () {
function descend(path, o) {
var step = path.shift();
if (typeof(o[step]) === "undefined") {
throw new Error("Broken descend path");
}
while (path.length > 0) {
if (typeof(o[step]) !== "object") {
throw new Error("Invalid descend path");
}
return descend(path, o[step]);
}
return o[step];
}
define({
load: function (name, req, load, config) {
var mod, x;
if (name.indexOf("?") === -1) {
load.error("No params specified");
} else {
x = name.slice(0, name.indexOf("?")).split(",");
mod = name.slice(name.indexOf("?") + 1);
req([mod], function (inc) {
var ret = {};
var path;
try {
if (x.length > 1) {
x.forEach(function (pname) {
path = pname.split(".");
ret[path[path.length - 1]] = descend(path, inc);
});
} else {
path = x[0].split(".");
ret = descend(path, inc);
}
load(ret);
} catch (e) {
load.error(e.message);
}
});
}
}
});
}());
|
Add pseudo bar chart using D3 scales with JSX | import React from "react";
import ReactDOM from "react-dom";
import tabify from "../../utils/tabify";
import * as d3 from "d3";
import "./BarGraph.css";
export default class BarGraph extends React.Component {
constructor(){
super();
this.xScale = d3.scaleBand();
this.yScale = d3.scaleLinear();
}
render() {
const {
xScale,
yScale,
props: {
response,
configuration,
onBarClick,
width,
height
}
} = this;
if (!response || response.error)
return;
const data = tabify(response.results);
const properties = configuration.data;
const { xColumn, yColumn } = properties;
xScale
.domain(data.map(function (d){ return d[xColumn]; }))
.range([0, width]);
yScale
.domain([0, d3.max(data, function (d){ return d[yColumn] })])
.range([height, 0]);
console.log(xScale.domain())
console.log(xScale.range())
return (
<div className="bar-graph">
<svg width={width} height={height}>
{data.map((d, i) => (
<rect
key={ i }
x={ xScale(d[xColumn]) }
y={ yScale(d[yColumn]) }
width={ xScale.bandwidth() }
height={ height - yScale(d[yColumn]) }
/>
))}
</svg>
</div>
);
}
}
BarGraph.propTypes = {
configuration: React.PropTypes.object,
response: React.PropTypes.object
};
| import React from "react";
import ReactDOM from "react-dom";
import tabify from "../../utils/tabify";
import * as d3 from "d3";
import "./BarGraph.css";
export default class BarGraph extends React.Component {
render() {
const { response, configuration, onBarClick } = this.props;
const { width, height } = this.props;
if (!response || response.error)
return;
const data = tabify(response.results);
const properties = configuration.data;
return (
<div className="bar-graph">
<svg width={width} height={height}>
{data.map((d, i) => (
<rect
x={i*50}
y="0"
width="40"
height="40"
/>
))}
</svg>
</div>
);
}
}
BarGraph.propTypes = {
configuration: React.PropTypes.object,
response: React.PropTypes.object
};
|
Remove support for deprecated Python versions. | #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long_description,
author="Russell Keith-Magee",
author_email="russell@keith-magee.com",
url='http://github.com/freakboy3742/pyspamsum/',
license="New BSD",
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Text Processing',
'Topic :: Utilities',
],
ext_modules=[
Extension(
"spamsum", [
"pyspamsum.c",
"spamsum.c",
"edit_dist.c",
]
)
],
test_suite='tests',
)
| #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long_description,
author="Russell Keith-Magee",
author_email="russell@keith-magee.com",
url='http://github.com/freakboy3742/pyspamsum/',
license="New BSD",
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'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',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Text Processing',
'Topic :: Utilities',
],
ext_modules=[
Extension(
"spamsum", [
"pyspamsum.c",
"spamsum.c",
"edit_dist.c",
]
)
],
test_suite='tests',
)
|
Use “helpers” as independent module for “tests.runtests” environment | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os
from helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.utils import TmpDirectory
class Test(TestCase):
def test_refresh(self):
with TmpDirectory() as dir:
old_dir = os.getcwd()
try:
os.chdir(dir.get_name())
db = Db(".pc")
db.create()
backup = os.path.join(".pc", "patch")
os.mkdir(backup)
make_file(b"", backup, "file")
db.add_patch(Patch("patch"))
db.save()
make_file(b"", "patch")
make_file(b"added\n", "file")
cmd = quilt.refresh.Refresh(".", ".pc", ".")
cmd.refresh()
with open("patch", "r") as patch:
self.assertTrue(patch.read(30))
finally:
os.chdir(old_dir)
| # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os
from .helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.utils import TmpDirectory
class Test(TestCase):
def test_refresh(self):
with TmpDirectory() as dir:
old_dir = os.getcwd()
try:
os.chdir(dir.get_name())
db = Db(".pc")
db.create()
backup = os.path.join(".pc", "patch")
os.mkdir(backup)
make_file(b"", backup, "file")
db.add_patch(Patch("patch"))
db.save()
make_file(b"", "patch")
make_file(b"added\n", "file")
cmd = quilt.refresh.Refresh(".", ".pc", ".")
cmd.refresh()
with open("patch", "r") as patch:
self.assertTrue(patch.read(30))
finally:
os.chdir(old_dir)
|
Update dependency jsonschema to v2.6.0 | # -*- coding: utf-8 -*-
import os
import sys
from setuptools import (
find_packages,
setup,
)
here = os.path.dirname(__file__)
requires = [
'jsonschema==2.6.0',
]
if sys.version_info <= (3, 5):
requires.append('zipp == 1.2.0')
tests_require = [
'pytest',
'pytest-cov',
'pytest-flake8',
]
def _read(name):
return open(os.path.join(here, name)).read()
setup(
name='jsmapper',
version='0.1.9',
description='A Object - JSON Schema Mapper.',
long_description=_read("README.rst"),
license='MIT',
url='https://github.com/yosida95/python-jsmapper',
author='Kohei YOSHIDA',
author_email='kohei@yosida95.com',
packages=find_packages(),
python_requires='>= 3.5',
install_requires=requires,
tests_require=tests_require,
extras_require={
'testing': tests_require,
},
test_suite='jsmapper',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| # -*- coding: utf-8 -*-
import os
import sys
from setuptools import (
find_packages,
setup,
)
here = os.path.dirname(__file__)
requires = [
'jsonschema==2.4.0',
]
if sys.version_info <= (3, 5):
requires.append('zipp == 1.2.0')
tests_require = [
'pytest',
'pytest-cov',
'pytest-flake8',
]
def _read(name):
return open(os.path.join(here, name)).read()
setup(
name='jsmapper',
version='0.1.9',
description='A Object - JSON Schema Mapper.',
long_description=_read("README.rst"),
license='MIT',
url='https://github.com/yosida95/python-jsmapper',
author='Kohei YOSHIDA',
author_email='kohei@yosida95.com',
packages=find_packages(),
python_requires='>= 3.5',
install_requires=requires,
tests_require=tests_require,
extras_require={
'testing': tests_require,
},
test_suite='jsmapper',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Upgrade ldap3 1.0.4 => 1.1.2 | import sys
from setuptools import find_packages, setup
with open('VERSION') as version_fp:
VERSION = version_fp.read().strip()
install_requires = [
'django-local-settings>=1.0a14',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='consultants@pdx.edu',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2016.2.28',
'ldap3>=1.1.2',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
with open('VERSION') as version_fp:
VERSION = version_fp.read().strip()
install_requires = [
'django-local-settings>=1.0a14',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='consultants@pdx.edu',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2016.2.28',
'ldap3>=1.0.4',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Move hide class to collection to remove margin-top spaces on hidden collections
SRFCMSAL-2500 | export function init() {
let triggers = document.querySelectorAll('.js-filter-bar-trigger');
for (let i = 0; i < triggers.length; i++) {
let currentTrigger = triggers[i];
currentTrigger.addEventListener('click', function(e) {
e.preventDefault();
const blockID = this.getAttribute('data-blockid'),
allID = 'a2z-all',
letterClass = 'filter-bar__letter',
letterActiveClass = 'filter-bar__letter--active',
blockClass = 'a2z-lists__block',
hiddenClass = 'a2z-lists__block--hidden';
// styles clicked filter-bar-Element as active
document.querySelectorAll('.' + letterClass).forEach(function(thisNode) {
thisNode.classList.remove(letterActiveClass);
});
this.classList.add(letterActiveClass);
// show/hide selected Block of Elements
if (blockID === allID) {
document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) {
thisNode.closest('.js-collection').classList.remove(hiddenClass);
});
} else {
document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) {
thisNode.closest('.js-collection').classList.remove(hiddenClass);
});
document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) {
thisNode.closest('.js-collection').classList.add(hiddenClass);
});
}
});
};
}
| export function init() {
let triggers = document.querySelectorAll('.js-filter-bar-trigger');
for (let i = 0; i < triggers.length; i++) {
let currentTrigger = triggers[i];
currentTrigger.addEventListener('click', function(e) {
e.preventDefault();
const blockID = this.getAttribute('data-blockid'),
allID = 'a2z-all',
letterClass = 'filter-bar__letter',
letterActiveClass = 'filter-bar__letter--active',
blockClass = 'a2z-lists__block',
hiddenClass = 'a2z-lists__block--hidden';
// styles clicked filter-bar-Element as active
document.querySelectorAll('.' + letterClass).forEach(function(thisNode) {
thisNode.classList.remove(letterActiveClass);
});
this.classList.add(letterActiveClass);
// show/hide selected Block of Elements
if (blockID == allID) {
document.querySelectorAll('.' + hiddenClass).forEach(function(thisNode) {
thisNode.classList.remove(hiddenClass);
});
} else {
document.querySelectorAll('.' + blockClass + '[data-block="' + blockID + '"]').forEach(function(thisNode) {
thisNode.classList.remove(hiddenClass);
});
document.querySelectorAll('.' + blockClass + ':not([data-block="' + blockID + '"])').forEach(function(thisNode) {
thisNode.classList.add(hiddenClass);
});
}
});
};
}
|
Fix encoding (thanks to Yasushi Masuda) | # -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
'''
elements=[]
lines=data.splitlines()
for line in lines:
lexer=shlex.shlex(line)
lexer.whitespace+=','
tokens=list(lexer)
command=tokens[0]
if command == 'PageBreak':
if len(tokens)==1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]),int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now
#def depth (node):
# if node.parent==None:
# return 0
# else:
# return 1+depth(node.parent)
| #$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
'''
elements=[]
lines=data.splitlines()
for line in lines:
lexer=shlex.shlex(line)
lexer.whitespace+=','
tokens=list(lexer)
command=tokens[0]
if command == 'PageBreak':
if len(tokens)==1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]),int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now
#def depth (node):
# if node.parent==None:
# return 0
# else:
# return 1+depth(node.parent)
|
Change the way to instaniate models | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
payload_data = json.loads(payload)
except ValueError:
return 'Bad request', 400
hook_data = parse_hook_data(payload_data)
repository = db.session.query(Repository).filter_by(
name=hook_data['repo_name'], user=hook_data['repo_user']
).first()
if repository is None:
repository = Repository(
name=hook_data['repo_name'],
user=hook_data['repo_user'],
url=hook_data['repo_url']
)
db.session.add(repository)
db.session.commit()
commit = db.session.query(Commit).filter_by(
hash=hook_data['hash'], repository_id=repository.id
).first()
if commit is None:
commit = Commit(
repository_id=repository.id,
hash=hook_data['hash'],
ref=hook_data['ref'],
compare_url=hook_data['compare_url'],
committer_name=hook_data['committer_name'],
committer_email=hook_data['committer_email'],
message=hook_data['message']
)
db.session.add(commit)
db.session.commit()
return 'OK'
| from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
payload_data = json.loads(payload)
except ValueError:
return 'Bad request', 400
hook_data = parse_hook_data(payload_data)
repository = db.session.query(Repository).filter_by(
name=hook_data['repo_name'], user=hook_data['repo_user']
).first()
if repository is None:
repository = Repository()
repository.name = hook_data['repo_name']
repository.user = hook_data['repo_user']
repository.url = hook_data['repo_url']
db.session.add(repository)
db.session.commit()
commit = db.session.query(Commit).filter_by(
hash=hook_data['hash'], repository_id=repository.id
).first()
if commit is None:
commit = Commit()
commit.repository_id = repository.id
commit.hash = hook_data['hash']
commit.ref = hook_data['ref']
commit.compare_url = hook_data['compare_url']
commit.committer_name = hook_data['committer_name']
commit.committer_email = hook_data['committer_email']
commit.message = hook_data['message']
db.session.add(commit)
db.session.commit()
return 'OK'
|
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing. | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
| #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
Fix path to css files | module.exports = function(grunt) {
// Chargement automatique de tous nos modules
require('load-grunt-tasks')(grunt);
// Configuration des plugins
grunt.initConfig({
// Concat and compress CSS
cssmin: {
combine: {
options:{
report: 'gzip',
keepSpecialComments: 0
},
files: {
'web/built/min.css': [
'web/vendor/foundation/css/normalize.css',
'web/vendor/foundation/css/foundation.css',
'web/vendor/mapbox.js/mapbox.css',
'src/Bonnes/*/Resources/public/css/style.css'
]
}
}
},
// Minify JS
uglify: {
options: {
mangle: false,
sourceMap: true,
sourceMapName: 'web/built/app.map'
},
dist: {
files: {
'web/built/app.min.js':[
'web/vendor/modernizr/modernizr.js',
'web/vendor/mapbox.js/mapbox.js',
'web/bundles/fosjsrouting/js/router.js'
]
}
}
},
// Allow the grunt watch command
watch: {
css: {
files: ['src/Bonnes/*/Resources/public/css/*.css'],
tasks: ['css']
},
javascript: {
files: ['src/Bonnes/*/Resources/public/js/*.js'],
tasks: ['javascript']
}
}
});
grunt.registerTask('default', ['css', 'javascript']);
grunt.registerTask('css', ['cssmin']);
grunt.registerTask('javascript', ['uglify']);
};
| module.exports = function(grunt) {
// Chargement automatique de tous nos modules
require('load-grunt-tasks')(grunt);
// Configuration des plugins
grunt.initConfig({
// Concat and compress CSS
cssmin: {
combine: {
options:{
report: 'gzip',
keepSpecialComments: 0
},
files: {
'web/built/min.css': [
'web/vendor/foundation/normalize.css',
'web/vendor/foundation/foundation.css',
'web/vendor/mapbox.js/mapbox.css',
'src/Bonnes/*/Resources/public/css/style.css'
]
}
}
},
// Minify JS
uglify: {
options: {
mangle: false,
sourceMap: true,
sourceMapName: 'web/built/app.map'
},
dist: {
files: {
'web/built/app.min.js':[
'web/vendor/modernizr/modernizr.js',
'web/vendor/mapbox.js/mapbox.js',
'web/bundles/fosjsrouting/js/router.js'
]
}
}
},
// Allow the grunt watch command
watch: {
css: {
files: ['src/Bonnes/*/Resources/public/css/*.css'],
tasks: ['css']
},
javascript: {
files: ['src/Bonnes/*/Resources/public/js/*.js'],
tasks: ['javascript']
}
}
});
grunt.registerTask('default', ['css', 'javascript']);
grunt.registerTask('css', ['cssmin']);
grunt.registerTask('javascript', ['uglify']);
};
|
Make navbar fixed and align links right | import React from 'react';
import {
Collapse,
Nav,
Navbar,
NavbarBrand,
NavbarToggler,
NavItem,
NavLink
} from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGithub, faLinkedin } from '@fortawesome/free-brands-svg-icons'
export default class Navigation extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<Navbar color="dark" dark expand="md" fixed="top">
<NavbarBrand href="/">Mike Thomas</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="mr-auto" navbar>
<NavItem>
<NavLink href="https://github.com/mikepthomas">
<FontAwesomeIcon icon={ faGithub } />
GitHub profile
</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://www.linkedin.com/in/mikepaulthomas">
<FontAwesomeIcon icon={ faLinkedin } />
LinkedIn profile
</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
);
}
}
| import React from 'react';
import {
Collapse,
Nav,
Navbar,
NavbarBrand,
NavbarToggler,
NavItem,
NavLink
} from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGithub, faLinkedin } from '@fortawesome/free-brands-svg-icons'
export default class Navigation extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<Navbar color="dark" dark expand="md">
<NavbarBrand href="/">Mike Thomas</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink href="https://github.com/mikepthomas">
<FontAwesomeIcon icon={ faGithub } />
GitHub profile
</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://www.linkedin.com/in/mikepaulthomas">
<FontAwesomeIcon icon={ faLinkedin } />
LinkedIn profile
</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
);
}
}
|
Move reset to on stop | let videoImage = document.getElementById('video_image');
videoImage.src = `http://${document.domain}:8080/?action=stream`;
let cameraJoystick = {
zone: videoImage,
color: 'red'
};
let cameraJoystickManager = nipplejs.create(cameraJoystick);
const clickTimeout = 500;
var lastStopClick = Date.now();
cameraJoystickManager.on('added',
function (evt, nipple) {
nipple.on('move',
function (evt, arg) {
var json = JSON.stringify({
joystickType: 'camera',
angle: arg.angle.radian,
MessageType: 'movement',
distance: arg.distance
});
serverSocket.send(json);
});
nipple.on('start',
function () {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'start' });
serverSocket.send(json);
});
nipple.on('end',
function () {
if (Date.now() - lastStopClick < clickTimeout) {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'reset' });
serverSocket.send(json);
} else {
var json = JSON.stringify({
joystickType: 'camera',
MessageType: 'stop'
});
serverSocket.send(json);
}
lastStopClick = Date.now();
});
}); | let videoImage = document.getElementById('video_image');
videoImage.src = `http://${document.domain}:8080/?action=stream`;
let cameraJoystick = {
zone: videoImage,
color: 'red'
};
let cameraJoystickManager = nipplejs.create(cameraJoystick);
const clickTimeout = 500;
var lastStartClick = Date.now();
cameraJoystickManager.on('added',
function (evt, nipple) {
nipple.on('move',
function (evt, arg) {
var json = JSON.stringify({
joystickType: 'camera',
angle: arg.angle.radian,
MessageType: 'movement',
distance: arg.distance
});
serverSocket.send(json);
});
nipple.on('start',
function () {
if (Date.now() - lastStartClick < clickTimeout) {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'reset' });
serverSocket.send(json);
} else {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'start' });
serverSocket.send(json);
}
lastStartClick = Date.now();
});
nipple.on('end',
function () {
var json = JSON.stringify({
joystickType: 'camera',
MessageType: 'stop'
});
serverSocket.send(json);
});
}); |
Remove broken leading and trailing characters. | #!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
# copied from:
# https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122
self.logger.debug("Decrypting password data using: %s", keyfile)
value = password_data
if not value:
return ''
# Note: Somewhere in the param transformation pipeline line break and
# carrieage return characters get messed up
value = value.strip('\\r').strip('\\n')
self.logger.debug('Encrypted value: "%s"' % (value))
value = base64.b64decode(value)
try:
with open(keyfile) as pk_file:
pk_contents = pk_file.read()
private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
value = rsa.decrypt(value, private_key)
return value.decode('utf-8')
except Exception:
msg = ('Unable to decrypt password data using '
'provided private key file: {}').format(keyfile)
self.logger.debug(msg, exc_info=True)
raise ValueError(msg)
| #!/usr/bin/env python
import base64
import rsa
import six
from st2common.runners.base_action import Action
class AwsDecryptPassworData(Action):
def run(self, keyfile, password_data):
# copied from:
# https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122
self.logger.debug("Decrypting password data using: %s", keyfile)
value = password_data
if not value:
return ''
# Hack because somewhere in the Mistral parameter "publish" pipeline, we
# strip trailing and leading whitespace from a string which results in
# an invalid base64 string
if not value.startswith('\r\n'):
value = '\r\n' + value
if not value.endswith('\r\n'):
value = value + '\r\n'
self.logger.debug('Encrypted value: "%s"' % (value))
value = base64.b64decode(value)
try:
with open(keyfile) as pk_file:
pk_contents = pk_file.read()
private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
value = rsa.decrypt(value, private_key)
return value.decode('utf-8')
except Exception:
msg = ('Unable to decrypt password data using '
'provided private key file: {}').format(keyfile)
self.logger.debug(msg, exc_info=True)
raise ValueError(msg)
|
Add uuid to identifier in test script | from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
|
Adjust for compatibility with Python 2.5 | try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| import collections
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
|
Revert "Revert "Last codestyle fix (I hope)""
This reverts commit f57f550268ef23ccb74c6b4da6f4e0cb4d515179. | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework;
use PHPUnit\Util\Test as TestUtil;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class DataProviderTestSuite extends TestSuite
{
/**
* @var string[]
*/
private $dependencies = [];
/**
* @param string[] $dependencies
*/
public function setDependencies(array $dependencies): void
{
$this->dependencies = $dependencies;
foreach ($this->tests as $test) {
if (!$test instanceof TestCase) {
continue;
}
$test->setDependencies($dependencies);
}
}
public function getDependencies(): array
{
return $this->dependencies;
}
public function hasDependencies(): bool
{
return \count($this->dependencies) > 0;
}
/**
* Returns the size of the each test created using the data provider(s)
*
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function getSize(): int
{
[$className, $methodName] = \explode('::', $this->getName());
/* @psalm-suppress ArgumentTypeCoercion */
return TestUtil::getSize($className, $methodName);
}
}
| <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework;
use PHPUnit\Util\Test as TestUtil;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class DataProviderTestSuite extends TestSuite
{
/**
* @var string[]
*/
private $dependencies = [];
/**
* @param string[] $dependencies
*/
public function setDependencies(array $dependencies): void
{
$this->dependencies = $dependencies;
foreach ($this->tests as $test) {
if (!$test instanceof TestCase) {
continue;
}
$test->setDependencies($dependencies);
}
}
public function getDependencies(): array
{
return $this->dependencies;
}
public function hasDependencies(): bool
{
return \count($this->dependencies) > 0;
}
/**
* Returns the size of the each test created using the data provider(s)
*
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function getSize(): int
{
[$className, $methodName] = \explode('::', $this->getName());
/** @psalm-suppress ArgumentTypeCoercion */
return TestUtil::getSize($className, $methodName);
}
}
|
Fix JS to use 2-space tabs | $(function () {
var params = {'data_type': '23andme_names'};
$.ajax({
'type': 'GET',
'url': '/json-data/',
'data': params,
'success': function(data) {
if (data.profiles && data.profiles.length > 0) {
for (var i = 0; i < data.profiles.length; i++) {
var radioElem = $('<input />');
radioElem.attr({'type' : 'radio',
'name' : 'profile_id',
'value' : data.profiles[i].id});
if (data.profiles.length == 1) {
radioElem.attr('checked', true);
}
var labelElem = $('<label></label>');
labelElem.append(radioElem);
labelElem.append(data.profiles[i].first_name + ' ' +
data.profiles[i].last_name);
var divElem = $('<div></div>');
divElem.attr('class', 'radio');
divElem.append(labelElem);
$("#23andme-list-profiles").append(divElem);
}
$("#load-23andme-waiting").hide();
$("#23andme-complete-submit").css('visibility', 'visible');
}
}
});
});
| $(function () {
var params = {'data_type': '23andme_names'};
$.ajax({
'type': 'GET',
'url': '/json-data/',
'data': params,
'success': function(data) {
if (data.profiles && data.profiles.length > 0) {
for (var i = 0; i < data.profiles.length; i++) {
var radioElem = $('<input />');
radioElem.attr({'type' : 'radio',
'name' : 'profile_id',
'value' : data.profiles[i].id});
if (data.profiles.length == 1) {
radioElem.attr('checked', true);
}
var labelElem = $('<label></label>');
labelElem.append(radioElem);
labelElem.append(data.profiles[i].first_name + ' ' +
data.profiles[i].last_name);
var divElem = $('<div></div>');
divElem.attr('class', 'radio');
divElem.append(labelElem);
$("#23andme-list-profiles").append(divElem);
}
$("#load-23andme-waiting").hide();
$("#23andme-complete-submit").css('visibility', 'visible');
}
}
});
});
|
Remove person link in gadget | <?php
$gadgets = Witi::fetchGadgets();
?>
<ul class="gadgets list">
<li class="col-md-2 col-sm-4 col-xs-6 person add">
<a class="add-trigger">
<figure class="image">
<img src="img/white_bg.jpg" alt="">
</figure>
<div class="icon-wrapper">
<i class="glyphicon glyphicon-plus"></i>
</div>
<h3 class="title">Add new gadget</h3>
</a>
</li>
<?php foreach ($gadgets as $gadget) { ?>
<li class="col-md-2 col-sm-4 col-xs-6 gadget">
<?php if ($gadget['image']) { ?>
<figure class="image">
<img src="storage/thumb/<?php print $gadget['image']; ?>" alt="">
<?php $people = Witi::fetchPeopleById($gadget['personId']); ?>
<?php if ($people) { ?>
<div class="people">
<div>
<ul>
<?php foreach ($people as $person) { ?>
<li><?php print $person['name']; ?></li>
<?php } ?>
</ul>
</div>
</div>
<?php }; ?>
</figure>
<?php } ?>
<h3 class="title"><?php print $gadget['name']; ?></h3>
</li>
<?php } ?>
</ul>
<?php require_once 'views/parts/add_gadget.php'; ?>
| <?php
$gadgets = Witi::fetchGadgets();
?>
<ul class="gadgets list">
<li class="col-md-2 col-sm-4 col-xs-6 person add">
<a class="add-trigger">
<figure class="image">
<img src="img/white_bg.jpg" alt="">
</figure>
<div class="icon-wrapper">
<i class="glyphicon glyphicon-plus"></i>
</div>
<h3 class="title">Add new gadget</h3>
</a>
</li>
<?php foreach ($gadgets as $gadget) { ?>
<li class="col-md-2 col-sm-4 col-xs-6 gadget">
<?php if ($gadget['image']) { ?>
<figure class="image">
<img src="storage/thumb/<?php print $gadget['image']; ?>" alt="">
<?php $people = Witi::fetchPeopleById($gadget['personId']); ?>
<?php if ($people) { ?>
<div class="people">
<div>
<ul>
<?php foreach ($people as $person) { ?>
<li><a href="/?view=person&id=<?php print $person['id']; ?>"><?php print $person['name']; ?></a></li>
<?php } ?>
</ul>
</div>
</div>
<?php }; ?>
</figure>
<?php } ?>
<h3 class="title"><?php print $gadget['name']; ?></h3>
</li>
<?php } ?>
</ul>
<?php require_once 'views/parts/add_gadget.php'; ?>
|
Fix a typo on error message | import requests
import os
from .endpoints import *
class UnauthorizedToken(Exception):
pass
class ReviewsAPI:
def __init__(self):
token = os.environ['UDACITY_AUTH_TOKEN']
self.headers = {'Authorization': token, 'Content-Length': '0'}
def execute(self, request):
try:
raw_response = request()
response = raw_response.json()
raw_response.raise_for_status()
return response
except requests.exceptions.HTTPError:
raise UnauthorizedToken('Maybe it\'s time to change your token!')
def certifications(self):
return self.execute(lambda : requests.get(CERTIFICATIONS_URL, headers=self.headers))
def certified_languages(self):
response = self.execute(lambda : requests.get(REVIEWER_URL, headers=self.headers))
return [language for language in response['application']['languages']]
def request_reviews(self, certifications_list):
projects = self.projects_with_languages(certifications_list)
return self.execute(lambda : requests.post(SUBMISSION_REQUESTS_URL, json=projects, headers=self.headers))
def projects_with_languages(self, certifications_list):
languages_list = self.certified_languages()
projects_list = [{'project_id': project_id, 'language': language} for project_id in certifications_list for language in languages_list]
return {'projects': projects_list}
| import requests
import os
from .endpoints import *
class UnauthorizedToken(Exception):
pass
class ReviewsAPI:
def __init__(self):
token = os.environ['UDACITY_AUTH_TOKEN']
self.headers = {'Authorization': token, 'Content-Length': '0'}
def execute(self, request):
try:
raw_response = request()
response = raw_response.json()
raw_response.raise_for_status()
return response
except requests.exceptions.HTTPError:
raise UnauthorizedToken('Maybe it\'s time to change you token!')
def certifications(self):
return self.execute(lambda : requests.get(CERTIFICATIONS_URL, headers=self.headers))
def certified_languages(self):
response = self.execute(lambda : requests.get(REVIEWER_URL, headers=self.headers))
return [language for language in response['application']['languages']]
def request_reviews(self, certifications_list):
projects = self.projects_with_languages(certifications_list)
return self.execute(lambda : requests.post(SUBMISSION_REQUESTS_URL, json=projects, headers=self.headers))
def projects_with_languages(self, certifications_list):
languages_list = self.certified_languages()
projects_list = [{'project_id': project_id, 'language': language} for project_id in certifications_list for language in languages_list]
return {'projects': projects_list}
|
Add missing import for sys | from gengine.app.tests import db as db
from gengine.metadata import init_declarative_base, init_session
import unittest
import os
import pkgutil
import testing.redis
import logging
import sys
log = logging.getLogger(__name__)
init_session()
init_declarative_base()
__path__ = [x[0] for x in os.walk(os.path.dirname(__file__))]
def create_test_suite():
suite = unittest.TestSuite()
for imp, modname, _ in pkgutil.walk_packages(__path__):
mod = imp.find_module(modname).load_module(modname)
for test in unittest.defaultTestLoader.loadTestsFromModule(mod):
suite.addTests(test)
return suite
if __name__=="__main__":
exit = 1
try:
redis = testing.redis.RedisServer()
from gengine.base.cache import setup_redis_cache
dsn = redis.dsn()
setup_redis_cache(dsn["host"], dsn["port"], dsn["db"])
from gengine.app.cache import init_caches
init_caches()
db.setupDB()
testSuite = create_test_suite()
text_runner = unittest.TextTestRunner(failfast=True).run(testSuite)
if text_runner.wasSuccessful():
exit = 0
finally:
try:
db.unsetupDB()
except:
log.exception()
try:
redis.stop()
except:
log.exception()
sys.exit(exit)
| from gengine.app.tests import db as db
from gengine.metadata import init_declarative_base, init_session
import unittest
import os
import pkgutil
import testing.redis
import logging
log = logging.getLogger(__name__)
init_session()
init_declarative_base()
__path__ = [x[0] for x in os.walk(os.path.dirname(__file__))]
def create_test_suite():
suite = unittest.TestSuite()
for imp, modname, _ in pkgutil.walk_packages(__path__):
mod = imp.find_module(modname).load_module(modname)
for test in unittest.defaultTestLoader.loadTestsFromModule(mod):
suite.addTests(test)
return suite
if __name__=="__main__":
exit = 1
try:
redis = testing.redis.RedisServer()
from gengine.base.cache import setup_redis_cache
dsn = redis.dsn()
setup_redis_cache(dsn["host"], dsn["port"], dsn["db"])
from gengine.app.cache import init_caches
init_caches()
db.setupDB()
testSuite = create_test_suite()
text_runner = unittest.TextTestRunner(failfast=True).run(testSuite)
if text_runner.wasSuccessful():
exit = 0
finally:
try:
db.unsetupDB()
except:
log.exception()
try:
redis.stop()
except:
log.exception()
sys.exit(exit)
|
Move from celery task to regular-old function | import urlparse
import requests
from celery.utils.log import get_task_logger
from api.base import settings
logger = get_task_logger(__name__)
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
def ban_url(url):
timeout = 0.5 # 500ms timeout for bans
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, timeout=timeout, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed: {}'.format(
url,
response.text
))
| import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from api.base import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed: {}'.format(
url,
response.text
))
|
Add better description to built-in Home
Summary: Ref T12174. This could be a little more verbose.
Test Plan: Review Global Menu Items
Reviewers: epriestley
Reviewed By: epriestley
Subscribers: Korvin
Maniphest Tasks: T12174
Differential Revision: https://secure.phabricator.com/D17294 | <?php
final class PhabricatorHomeProfileMenuItem
extends PhabricatorProfileMenuItem {
const MENUITEMKEY = 'home.dashboard';
public function getMenuItemTypeName() {
return pht('Built-in Homepage');
}
private function getDefaultName() {
return pht('Home');
}
public function canMakeDefault(
PhabricatorProfileMenuItemConfiguration $config) {
return true;
}
public function getDisplayName(
PhabricatorProfileMenuItemConfiguration $config) {
$name = $config->getMenuItemProperty('name');
if (strlen($name)) {
return $name;
}
return $this->getDefaultName();
}
public function newPageContent() {
$viewer = $this->getViewer();
return id(new PHUIHomeView())
->setViewer($viewer);
}
public function buildEditEngineFields(
PhabricatorProfileMenuItemConfiguration $config) {
return array(
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setPlaceholder($this->getDefaultName())
->setValue($config->getMenuItemProperty('name')),
);
}
protected function newNavigationMenuItems(
PhabricatorProfileMenuItemConfiguration $config) {
$viewer = $this->getViewer();
$name = $this->getDisplayName($config);
$icon = 'fa-home';
$href = $this->getItemViewURI($config);
$item = $this->newItem()
->setHref($href)
->setName($name)
->setIcon($icon);
return array(
$item,
);
}
}
| <?php
final class PhabricatorHomeProfileMenuItem
extends PhabricatorProfileMenuItem {
const MENUITEMKEY = 'home.dashboard';
public function getMenuItemTypeName() {
return pht('Home');
}
private function getDefaultName() {
return pht('Home');
}
public function canMakeDefault(
PhabricatorProfileMenuItemConfiguration $config) {
return true;
}
public function getDisplayName(
PhabricatorProfileMenuItemConfiguration $config) {
$name = $config->getMenuItemProperty('name');
if (strlen($name)) {
return $name;
}
return $this->getDefaultName();
}
public function newPageContent() {
$viewer = $this->getViewer();
return id(new PHUIHomeView())
->setViewer($viewer);
}
public function buildEditEngineFields(
PhabricatorProfileMenuItemConfiguration $config) {
return array(
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setPlaceholder($this->getDefaultName())
->setValue($config->getMenuItemProperty('name')),
);
}
protected function newNavigationMenuItems(
PhabricatorProfileMenuItemConfiguration $config) {
$viewer = $this->getViewer();
$name = $this->getDisplayName($config);
$icon = 'fa-home';
$href = $this->getItemViewURI($config);
$item = $this->newItem()
->setHref($href)
->setName($name)
->setIcon($icon);
return array(
$item,
);
}
}
|
Fix next activities bug (date filter D8 not operational) | (function ($) {
'use strict';
setNextActivities();
function setNextActivities() {
$.ajax({
url: "/next_activities"
}).done(function (data) {
var count = 0;
var str = '';
$.each(data, function (index, activity) {
if(new Date(activity.field_date_1)>new Date() && count <=10) {
str += '<tr>';
str += '<td class="date">' + activity.field_date + '</td>';
if (activity.field_lien && activity.field_lien != '') {
str += '<td class="title"><a href="' + activity.field_lien + '">' + activity.title + '</a></td>';
} else {
str += '<td class="title">' + activity.title + '</td>';
}
str += '<td class="room">' + activity.field_room + '</td>';
str += '</tr>';
count ++;
}
});
$('.tournaments-home-next table').html(str);
setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
});
}
})(jQuery);
| (function ($) {
'use strict';
setNextActivities();
function setNextActivities() {
$.ajax({
url: "/next_activities"
}).done(function (data) {
var str = '';
$.each(data, function (index, activity) {
if(new Date(activity.field_date_1)>new Date()) {
str += '<tr>';
str += '<td class="date">' + activity.field_date + '</td>';
if (activity.field_lien && activity.field_lien != '') {
str += '<td class="title"><a href="' + activity.field_lien + '">' + activity.title + '</a></td>';
} else {
str += '<td class="title">' + activity.title + '</td>';
}
str += '<td class="room">' + activity.field_room + '</td>';
str += '</tr>';
}
});
$('.tournaments-home-next table').html(str);
setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
});
}
})(jQuery);
|
Add optional callbacks for call buffer | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
if cursor:
calls = []
cursor_found = False
for call in self.cache:
if call['id'] == cursor:
cursor_found = True
continue
if not cursor_found:
continue
calls.append(call)
if calls:
callback(calls)
return
self.waiters.add(callback)
def return_call(self, id, response):
callback = self.call_waiters.pop(id, None)
if callback:
callback(response)
def create_call(self, command, args, callback=None):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
if callback:
self.call_waiters[call_id] = callback
self.cache.append(call)
for callback in self.waiters:
callback([call])
self.waiters = set()
| from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
if cursor:
calls = []
cursor_found = False
for call in self.cache:
if call['id'] == cursor:
cursor_found = True
continue
if not cursor_found:
continue
calls.append(call)
if calls:
callback(calls)
return
self.waiters.add(callback)
def return_call(self, id, response):
callback = self.call_waiters.pop(id)
if callback:
callback(response)
def create_call(self, command, args, callback):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
self.call_waiters[call_id] = callback
self.cache.append(call)
for callback in self.waiters:
callback([call])
self.waiters = set()
|
Use migrationJob identifier hashcode as notification identifier. | package com.novoda.downloadmanager;
import android.app.Notification;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
class MigrationStatusNotificationCreator implements NotificationCreator<MigrationStatus> {
private final Context applicationContext;
private final NotificationCustomizer<MigrationStatus> notificationCustomizer;
private NotificationChannelProvider notificationChannelProvider;
MigrationStatusNotificationCreator(Context context, NotificationCustomizer<MigrationStatus> customizer, NotificationChannelProvider notificationChannelProvider) {
this.applicationContext = context.getApplicationContext();
this.notificationCustomizer = customizer;
this.notificationChannelProvider = notificationChannelProvider;
}
@Override
public void setNotificationChannelProvider(NotificationChannelProvider notificationChannelProvider) {
this.notificationChannelProvider = notificationChannelProvider;
}
private MigrationStatus.Status previousStatus;
private NotificationCompat.Builder builder;
@Override
public NotificationInformation createNotification(final MigrationStatus migrationStatus) {
return new NotificationInformation() {
@Override
public int getId() {
return migrationStatus.migrationId().hashCode();
}
@Override
public Notification getNotification() {
MigrationStatus.Status status = migrationStatus.status();
if (builder == null || !previousStatus.equals(status)) {
builder = new NotificationCompat.Builder(applicationContext, notificationChannelProvider.channelId());
previousStatus = status;
}
return notificationCustomizer.customNotificationFrom(builder, migrationStatus);
}
@Override
public NotificationCustomizer.NotificationDisplayState notificationDisplayState() {
return notificationCustomizer.notificationDisplayState(migrationStatus);
}
};
}
}
| package com.novoda.downloadmanager;
import android.app.Notification;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
class MigrationStatusNotificationCreator implements NotificationCreator<MigrationStatus> {
private final Context applicationContext;
private final NotificationCustomizer<MigrationStatus> notificationCustomizer;
private NotificationChannelProvider notificationChannelProvider;
MigrationStatusNotificationCreator(Context context, NotificationCustomizer<MigrationStatus> customizer, NotificationChannelProvider notificationChannelProvider) {
this.applicationContext = context.getApplicationContext();
this.notificationCustomizer = customizer;
this.notificationChannelProvider = notificationChannelProvider;
}
@Override
public void setNotificationChannelProvider(NotificationChannelProvider notificationChannelProvider) {
this.notificationChannelProvider = notificationChannelProvider;
}
private MigrationStatus.Status previousStatus;
private NotificationCompat.Builder builder;
@Override
public NotificationInformation createNotification(final MigrationStatus migrationStatus) {
return new NotificationInformation() {
@Override
public int getId() {
return migrationStatus.hashCode();
}
@Override
public Notification getNotification() {
MigrationStatus.Status status = migrationStatus.status();
if (builder == null || !previousStatus.equals(status)) {
builder = new NotificationCompat.Builder(applicationContext, notificationChannelProvider.channelId());
previousStatus = status;
}
return notificationCustomizer.customNotificationFrom(builder, migrationStatus);
}
@Override
public NotificationCustomizer.NotificationDisplayState notificationDisplayState() {
return notificationCustomizer.notificationDisplayState(migrationStatus);
}
};
}
}
|
Fix CSV generator sometimes printing empty entries | <?php
namespace Craft;
class SlugRegen_RegenerateEntrySlugsTask extends BaseTask
{
private $settings;
private $entries;
private $_totalSteps = null;
public function getTotalSteps()
{
if (is_int($this->_totalSteps)) {
return $this->_totalSteps;
}
$this->settings = $this->model->getAttribute('settings');
foreach ($this->settings['locales'] as $locale) {
$this->entries[] = craft()->entries->getEntryById($this->settings['entryId'], $locale);
}
$this->_totalSteps = count($this->settings['locales']);
return $this->_totalSteps;
}
public function runStep($step)
{
$entry = $this->entries[$step];
$oldSlug = $entry->slug;
$oldUri = $entry->uri;
switch ($oldSlug) {
case '__home__':
return true;
break;
default:
$entry->slug = '';
break;
}
craft()->entries->saveEntry($entry);
if ($this->settings['generateCsv'] && trim($oldUri) != trim($entry->uri)) {
$comparison = '"' . $oldUri . '";"' . $entry->uri . '"' . "\n";
file_put_contents($this->settings['fileName'], $comparison, FILE_APPEND);
}
unset($entry);
if ($this->_totalSteps - 1 == $step) {
unset($this->entries);
}
return true;
}
} | <?php
namespace Craft;
class SlugRegen_RegenerateEntrySlugsTask extends BaseTask
{
private $settings;
private $entries;
private $_totalSteps = null;
public function getTotalSteps()
{
if (is_int($this->_totalSteps)) {
return $this->_totalSteps;
}
$this->settings = $this->model->getAttribute('settings');
foreach ($this->settings['locales'] as $locale) {
$this->entries[] = craft()->entries->getEntryById($this->settings['entryId'], $locale);
}
$this->_totalSteps = count($this->settings['locales']);
return $this->_totalSteps;
}
public function runStep($step)
{
$entry = $this->entries[$step];
$oldSlug = $entry->slug;
$oldUri = $entry->uri;
switch ($oldSlug) {
case '__home__':
return true;
break;
default:
$entry->slug = '';
break;
}
craft()->entries->saveEntry($entry);
if ($this->settings['generateCsv'] && $oldSlug != $entry->slug) {
$comparison = '"' . $oldUri . '";"' . $entry->uri . '"' . "\n";
file_put_contents($this->settings['fileName'], $comparison, FILE_APPEND);
}
unset($entry);
if ($this->_totalSteps - 1 == $step) {
unset($this->entries);
}
return true;
}
} |
Correct link to fix Javadoc warnings | /*
* Copyright 2016 Datalogics Inc.
*/
package com.datalogics.pdf.security;
import java.security.Key;
import java.security.cert.Certificate;
/**
* The basic interface for logging into a HSM machine.
*/
public interface HsmManager {
/**
* Performs a login operation to the HSM device.
*
* @param parms the parameters needed to login to the device
* @return a boolean indicating if the login was successful
* @throws IllegalArgumentException if an argument was invalid
*/
boolean hsmLogin(final HsmLoginParameters parms);
/**
* Logs out of the default session with the HSM device.
*
* <p>
* This method should be called only if you have called {@link HsmManager#hsmLogin(HsmLoginParameters)} to establish
* a login session.
*/
void hsmLogout();
/**
* Determines if logged in to the HSM Device.
*
* @return boolean
*/
boolean isLoggedIn();
/**
* Get the Key object for the HSM device.
*
* @param password the password for recovering the key
* @param keyLabel the given alias associated with the key
* @return key
*/
Key getKey(final String password, final String keyLabel);
/**
* Get an array of Certificates for the HSM device.
*
* @param certLabel the given alias associated with the certificate
* @return Certificate[]
*/
Certificate[] getCertificateChain(final String certLabel);
/**
* Get the provider name installed by this HSM.
*
* @return the provider name
*/
String getProviderName();
}
| /*
* Copyright 2016 Datalogics Inc.
*/
package com.datalogics.pdf.security;
import java.security.Key;
import java.security.cert.Certificate;
/**
* The basic interface for logging into a HSM machine.
*/
public interface HsmManager {
/**
* Performs a login operation to the HSM device.
*
* @param parms the parameters needed to login to the device
* @return a boolean indicating if the login was successful
* @throws IllegalArgumentException if an argument was invalid
*/
boolean hsmLogin(final HsmLoginParameters parms);
/**
* Logs out of the default session with the HSM device.
*
* <p>
* This method should be called only if you have called {@link hsmLogin} to establish a login session.
*/
void hsmLogout();
/**
* Determines if logged in to the HSM Device.
*
* @return boolean
*/
boolean isLoggedIn();
/**
* Get the Key object for the HSM device.
*
* @param password the password for recovering the key
* @param keyLabel the given alias associated with the key
* @return key
*/
Key getKey(final String password, final String keyLabel);
/**
* Get an array of Certificates for the HSM device.
*
* @param certLabel the given alias associated with the certificate
* @return Certificate[]
*/
Certificate[] getCertificateChain(final String certLabel);
/**
* Get the provider name installed by this HSM.
*
* @return the provider name
*/
String getProviderName();
}
|
Revert parameter name for isExpired() to validSeconds | "use strict";
const VError = require("verror");
module.exports = function (dependencies) {
const sign = dependencies.sign;
const decode = dependencies.decode;
const resolve = dependencies.resolve;
function prepareToken(options) {
let keyData;
try {
keyData = resolve(options.key);
} catch (err) {
throw new VError(err, "Failed loading token key");
}
try {
let token = sign.bind(null, {}, keyData, {
algorithm: "ES256",
issuer: options.teamId,
header: { kid: options.keyId }
});
return {
generation: 0,
current: token(),
iat: null,
regenerate(generation) {
if (generation === this.generation) {
this.generation += 1;
this.current = token();
this.iat = null;
}
},
isExpired(validSeconds) {
if (this.iat == null) {
let decoded = decode(this.current);
this.iat = decoded.iat;
}
return (Math.floor(Date.now() / 1000) - this.iat) >= validSeconds;
}
};
} catch (err) {
throw new VError(err, "Failed to generate token");
}
}
return prepareToken;
};
| "use strict";
const VError = require("verror");
module.exports = function (dependencies) {
const sign = dependencies.sign;
const decode = dependencies.decode;
const resolve = dependencies.resolve;
function prepareToken(options) {
let keyData;
try {
keyData = resolve(options.key);
} catch (err) {
throw new VError(err, "Failed loading token key");
}
try {
let token = sign.bind(null, {}, keyData, {
algorithm: "ES256",
issuer: options.teamId,
header: { kid: options.keyId }
});
return {
generation: 0,
current: token(),
iat: null,
regenerate(generation) {
if (generation === this.generation) {
this.generation += 1;
this.current = token();
this.iat = null;
}
},
isExpired(validMilliSeconds) {
if (this.iat == null) {
let decoded = decode(this.current);
this.iat = decoded.iat;
}
return (Math.floor(Date.now() / 1000) - this.iat) >= validMilliSeconds;
}
};
} catch (err) {
throw new VError(err, "Failed to generate token");
}
}
return prepareToken;
};
|
Return the Link instance itself when accessed through a class (so sphinx autodoc works) | import logging
import remoteobjects.dataobject
import remoteobjects.fields
from remoteobjects.fields import *
import typepad.tpobject
class Link(remoteobjects.fields.Link):
"""A `TypePadObject` property representing a link from one TypePad API
object to another.
This `Link` works like `remoteobjects.fields.Link`, but builds links using
the TypePad API URL scheme. That is, a `Link` on ``/asset/1.json`` called
``events`` links to ``/asset/1/events.json``.
"""
def __get__(self, instance, owner):
"""Generates the `TypePadObject` representing the target of this
`Link` object.
This `__get__()` implementation implements the ``../x/target.json`` style
URLs used in the TypePad API.
"""
if instance is None:
return self
try:
if instance._location is None:
raise AttributeError('Cannot find URL of %s relative to URL-less %s' % (type(self).__name__, owner.__name__))
assert instance._location.endswith('.json')
newurl = instance._location[:-5]
newurl += '/' + self.api_name
newurl += '.json'
ret = self.cls.get(newurl)
ret.of_cls = self.of_cls
return ret
except Exception, e:
logging.error(str(e))
raise
| import logging
import remoteobjects.dataobject
import remoteobjects.fields
from remoteobjects.fields import *
import typepad.tpobject
class Link(remoteobjects.fields.Link):
"""A `TypePadObject` property representing a link from one TypePad API
object to another.
This `Link` works like `remoteobjects.fields.Link`, but builds links using
the TypePad API URL scheme. That is, a `Link` on ``/asset/1.json`` called
``events`` links to ``/asset/1/events.json``.
"""
def __get__(self, instance, owner):
"""Generates the `TypePadObject` representing the target of this
`Link` object.
This `__get__()` implementation implements the ``../x/target.json`` style
URLs used in the TypePad API.
"""
try:
if instance._location is None:
raise AttributeError('Cannot find URL of %s relative to URL-less %s' % (type(self).__name__, owner.__name__))
assert instance._location.endswith('.json')
newurl = instance._location[:-5]
newurl += '/' + self.api_name
newurl += '.json'
ret = self.cls.get(newurl)
ret.of_cls = self.of_cls
return ret
except Exception, e:
logging.error(str(e))
raise
|
Fix generator path for service provider | <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->config('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
| <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->get('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
|
Implement pause property more accurately | # coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if self._cmdline is None:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.paused:
self.unpause()
if self.running:
logging.debug('stopping ffmpeg process')
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
| # coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if self._cmdline is None:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.paused:
self.unpause()
if self.running:
logging.debug('stopping ffmpeg process')
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
Add a tool tip to the form. | import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import style from './../../../styles/organisms/ThermostatForm.scss'
class ThermostatForm extends Component {
getLastRemoteCheckin() {
return moment().diff(this.props.lastCheckin, 'minutes')
}
render() {
const minutesSinceLastCheckin = this.getLastRemoteCheckin.call(this)
return (
<form
title={`The remote last checked in ${minutesSinceLastCheckin} minutes ago.`}
className={style.form}
method="post"
action={`/thermostat/${this.props.id}`}>
<fieldset className={style.temperature}>
<legend>Target Temperature</legend>
<input type="hidden" name="_method" value="put" />
<input name="temperature" type="number" required value={this.props.temperature} max="99" min="68" />
<span className={style.degree}>°</span>
</fieldset>
<input
className={style.name}
type="text" name="name"
value={this.props.name} required />
<button className="pure-button pure-button-primary">Update</button>
{
minutesSinceLastCheckin > 15 &&
<div className={style.warning}>
<span>{"The remote hasn\'t checked in recently."}</span>
</div>
}
</form>
)
}
}
ThermostatForm.propTypes = {
id: PropTypes.number,
temperature: PropTypes.string,
name: PropTypes.string,
lastCheckin: PropTypes.string
}
export default ThermostatForm
| import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import style from './../../../styles/organisms/ThermostatForm.scss'
class ThermostatForm extends Component {
getLastRemoteCheckin() {
return moment().diff(this.props.lastCheckin, 'minutes')
}
render() {
const minutesSinceLastCheckin = this.getLastRemoteCheckin.call(this)
return (
<form className={style.form} method="post" action={`/thermostat/${this.props.id}`}>
<fieldset className={style.temperature}>
<legend>Target Temperature</legend>
<input type="hidden" name="_method" value="put" />
<input name="temperature" type="number" required value={this.props.temperature} max="99" min="68" />
<span className={style.degree}>°</span>
</fieldset>
<input className={style.name} type="text" name="name" value={this.props.name} required />
<button className="pure-button pure-button-primary">Update</button>
{
minutesSinceLastCheckin > 15 &&
<div className={style.warning}>
<span>{"The remote hasn\'t checked in recently."}</span>
</div>
}
</form>
)
}
}
ThermostatForm.propTypes = {
id: PropTypes.number,
temperature: PropTypes.string,
name: PropTypes.string,
lastCheckin: PropTypes.string
}
export default ThermostatForm
|
Enable Command to support memory limiting. | import subprocess as sp
import signal
import threading
import os
SIGTERM_TIMEOUT = 1.0
class Command(object):
def __init__(self, cmd, memlimit=None):
self.cmd = cmd
self.memlimit = memlimit
self.process = None
self.stdout = None
self.stderr = None
self.exitcode = None
self.timed_out = False
def run(self, timeout=None):
def target():
cmd = self.cmd
if self.memlimit:
cmd = "ulimit -v %d; %s" % (self.memlimit, cmd)
self.process = sp.Popen(cmd,
stdout=sp.PIPE, stderr=sp.PIPE,
shell=True, preexec_fn=os.setpgrp)
self.stdout, self.stderr = self.process.communicate()
self.exitcode = self.process.returncode
thread = threading.Thread(target=target)
thread.start()
thread.join(float(timeout))
if thread.is_alive():
self.timed_out = True
# Send the TERM signal to all the process groups
os.killpg(self.process.pid, signal.SIGTERM)
thread.join(SIGTERM_TIMEOUT)
if thread.is_alive():
# Send the KILL signal if the process hasn't exited by now.
os.killpg(self.process.pid, signal.SIGKILL)
self.process.kill()
thread.join()
| import subprocess as sp
import signal
import threading
import os
SIGTERM_TIMEOUT = 1.0
class Command(object):
def __init__(self, cmd, memlimit=None):
self.cmd = cmd
self.memlimit = memlimit
self.process = None
self.stdout = None
self.stderr = None
self.exitcode = None
self.timed_out = False
def run(self, timeout=None):
def target():
self.process = sp.Popen(self.cmd,
stdout=sp.PIPE, stderr=sp.PIPE,
shell=True, preexec_fn=os.setpgrp)
self.stdout, self.stderr = self.process.communicate()
self.exitcode = self.process.returncode
thread = threading.Thread(target=target)
thread.start()
thread.join(float(timeout))
if thread.is_alive():
self.timed_out = True
# Send the TERM signal to all the process groups
os.killpg(self.process.pid, signal.SIGTERM)
thread.join(SIGTERM_TIMEOUT)
if thread.is_alive():
# Send the KILL signal if the process hasn't exited by now.
os.killpg(self.process.pid, signal.SIGKILL)
self.process.kill()
thread.join()
|
Improve API test by only comparing args and varargs. | # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
return False
try:
return HttpBackend in inspect.getmro(t)
except AttributeError:
return False
def derived_types():
return [t for t in globals().values() if is_http_backend_derived(t)]
class ApiTests(TestCase):
def test_go(self):
def just_args(s):
return dict(args=s.args, varargs=s.varargs)
comp = just_args(inspect.getargspec(HttpBackend.go))
for t in derived_types():
sig = just_args(inspect.getargspec(t.go))
self.assertEqual(comp, sig, "Type %(t)s does not adhere to the spec %(spec)s with signature %(sig)s" % dict(t=t, spec=comp, sig=sig))
def test_properties(self):
comp = set(dir(HttpBackend))
for t in derived_types():
self.assertEqual(comp - set(dir(t)), set())
def test_properties_overriden(self):
comp = dir(HttpBackend)
for t in derived_types():
o = t()
for p in comp:
try:
getattr(o, p)
except NotImplementedError:
raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t)))
except:
pass
| # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
return False
try:
return HttpBackend in inspect.getmro(t)
except AttributeError:
return False
def derived_types():
return [t for t in globals().values() if is_http_backend_derived(t)]
class ApiTests(TestCase):
def test_go(self):
comp = inspect.getargspec(HttpBackend.go)
for t in derived_types():
self.assertEqual(comp, inspect.getargspec(t.go), "Type %(t)s does not adhere to the spec %(s)s" % dict(t=t, s=comp))
def test_properties(self):
comp = set(dir(HttpBackend))
for t in derived_types():
self.assertEqual(comp - set(dir(t)), set())
def test_properties_overriden(self):
comp = dir(HttpBackend)
for t in derived_types():
o = t()
for p in comp:
try:
getattr(o, p)
except NotImplementedError:
raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t)))
except:
pass
|
Fix server error when login with u2f | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from u2flib_server.u2f import (begin_registration,
begin_authentication,
complete_registration,
complete_authentication)
from components.eternity import config
facet = config.rss['link']
async def enroll(user):
enroll = begin_registration(facet, user.get('_u2f_devices_', []))
user['_u2f_enroll_'] = enroll.json
return user, json.dumps(enroll.data_for_client)
async def bind(user, data):
response = data['tokenResponse']
enroll = user.pop('_u2f_enroll_')
device, cert = complete_registration(enroll, response, [facet])
patch = device
patch['deviceName'] = data['deviceName']
patch['registerDate'] = data['date']
user.setdefault('_u2f_devices_', []).append(json.dumps(patch))
# cert = x509.load_der_x509_certificate(cert, default_backend())
return user, True
async def sign(user):
challenge = begin_authentication(facet, user.get('_u2f_devices_', []))
user['_u2f_challenge_'] = challenge.json
return user, json.dumps(challenge.data_for_client)
async def verify(user, data):
challenge = user.pop('_u2f_challenge_')
try:
complete_authentication(challenge, data['tokenResponse'], [facet])
except AttributeError:
return user, False
return user, True
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from u2flib_server.u2f import (begin_registration,
begin_authentication,
complete_registration,
complete_authentication)
from components.eternity import config
facet = config.rss['link']
async def enroll(user):
enroll = begin_registration(facet, user.get('_u2f_devices_', []))
user['_u2f_enroll_'] = enroll.json
return user, json.dumps(enroll.data_for_client)
async def bind(user, data):
response = data['tokenResponse']
enroll = user.pop('_u2f_enroll_')
device, cert = complete_registration(enroll, response, [facet])
patch = device
patch['deviceName'] = data['deviceName']
patch['registerDate'] = data['date']
user.setdefault('_u2f_devices_', []).append(json.dumps(patch))
# cert = x509.load_der_x509_certificate(cert, default_backend())
return user, True
async def sign(user):
challenge = begin_authentication(facet, user.get('_u2f_devices_', []))
user['_u2f_challenge_'] = challenge.json
return user, json.dumps(challenge.data_for_client)
async def verify(user, data):
challenge = user.pop('_u2f_challenge_')
try:
complete_authentication(challenge, data, [facet])
except AttributeError:
return user, False
return user, True
|
Add test for use case when at least two neightbours are alive |
var GameOfLife = (function() {
var ALIVE = "alive", DEAD = "dead";
function Cell(initialState) {
var state = initialState || DEAD;
function getNumberOfAlive(neighbours) {
var nbAliveCells = 0;
neighbours.forEach(function (neighbor) {
if (neighbor.isAlive()) {
nbAliveCells += 1;
}
});
return nbAliveCells;
}
return {
setNeighbours: function (neighbours) {
if(getNumberOfAlive(neighbours) < 2) {
state = DEAD;
}
},
isAlive: function() {
return state === ALIVE;
}
};
}
function AliveCell() {
return new Cell(ALIVE);
}
function DeadCell() {
return new Cell(DEAD);
}
return {
AliveCell: AliveCell,
DeadCell: DeadCell
};
})();
describe('Live cell', function () {
it('should die when it has fewer than two live neighbours', function () {
var cell = new GameOfLife.AliveCell();
cell.setNeighbours([new GameOfLife.AliveCell()]);
expect(cell.isAlive()).toBe(false);
});
it('should stay alive when it has at least two live neighbours', function () {
var cell = new GameOfLife.AliveCell();
cell.setNeighbours([new GameOfLife.AliveCell(), new GameOfLife.AliveCell()]);
expect(cell.isAlive()).toBe(true);
});
}); |
var GameOfLife = (function() {
var ALIVE = "alive", DEAD = "dead";
function Cell(initialState) {
var state = initialState || DEAD;
function getNumberOfAlive(neighbours) {
var nbAliveCells = 0;
neighbours.forEach(function (neighbor) {
if (neighbor.isAlive()) {
nbAliveCells += 1;
}
});
return nbAliveCells;
}
return {
setNeighbours: function (neighbours) {
if(getNumberOfAlive(neighbours) < 2) {
state = DEAD;
}
},
isAlive: function() {
return state === ALIVE;
}
};
}
function AliveCell() {
return new Cell(ALIVE);
}
function DeadCell() {
return new Cell(DEAD);
}
return {
AliveCell: AliveCell,
DeadCell: DeadCell
};
})();
describe('Live cell', function () {
it('should die when it has fewer than two live neighbours', function () {
var cell = new GameOfLife.AliveCell();
cell.setNeighbours([new GameOfLife.AliveCell()]);
expect(cell.isAlive()).toBe(false);
});
}); |
Add verification that the code ran on GPU. Otherwise we get a false positive. | package com.amd.aparapi.test.runtime;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.amd.aparapi.Kernel;
class AnotherClass{
static public int foo(int i) {
return i + 42;
}
};
public class CallStaticFromAnonymousKernel {
static final int size = 256;
final int[] values = new int[size];
final int[] results = new int[size];
public CallStaticFromAnonymousKernel() {
for(int i=0; i<size; i++) {
values[i] = i;
results[i] = 0;
}
}
public static int fooBar(int i) {
return i + 20;
}
@Test public void test() {
Kernel kernel = new Kernel() {
public int doodoo(int i) {
return AnotherClass.foo(i);
}
@Override public void run() {
int gid = getGlobalId();
results[gid] = fooBar(values[gid]) + doodoo(gid);
}
};
kernel.execute(size);
assertTrue("ran on GPU", kernel.getExecutionMode()==Kernel.EXECUTION_MODE.GPU);
for(int i=0; i<size; i++) {
System.out.println(results[i] + " == " + fooBar(values[i]) + AnotherClass.foo(i));
assertTrue( "results == fooBar", results[i] == (fooBar(values[i]) + AnotherClass.foo(i)));
}
}
}
| package com.amd.aparapi.test.runtime;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.amd.aparapi.Kernel;
class AnotherClass{
static public int foo(int i) {
return i + 42;
}
};
public class CallStaticFromAnonymousKernel {
static final int size = 256;
final int[] values = new int[size];
final int[] results = new int[size];
public CallStaticFromAnonymousKernel() {
for(int i=0; i<size; i++) {
values[i] = i;
results[i] = 0;
}
}
public static int fooBar(int i) {
return i + 20;
}
@Test public void test() {
Kernel kernel = new Kernel() {
public int doodoo(int i) {
return AnotherClass.foo(i);
}
@Override public void run() {
int gid = getGlobalId();
results[gid] = fooBar(values[gid]) + doodoo(gid);
}
};
kernel.execute(size);
for(int i=0; i<size; i++) {
System.out.println(results[i] + " == " + fooBar(values[i]) + AnotherClass.foo(i));
assertTrue( "results == fooBar", results[i] == (fooBar(values[i]) + AnotherClass.foo(i)));
}
}
}
|
fix(lang): Fix comment for lang method | <?php
namespace Unicodeveloper\Identify;
use Sinergi\BrowserDetector\Browser;
use Sinergi\BrowserDetector\Os;
use Sinergi\BrowserDetector\Language;
class Identify {
/**
* Store the browser object
* @var object
*/
protected $browser;
/**
* Store the os object
* @var object
*/
protected $os;
/**
* Store the language object
* @var object
*/
protected $language;
/**
* Create an Instance of Browser and Os
*/
public function __construct()
{
$this->os = new Os();
$this->browser = new Browser();
$this->language = new Language();
}
/**
* Get all the methods applicable to browser detection
* e.g getName(), getVersion()
* @return \Sinergi\BrowserDetector\Browser
*/
public function browser()
{
return $this->browser;
}
/**
* Get all the methods applicable to Os detection
* e.g getName(), getVersion()
* @return \Sinergi\BrowserDetector\Os
*/
public function os()
{
return $this->os;
}
/**
* Get all the methods applicable to Language detection
* e.g getLanguage()
* @return \Sinergi\BrowserDetector\Language
*/
public function lang()
{
return $this->language;
}
} | <?php
namespace Unicodeveloper\Identify;
use Sinergi\BrowserDetector\Browser;
use Sinergi\BrowserDetector\Os;
use Sinergi\BrowserDetector\Language;
class Identify {
/**
* Store the browser object
* @var object
*/
protected $browser;
/**
* Store the os object
* @var object
*/
protected $os;
/**
* Store the language object
* @var object
*/
protected $language;
/**
* Create an Instance of Browser and Os
*/
public function __construct()
{
$this->os = new Os();
$this->browser = new Browser();
$this->language = new Language();
}
/**
* Get all the methods applicable to browser detection
* e.g getName(), getVersion()
* @return \Sinergi\BrowserDetector\Browser
*/
public function browser()
{
return $this->browser;
}
/**
* Get all the methods applicable to Os detection
* e.g getName(), getVersion()
* @return \Sinergi\BrowserDetector\Os
*/
public function os()
{
return $this->os;
}
/**
* Get all the methods applicable to Language detection
* @return \Sinergi\BrowserDetector\Language
*/
public function lang()
{
return $this->language;
}
} |
Fix unbloud local error if no matching records | import logging
from django.core.management.base import BaseCommand
from cityhallmonitor.models import Document
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'For each document, force an update of its related fields and its postgres text index'
def add_arguments(self, parser):
parser.add_argument('--limit', type=int,
help='Process up to LIMIT documents')
parser.add_argument('--where',
help='WHERE condition to filter documents')
def handle(self, *args, **options):
logger.info(
'Rebuilding text index, limit=%(limit)s, where="%(where)s"' \
% options)
if options['where']:
qs = Document.objects.extra(where=[options['where']])
else:
qs = Document.objects.all()
if options['limit']:
qs = qs[:options['limit']]
i = 0
for i,d in enumerate(qs, start=1):
d._set_dependent_fields()
d.save(update_text=True)
if i % 1000 == 0:
logger.debug("Processed %i documents" % i)
logger.info('Done, processed %d documents\n' % i)
| import logging
from django.core.management.base import BaseCommand
from cityhallmonitor.models import Document
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'For each document, force an update of its related fields and its postgres text index'
def add_arguments(self, parser):
parser.add_argument('--limit', type=int,
help='Process up to LIMIT documents')
parser.add_argument('--where',
help='WHERE condition to filter documents')
def handle(self, *args, **options):
logger.info(
'Rebuilding text index, limit=%(limit)s, where="%(where)s"' \
% options)
if options['where']:
qs = Document.objects.extra(where=[options['where']])
else:
qs = Document.objects.all()
if options['limit']:
qs = qs[:options['limit']]
for i,d in enumerate(qs, start=1):
d._set_dependent_fields()
d.save(update_text=True)
if i % 1000 == 0:
logger.debug("Processed %i documents" % i)
logger.info('Done, processed %d documents\n' % i)
|
Use -platform:anycpu while compiling .NET assemblies
git-svn-id: 8d82213adbbc6b1538a984bace977d31fcb31691@349 2f5d681c-ba19-11dd-a503-ed2d4bea8bb5 | import os.path
import SCons.Builder
import SCons.Node.FS
import SCons.Util
csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES"
csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES"
McsBuilder = SCons.Builder.Builder(action = '$CSCCOM',
source_factory = SCons.Node.FS.default_fs.Entry,
suffix = '.exe')
McsLibBuilder = SCons.Builder.Builder(action = '$CSCLIBCOM',
source_factory = SCons.Node.FS.default_fs.Entry,
suffix = '.dll')
def generate(env):
env['BUILDERS']['CLIProgram'] = McsBuilder
env['BUILDERS']['CLILibrary'] = McsLibBuilder
env['CSC'] = 'gmcs'
env['_CSCLIBS'] = "${_stripixes('-r:', CILLIBS, '', '-r', '', __env__)}"
env['_CSCLIBPATH'] = "${_stripixes('-lib:', CILLIBPATH, '', '-r', '', __env__)}"
env['CSCFLAGS'] = SCons.Util.CLVar('-platform:anycpu')
env['CSCLIBFLAGS'] = SCons.Util.CLVar('-platform:anycpu')
env['CSCCOM'] = SCons.Action.Action(csccom)
env['CSCLIBCOM'] = SCons.Action.Action(csclibcom)
def exists(env):
return internal_zip or env.Detect('gmcs')
| import os.path
import SCons.Builder
import SCons.Node.FS
import SCons.Util
csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES"
csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES"
McsBuilder = SCons.Builder.Builder(action = '$CSCCOM',
source_factory = SCons.Node.FS.default_fs.Entry,
suffix = '.exe')
McsLibBuilder = SCons.Builder.Builder(action = '$CSCLIBCOM',
source_factory = SCons.Node.FS.default_fs.Entry,
suffix = '.dll')
def generate(env):
env['BUILDERS']['CLIProgram'] = McsBuilder
env['BUILDERS']['CLILibrary'] = McsLibBuilder
env['CSC'] = 'gmcs'
env['_CSCLIBS'] = "${_stripixes('-r:', CILLIBS, '', '-r', '', __env__)}"
env['_CSCLIBPATH'] = "${_stripixes('-lib:', CILLIBPATH, '', '-r', '', __env__)}"
env['CSCFLAGS'] = SCons.Util.CLVar('')
env['CSCCOM'] = SCons.Action.Action(csccom)
env['CSCLIBCOM'] = SCons.Action.Action(csclibcom)
def exists(env):
return internal_zip or env.Detect('gmcs')
|
Remove some single quotes from a key | (function() {
'use strict';
angular.module('app.config')
.config(navigation);
/** @ngInject */
function navigation(NavigationProvider) {
NavigationProvider.configure({
items: {
primary: [
{
title: 'Dashboard',
state: 'dashboard',
icon: 'fa fa-dashboard'
},
{
title: 'My Services',
state: 'services',
icon: 'fa fa-file-o',
count: 12
},
{
title: 'My Requests',
state: 'order-history',
icon: 'fa fa-file-text-o',
count: 2
},
{
title: 'Service Catalog',
state: 'marketplace',
icon: 'fa fa-copy'
}
],
secondary: [
{
title: 'Help',
icon: 'fa fa-question-circle',
state: 'help'
},
{
title: 'About Me',
icon: 'fa fa-user',
state: 'about-me'
},
{
title: 'Search',
icon: 'fa fa-search',
state: 'search'
}
]
}
});
}
})();
| (function() {
'use strict';
angular.module('app.config')
.config(navigation);
/** @ngInject */
function navigation(NavigationProvider) {
NavigationProvider.configure({
items: {
primary: [
{
title: 'Dashboard',
'state': 'dashboard',
icon: 'fa fa-dashboard'
},
{
title: 'My Services',
state: 'services',
icon: 'fa fa-file-o',
count: 12
},
{
title: 'My Requests',
state: 'order-history',
icon: 'fa fa-file-text-o',
count: 2
},
{
title: 'Service Catalog',
state: 'marketplace',
icon: 'fa fa-copy'
}
],
secondary: [
{
title: 'Help',
icon: 'fa fa-question-circle',
state: 'help'
},
{
title: 'About Me',
icon: 'fa fa-user',
state: 'about-me'
},
{
title: 'Search',
icon: 'fa fa-search',
state: 'search'
}
]
}
});
}
})();
|
Add wait for pagination test | import unittest
import sys
import os
try:
from instagram_private_api_extensions import pagination
except ImportError:
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from instagram_private_api_extensions import pagination
class TestPagination(unittest.TestCase):
def test_page(self):
testset = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
def paging_stub(start=0):
page_size = 3
result = {
'items': testset[start:start + page_size]
}
if len(testset) > start + page_size:
result['next_index'] = start + page_size
return result
resultset = []
for results in pagination.page(
paging_stub, args={},
cursor_key='start',
get_cursor=lambda r: r.get('next_index'),
wait=0):
if results.get('items'):
resultset.extend(results['items'])
self.assertEqual(testset, resultset)
resultset = []
for results in pagination.page(
paging_stub, args={},
cursor_key='start',
get_cursor=lambda r: r.get('next_index'),
wait=1):
if results.get('items'):
resultset.extend(results['items'])
self.assertEqual(testset, resultset)
| import unittest
import sys
import os
try:
from instagram_private_api_extensions import pagination
except ImportError:
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from instagram_private_api_extensions import pagination
class TestPagination(unittest.TestCase):
def test_page(self):
testset = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
def paging_stub(start=0):
page_size = 3
result = {
'items': testset[start:start + page_size]
}
if len(testset) > start + page_size:
result['next_index'] = start + page_size
return result
resultset = []
for results in pagination.page(
paging_stub, args={},
cursor_key='start',
get_cursor=lambda r: r.get('next_index'),
wait=0):
if results.get('items'):
resultset.extend(results['items'])
self.assertEqual(testset, resultset)
|
Update version number to 0.6.2 | from setuptools import setup, find_packages
version = '0.6.2'
setup(
name='ckanext-oaipmh',
version=version,
description="OAI-PMH server and harvester for CKAN",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='CSC - IT Center for Science Ltd.',
author_email='kata-project@postit.csc.fi',
url='https://github.com/kata-csc/ckanext-oaipmh',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['ckanext', 'ckanext.oaipmh'],
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
'pyoai',
'ckanext-harvest',
'lxml',
'rdflib',
'beautifulsoup4',
'pointfree',
'functionally',
'fn',
],
entry_points="""
[ckan.plugins]
oaipmh=ckanext.oaipmh.plugin:OAIPMHPlugin
oaipmh_harvester=ckanext.oaipmh.harvester:OAIPMHHarvester
ida_harvester=ckanext.oaipmh.ida:IdaHarvester
cmdi_harvester=ckanext.oaipmh.cmdi:CMDIHarvester
""",
)
| from setuptools import setup, find_packages
version = '0.6.1'
setup(
name='ckanext-oaipmh',
version=version,
description="OAI-PMH server and harvester for CKAN",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='CSC - IT Center for Science Ltd.',
author_email='kata-project@postit.csc.fi',
url='https://github.com/kata-csc/ckanext-oaipmh',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['ckanext', 'ckanext.oaipmh'],
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
'pyoai',
'ckanext-harvest',
'lxml',
'rdflib',
'beautifulsoup4',
'pointfree',
'functionally',
'fn',
],
entry_points="""
[ckan.plugins]
oaipmh=ckanext.oaipmh.plugin:OAIPMHPlugin
oaipmh_harvester=ckanext.oaipmh.harvester:OAIPMHHarvester
ida_harvester=ckanext.oaipmh.ida:IdaHarvester
cmdi_harvester=ckanext.oaipmh.cmdi:CMDIHarvester
""",
)
|
Align media form with displayed media link info
The issue was that if you have a media link and click ad media link
the form had a different order or type and uri. | <?php
namespace Talk;
use Event\EventEntity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Form used to render and validate the speakers collection on a Talk form
*/
class TalkMediaFormType extends AbstractType
{
/**
* Returns the name of this form type.
*
* @return string
*/
public function getName()
{
return 'talk_media';
}
/**
* Adds fields with their types and validation constraints to this definition.
*
* @param FormBuilderInterface $builder
* @param array $options
*
* @return void
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'type',
'choice',
[
'choices' => [
'slides_link' => 'Slides',
'video_link' => 'Video',
'audio_link' => 'Audio',
'code_link' => 'Code',
'joindin_link' => 'JoindIn',
],
'label' => false,
]
)
->add('url', 'text', [
'label' => false,
'required' => false,
])
;
}
}
| <?php
namespace Talk;
use Event\EventEntity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Form used to render and validate the speakers collection on a Talk form
*/
class TalkMediaFormType extends AbstractType
{
/**
* Returns the name of this form type.
*
* @return string
*/
public function getName()
{
return 'talk_media';
}
/**
* Adds fields with their types and validation constraints to this definition.
*
* @param FormBuilderInterface $builder
* @param array $options
*
* @return void
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('url', 'text', [
'label' => false,
'required' => false,
])
->add(
'type',
'choice',
[
'choices' => [
'slides_link' => 'Slides',
'video_link' => 'Video',
'audio_link' => 'Audio',
'code_link' => 'Code',
'joindin_link' => 'JoindIn',
],
'label' => false,
]
)
;
}
}
|
Fix level not returned in getLevel(). | <?php
namespace MinePlus\VoterBundle;
class VoteDispatcher
{
protected $voters;
public function hasVoters()
{
// An empty array cast's into false
return (boolean) $this->voters;
}
public function addVoter($eventName, $voter, $multiplicator)
{
$this->voters[$eventName][$multiplicator][] = $voter;
}
public function decide($eventName, $event)
{
return ($this->getLevel($eventName, $event) <= 0) ? false : true;
}
public function getLevel($eventName, $event)
{
$level = 0;
if (!array_key_exists($eventName, $this->voters))
return $level;
$voters = $this->voters[$eventName];
foreach ($voters as $multiplicator => $votersArray) {
foreach ($votersArray as $voter) {
$returnedLevel = call_user_func($voter, $event);
$level = $level + $returnedLevel * $multiplicator;
}
}
return $level;
}
}
?>
| <?php
namespace MinePlus\VoterBundle;
class VoteDispatcher
{
protected $voters;
public function hasVoters()
{
// An empty array cast's into false
return (boolean) $this->voters;
}
public function addVoter($eventName, $voter, $multiplicator)
{
$this->voters[$eventName][$multiplicator][] = $voter;
}
public function decide($eventName, $event)
{
return ($this->getLevel($eventName, $event) <= 0) ? false : true;
}
public function getLevel($eventName, $event)
{
$level = 0;
if (!array_key_exists($eventName, $this->voters))
return $level;
$voters = $this->voters[$eventName];
foreach ($voters as $multiplicator => $votersArray) {
foreach ($votersArray as $voter) {
$returnedLevel = call_user_func($voter, $event);
$level = $level + $returnedLevel * $multiplicator;
}
}
}
}
?>
|
Handle alternate form of mongoose 11000 error | var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (fieldName in this.schema.tree) {
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
if (idType === ShortId || idType.type === ShortId) {
var idInfo = this.schema.path(fieldName);
var retries = idInfo.retries;
var self = this;
function attemptSave() {
idInfo.generator(idInfo.generatorOptions, function(err, id) {
if (err) {
cb(err);
return;
}
self[fieldName] = id;
defaultSave.call(self, function(err, obj) {
if (err &&
err.code == 11000 &&
(err.err || err.errmsg || '').indexOf(fieldName) !== -1 &&
retries > 0
) {
--retries;
attemptSave();
} else {
// TODO check these args
cb(err, obj);
}
});
});
}
attemptSave();
return;
}
}
}
defaultSave.call(this, cb);
};
module.exports = exports = ShortId;
| var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (fieldName in this.schema.tree) {
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
if (idType === ShortId || idType.type === ShortId) {
var idInfo = this.schema.path(fieldName);
var retries = idInfo.retries;
var self = this;
function attemptSave() {
idInfo.generator(idInfo.generatorOptions, function(err, id) {
if (err) {
cb(err);
return;
}
self[fieldName] = id;
defaultSave.call(self, function(err, obj) {
if (err &&
err.code == 11000 &&
err.err.indexOf(fieldName) !== -1 &&
retries > 0
) {
--retries;
attemptSave();
} else {
// TODO check these args
cb(err, obj);
}
});
});
}
attemptSave();
return;
}
}
}
defaultSave.call(this, cb);
};
module.exports = exports = ShortId;
|
Use query result rather than simply syntax binding | <?php
namespace DB\Driver;
/**
* Database driver for MYSQL using MYSQLI rather than default and deprecated
* MYSQL which is recommended by most PHP developer.
*
* @package DB\Driver
*/
class MYSQLI implements IDriver
{
private $mysqli;
public function connect($host, $user, $password)
{
$this->mysqli = new \mysqli($host, $user, $password);
}
public function database($name)
{
$this->mysqli->select_db($name);
}
public function query($sql)
{
$result = $this->mysqli->query($sql);
return $result->mysqli_fetch_all();
}
public function bind($sql, $data=[])
{
$length = count($data);
for ($i=0;$i<$length;$i++)
{
$data[$i] = mysqli_escape_string($data[$i]);
}
$subs = 0;
while (($pos = strpos($sql, '?')) !== false)
{
$sql = substr_replace($sql, $data[$subs], $pos);
$subs++;
}
return $this->query($sql);
}
}
?>
| <?php
namespace DB\Driver;
/**
* Database driver for MYSQL using MYSQLI rather than default and deprecated
* MYSQL which is recommended by most PHP developer.
*
* @package DB\Driver
*/
class MYSQLI implements IDriver
{
private $mysqli;
public function connect($host, $user, $password)
{
$this->mysqli = new \mysqli($host, $user, $password);
}
public function database($name)
{
$this->mysqli->select_db($name);
}
public function query($sql)
{
$result = $this->mysqli->query($sql);
return $result->mysqli_fetch_all();
}
public function bind($sql, $data=[])
{
$length = count($data);
for ($i=0;$i<$length;$i++)
{
$data[$i] = mysqli_escape_string($data[$i]);
}
$subs = 0;
while (($pos = strpos($sql, '?')) !== false)
{
$sql = substr_replace($sql, $data[$subs], $pos);
$subs++;
}
return $sql;
}
}
?>
|
Handle cases where nvidia-smi does not exist | from setuptools import setup
from subprocess import check_output, CalledProcessError
try:
num_gpus = len(check_output(['nvidia-smi', '--query-gpu=gpu_name',
'--format=csv']).decode().strip().split('\n'))
tf = 'tensorflow-gpu' if num_gpus > 1 else 'tensorflow'
except CalledProcessError:
tf = 'tensorflow'
except FileNotFoundError:
tf = 'tensorflow'
setup(
name='autoencoder',
version='0.1',
description='An autoencoder implementation',
author='Gokcen Eraslan',
author_email="goekcen.eraslan@helmholtz-muenchen.de",
packages=['autoencoder'],
install_requires=[tf,
'numpy>=1.7',
'keras>=1.2',
'six>=1.10.0',
'scikit-learn',
'pandas' #for preprocessing
],
url='https://github.com/gokceneraslan/autoencoder',
entry_points={
'console_scripts': [
'autoencoder = autoencoder.__main__:main'
]},
license='Apache License 2.0',
classifiers=['License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5'],
)
| from setuptools import setup
from subprocess import check_output, CalledProcessError
try:
num_gpus = len(check_output(['nvidia-smi', '--query-gpu=gpu_name',
'--format=csv']).decode().strip().split('\n'))
tf = 'tensorflow-gpu' if num_gpus > 1 else 'tensorflow'
except CalledProcessError:
tf = 'tensorflow'
setup(
name='autoencoder',
version='0.1',
description='An autoencoder implementation',
author='Gokcen Eraslan',
author_email="goekcen.eraslan@helmholtz-muenchen.de",
packages=['autoencoder'],
install_requires=[tf,
'numpy>=1.7',
'keras>=1.2',
'six>=1.10.0',
'scikit-learn',
'pandas' #for preprocessing
],
url='https://github.com/gokceneraslan/autoencoder',
entry_points={
'console_scripts': [
'autoencoder = autoencoder.__main__:main'
]},
license='Apache License 2.0',
classifiers=['License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5'],
)
|
Remove the ? mark at because not all video URLs contain it, therefore it misses some URLs. | function findUrls( text )
{
var source = (text || '').toString();
var urlArray = [];
var url;
var matchArray;
// Regular expression to find FTP, HTTP(S) and email URLs.
var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;
// Iterate through any URLs in the text.
while( (matchArray = regexToken.exec( source )) !== null )
{
var token = matchArray[0];
urlArray.push( token );
}
return urlArray;
}
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Received message: " + request.action);
if (request.action == "getVideoSrc") {
var urls = findUrls($('#player').text());
for (var i = 0; i < urls.length; i++) {
if (urls[i].indexOf('.flv') >= 0 || urls[i].indexOf('.mp4') >= 0) {
var videoSrc = decodeURIComponent(urls[i]);
sendResponse({videoSrc: videoSrc});
return;
}
}
} else {
console.log('Unknown action: ' + request.action);
}
}
); | function findUrls( text )
{
var source = (text || '').toString();
var urlArray = [];
var url;
var matchArray;
// Regular expression to find FTP, HTTP(S) and email URLs.
var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;
// Iterate through any URLs in the text.
while( (matchArray = regexToken.exec( source )) !== null )
{
var token = matchArray[0];
urlArray.push( token );
}
return urlArray;
}
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("Received message: " + request.action);
if (request.action == "getVideoSrc") {
var urls = findUrls($('#player').text());
for (var i = 0; i < urls.length; i++) {
if (urls[i].indexOf('.flv?') >= 0 || urls[i].indexOf('.mp4?') >= 0) {
var videoSrc = decodeURIComponent(urls[i]);
sendResponse({videoSrc: videoSrc});
return;
}
}
} else {
console.log('Unknown action: ' + request.action);
}
}
); |
Test changes in myfeature branch | <?php
/* MYFEATURE BRANCH */
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Angrybirds;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
/*public function onBootstrap($e)
{
// You may not need to do this if you're doing it elsewhere in your
// application
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}*/
}
| <?php
/* DEVELOPMENT BRANCH */
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Angrybirds;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
/*public function onBootstrap($e)
{
// You may not need to do this if you're doing it elsewhere in your
// application
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}*/
}
|
Send theme setting during startup | //
// Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const _ = require('lodash'),
redis = require('../lib/redis').createClient(),
notification = require('../lib/notification');
exports.sendSet = function*(userId, sessionId) {
let settings = (yield redis.hgetall(`settings:${userId}`)) || {};
_.defaults(settings, {
activeDesktop: 0,
theme: 'default'
});
let user = yield redis.hgetall(`user:${userId}`);
let command = {
id: 'SET',
settings: {
activeDesktop: parseInt(settings.activeDesktop),
theme: settings.theme,
email: user.email,
emailConfirmed: user.emailConfirmed === 'true'
}
};
if (sessionId) {
yield notification.send(userId, sessionId, command);
} else {
yield notification.broadcast(userId, command);
}
};
| //
// Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const _ = require('lodash'),
redis = require('../lib/redis').createClient(),
notification = require('../lib/notification');
exports.sendSet = function*(userId, sessionId) {
let settings = (yield redis.hgetall(`settings:${userId}`)) || {};
_.defaults(settings, {
activeDesktop: 0
});
let user = yield redis.hgetall(`user:${userId}`);
let command = {
id: 'SET',
settings: {
activeDesktop: parseInt(settings.activeDesktop),
email: user.email,
emailConfirmed: user.emailConfirmed === 'true'
}
};
if (sessionId) {
yield notification.send(userId, sessionId, command);
} else {
yield notification.broadcast(userId, command);
}
};
|
Revert "Get more data from onChange event" | import React, { PropTypes } from 'react';
import classNames from 'classnames';
import mdlUpgrade from './utils/mdlUpgrade';
class Switch extends React.Component {
static propTypes = {
checked: PropTypes.bool,
className: PropTypes.string,
disabled: PropTypes.bool,
id: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
ripple: PropTypes.bool
}
_handleChange = (event) => {
this.props.onChange(event.target.checked);
}
render() {
var { checked, className, disabled, id, ripple } = this.props;
var inputId = 'switch-' + id;
// enable ripple by default
ripple = ripple !== false;
var classes = classNames('mdl-switch mdl-js-switch', {
'mdl-js-ripple-effect': ripple
}, className);
return (
<label className={classes} htmlFor={inputId}>
<input
type="checkbox"
id={inputId}
className="mdl-switch__input"
checked={checked}
disabled={disabled}
onChange={this._handleChange}
/>
<span className="mdl-switch__label">{this.props.children}</span>
</label>
);
}
}
export default mdlUpgrade(Switch);
| import React, { PropTypes } from 'react';
import classNames from 'classnames';
import mdlUpgrade from './utils/mdlUpgrade';
class Switch extends React.Component {
static propTypes = {
checked: PropTypes.bool,
className: PropTypes.string,
disabled: PropTypes.bool,
id: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
ripple: PropTypes.bool
}
_handleChange = (event) => {
this.props.onChange(event);
}
render() {
var { checked, className, disabled, id, ripple } = this.props;
// enable ripple by default
ripple = ripple !== false;
var classes = classNames('mdl-switch mdl-js-switch', {
'mdl-js-ripple-effect': ripple
}, className);
return (
<label className={classes} htmlFor={id}>
<input
type="checkbox"
id={id}
className="mdl-switch__input"
checked={checked}
disabled={disabled}
onChange={this._handleChange}
/>
<span className="mdl-switch__label">{this.props.children}</span>
</label>
);
}
}
export default mdlUpgrade(Switch);
|
Set NODE_ENV to production in release build (build react in prod mode) | const webpack = require("webpack");
const CURRENT_STYLE = process.env.INFOTV_STYLE || "desucon";
const outputFsPath = process.env.OUTPUT_PATH || `${__dirname}/../static/infotv`;
const outputPublicPath = process.env.PUBLIC_PATH || "/static/infotv";
const production = process.argv.indexOf("-p") !== -1;
const config = {
context: __dirname,
entry: "./src/main.js",
bail: true,
devtool: "source-map",
output: {
path: outputFsPath,
filename: "bundle.js",
publicPath: outputPublicPath,
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel",
},
{
test: /\.(woff|svg|otf|ttf|eot|png)(\?.*)?$/,
loader: "url",
},
],
},
resolve: {
alias: {
"current-style": `../styles/${CURRENT_STYLE}/less/style.less`,
},
},
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|fi/),
],
};
if (production) {
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production"),
},
})
);
}
module.exports = config;
| const webpack = require("webpack");
const CURRENT_STYLE = process.env.INFOTV_STYLE || "desucon";
const outputFsPath = process.env.OUTPUT_PATH || `${__dirname}/../static/infotv`;
const outputPublicPath = process.env.PUBLIC_PATH || "/static/infotv";
module.exports = {
context: __dirname,
entry: "./src/main.js",
bail: true,
devtool: "source-map",
output: {
path: outputFsPath,
filename: "bundle.js",
publicPath: outputPublicPath,
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel",
},
{
test: /\.(woff|svg|otf|ttf|eot|png)(\?.*)?$/,
loader: "url",
},
],
},
resolve: {
alias: {
"current-style": `../styles/${CURRENT_STYLE}/less/style.less`,
},
},
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|fi/),
],
};
|
Print output on success/failure & catch exceptions. | <?php
namespace Northstar\Console\Commands;
use Carbon\Carbon;
use DoSomething\Gateway\Blink;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Northstar\Models\User;
class BackfillCustomerIoProfiles extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'northstar:cio {start}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send profiles updated after the given date to Customer.io';
/**
* Execute the console command.
*
* @param Blink $blink
* @return mixed
*/
public function handle(Blink $blink)
{
$start = new Carbon($this->argument('start'));
// Iterate over users where the `mobile` field is not null
// or their profile was updated after the given date.
$query = User::whereNotNull('mobile')
->orWhere('updated_at', '>', $start);
$query->chunkById(200, function (Collection $records) use ($blink) {
$users = User::hydrate($records->toArray());
// Send each of the loaded users to Blink's user queue.
$users->each(function ($user) {
try {
gateway('blink')->userCreate($user->toBlinkPayload());
$this->line('Successfully backfilled user '.$user->id);
} catch (Exception $e) {
$this->error('Failed to backfill user '.$user->id);
}
});
});
}
}
| <?php
namespace Northstar\Console\Commands;
use Carbon\Carbon;
use DoSomething\Gateway\Blink;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Northstar\Models\User;
class BackfillCustomerIoProfiles extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'northstar:cio {start}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send profiles updated after the given date to Customer.io';
/**
* Execute the console command.
*
* @param Blink $blink
* @return mixed
*/
public function handle(Blink $blink)
{
$start = new Carbon($this->argument('start'));
// Iterate over users where the `mobile` field is not null
// or their profile was updated after the given date.
$query = User::whereNotNull('mobile')
->orWhere('updated_at', '>', $start);
$query->chunkById(200, function (Collection $records) use ($blink) {
$users = User::hydrate($records->toArray());
// Send each of the loaded users to Blink's user queue.
$users->each(function ($user) {
gateway('blink')->userCreate($user->toBlinkPayload());
});
});
}
}
|
Enable SSL communication for PubNub
This makes the communication with PubNub more secure. this update sends device info, including lng/lat coordinates, so its best to use SSL. | import EventEmitter from "events";
import PubNub from "pubnub";
export default class Subscriptions extends EventEmitter {
constructor() {
super();
this.subscribers = {};
}
getOrAddSubscriber(subscribeKey) {
if (!this.subscribers[subscribeKey]) {
this.subscribers[subscribeKey] = new PubNub({
ssl:true,
subscribeKey
});
this.subscribers[subscribeKey].addListener({
message: this.onMessage.bind(this)
});
}
return this.subscribers[subscribeKey];
}
subscribe(subscription) {
const { pubnub } = subscription;
const subscriber = this.getOrAddSubscriber(pubnub.subscribe_key);
subscriber.subscribe({
channels: [pubnub.channel]
});
}
unsubscribe(subscription) {
const { pubnub } = subscription;
const subscriber = this.getOrAddSubscriber(pubnub.subscribe_key);
subscriber.unsubscribe({
channels: [pubnub.channel]
});
}
onMessage(message) {
const msg = typeof message.message !== "string"
? message.message
: JSON.parse(message.message);
this.emit("message", msg);
if (
msg.uuid &&
msg.name &&
msg.object_type &&
msg.object_id &&
msg.last_reading
) {
return this.emit("device-update", msg);
}
if (msg.data && Array.isArray(msg.data)) {
return this.emit("device-list", msg);
}
this.emit("unknown-message", msg);
}
}
| import EventEmitter from "events";
import PubNub from "pubnub";
export default class Subscriptions extends EventEmitter {
constructor() {
super();
this.subscribers = {};
}
getOrAddSubscriber(subscribeKey) {
if (!this.subscribers[subscribeKey]) {
this.subscribers[subscribeKey] = new PubNub({
subscribeKey
});
this.subscribers[subscribeKey].addListener({
message: this.onMessage.bind(this)
});
}
return this.subscribers[subscribeKey];
}
subscribe(subscription) {
const { pubnub } = subscription;
const subscriber = this.getOrAddSubscriber(pubnub.subscribe_key);
subscriber.subscribe({
channels: [pubnub.channel]
});
}
unsubscribe(subscription) {
const { pubnub } = subscription;
const subscriber = this.getOrAddSubscriber(pubnub.subscribe_key);
subscriber.unsubscribe({
channels: [pubnub.channel]
});
}
onMessage(message) {
const msg = typeof message.message !== "string"
? message.message
: JSON.parse(message.message);
this.emit("message", msg);
if (
msg.uuid &&
msg.name &&
msg.object_type &&
msg.object_id &&
msg.last_reading
) {
return this.emit("device-update", msg);
}
if (msg.data && Array.isArray(msg.data)) {
return this.emit("device-list", msg);
}
this.emit("unknown-message", msg);
}
}
|
Change teleop to drive with the new Gamepad class. | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.edinarobotics.zephyr;
import com.edinarobotics.utils.gamepad.Gamepad;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Zephyr extends SimpleRobot {
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
Gamepad gamepad1 = new Gamepad(1);
Components components = Components.getInstance();
while(this.isOperatorControl()&&this.isEnabled()){
components.leftJaguar.set(gamepad1.getLeftY());
components.rightJaguar.set(gamepad1.getRightY());
}
components.leftJaguar.set(0);
components.rightJaguar.set(0);
}
}
| /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.edinarobotics.zephyr;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Zephyr extends SimpleRobot {
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
Joystick joystick = new Joystick(1);
Components components = Components.getInstance();
while(this.isOperatorControl()&&this.isEnabled()){
components.leftJaguar.set(joystick.getRawAxis(2));
components.rightJaguar.set(joystick.getRawAxis(5));
}
components.leftJaguar.set(0);
components.rightJaguar.set(0);
}
}
|
Add ref to table element | var React = require('react');
var data = require('./data.full.js');
var options = {
rowHeight: 40
};
var ReactDataTable = React.createClass({
getInitialState: function() {
return {
rowsToDisplay: {
toHideAbove: 0,
toRender: 0,
toHideBelow: 0
}
};
},
render: function() {
var createCell = function createCell (key, value) {
return <td key={key}>{value}</td>;
};
var createRow = function createRow (row) {
return (
<tr key={row._id}>{
Object.keys(row).map( function(key) {
return createCell(key, row[key]);
})
}</tr>
);
};
var createHeaderCell = function createHeaderCell (key) {
return <th key={key}>{key}</th>;
};
var createTable = function createTable (table) {
return (
<table ref="table">
<thead>{
Object.keys(table[0]).map(function (key) {
return createHeaderCell(key);
})
}</thead>
<tbody>
{table.map(createRow)}
</tbody>
</table>
);
}.bind(this);
return createTable(this.props.data);
}
});
React.render(<ReactDataTable data={data} options={options} />, document.getElementById('app'));
| var React = require('react');
var data = require('./data.full.js');
var options = {
rowHeight: 40
};
var ReactDataTable = React.createClass({
getInitialState: function() {
return {
rowsToDisplay: {
toHideAbove: 0,
toRender: 0,
toHideBelow: 0
}
};
},
render: function() {
var createCell = function createCell (key, value) {
return <td key={key}>{value}</td>;
};
var createRow = function createRow (row) {
return (
<tr key={row._id}>{
Object.keys(row).map( function(key) {
return createCell(key, row[key]);
})
}</tr>
);
};
var createHeaderCell = function createHeaderCell (key) {
return <th key={key}>{key}</th>;
};
var createTable = function createTable (table) {
return (
<table>
<thead>{
Object.keys(table[0]).map(function (key) {
return createHeaderCell(key);
})
}</thead>
<tbody>
{table.map(createRow)}
</tbody>
</table>
);
}
return createTable(this.props.data);
}
});
React.render(<ReactDataTable data={data} options={options} />, document.getElementById('app'));
|
Fix missing synchronized read access | <?php
require dirname(__DIR__).'/vendor/autoload.php';
use Icicle\Concurrent\Forking\ForkContext;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
class Test extends ForkContext
{
/**
* @synchronized
*/
public $data;
public function run()
{
print "Child sleeping for 4 seconds...\n";
sleep(4);
yield $this->synchronized(function () {
$this->data = 'progress';
});
print "Child sleeping for 2 seconds...\n";
sleep(2);
}
}
$generator = function () {
$context = new Test();
$context->data = 'blank';
$context->start();
Loop\timer(1, function () use ($context) {
$context->synchronized(function ($context) {
print "Finally got lock from child!\n";
});
});
$timer = Loop\periodic(1, function () use ($context) {
static $i;
$i = $i + 1 ?: 1;
print "Demonstrating how alive the parent is for the {$i}th time.\n";
if ($context->isRunning()) {
$context->synchronized(function ($context) {
printf("Context data: '%s'\n", $context->data);
});
}
});
try {
yield $context->join();
print "Context done!\n";
} catch (Exception $e) {
print "Error from child!\n";
print $e."\n";
} finally {
$timer->stop();
}
};
new Coroutine($generator());
Loop\run();
| <?php
require dirname(__DIR__).'/vendor/autoload.php';
use Icicle\Concurrent\Forking\ForkContext;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
class Test extends ForkContext
{
/**
* @synchronized
*/
public $data;
public function run()
{
print "Child sleeping for 4 seconds...\n";
yield $this->lock();
sleep(4);
yield $this->unlock();
yield $this->synchronized(function () {
$this->data = 'progress';
});
print "Child sleeping for 2 seconds...\n";
sleep(2);
}
}
$generator = function () {
$context = new Test();
$context->data = 'blank';
$context->start();
Loop\timer(1, function () use ($context) {
$context->synchronized(function ($context) {
print "Finally got lock from child!\n";
});
});
$timer = Loop\periodic(1, function () use ($context) {
static $i;
$i = $i + 1 ?: 1;
print "Demonstrating how alive the parent is for the {$i}th time.\n";
if ($context->isRunning()) {
printf("Context data: '%s'\n", $context->data);
}
});
try {
yield $context->join();
print "Context done!\n";
} catch (Exception $e) {
print "Error from child!\n";
print $e."\n";
} finally {
$timer->stop();
}
};
new Coroutine($generator());
Loop\run();
|
Fix login test in Travis. | /*jshint quotmark: false */
"use strict";
var rio = require("../lib/rio"),
vows = require("vows"),
assert = require("assert");
var isEnablePlaybackMode = process.env.CI === "true";
vows.describe("Login tests").addBatch({
"login ok test": {
topic: function () {
rio.enablePlaybackMode(isEnablePlaybackMode, {
fileName: "test/dump/login-ok-test.bin"
});
rio.evaluate("2+2", {
callback: this.callback
});
},
"eval with login ok": function (err, topic) {
if (!err) {
assert(4, topic);
}
}
},
"login ko test": {
topic: function () {
rio.enablePlaybackMode(isEnablePlaybackMode, {
fileName: "test/dump/login-ko-test.bin"
});
rio.evaluate("2+2", {
user: "wrong user",
password: "wrong password",
callback: this.callback
});
},
"eval with login ko": function (err, topic) {
if (!err) {
assert(4, topic);
} else {
if (err.code) {
assert.equal("ECONNRESET", err.code);
} else {
if ("Response with error code 65" !== err && // Rserve
"Response with error code 0" !== err && // Local
"Eval failed with error code 0" !== err) { // Travis
assert.ifError(err);
}
}
}
}
}
}).export(module);
| /*jshint quotmark: false */
"use strict";
var rio = require("../lib/rio"),
vows = require("vows"),
assert = require("assert");
var isEnablePlaybackMode = process.env.CI === "true";
vows.describe("Login tests").addBatch({
"login ok test": {
topic: function () {
rio.enablePlaybackMode(isEnablePlaybackMode, {
fileName: "test/dump/login-ok-test.bin"
});
rio.evaluate("2+2", {
callback: this.callback
});
},
"eval with login ok": function (err, topic) {
if (!err) {
assert(4, topic);
}
}
},
"login ko test": {
topic: function () {
rio.enablePlaybackMode(isEnablePlaybackMode, {
fileName: "test/dump/login-ko-test.bin"
});
rio.evaluate("2+2", {
user: "wrong user",
password: "wrong password",
callback: this.callback
});
},
"eval with login ko": function (err, topic) {
if (!err) {
assert(4, topic);
} else {
if (err.code) {
assert.equal("ECONNRESET", err.code);
} else {
if ("Response with error code 65" !== err &&
"Response with error code 0" !== err) {
assert.ifError(err);
}
}
}
}
}
}).export(module);
|
Fix formSelect component's default option
When adding using the `default-option` directive you would need to have added a `length` property with a truthy value to successfully add the default option. This change fixes that by making sure there is a default option with a text and value property. | // import dependencies
import {uniqueId} from '../../utils/helpers.js'
import template from './form-select.html'
// export component object
export default {
template: template,
replace: true,
computed: {
allOptions(){
if (this.defaultOption.text && this.defaultOption.value) {
return [this.defaultOption].concat(this.options)
}
return this.options
},
inputState() {
return !this.state || this.state === `default` ? `` : `has-${this.state}`
},
inputSize() {
return !this.size || this.size === `default` ? `` : `form-control-${this.size}`
},
},
props: {
model: {
twoWay: true,
required: true
},
options: {
type: Array,
default: [],
required: true,
},
id: {
type: String,
default: uniqueId
},
label: {
type: String,
default: false
},
defaultOption: {
type: Object,
default() {
return {}
}
},
description: {
type: String,
default: false
},
size: {
type: String,
default: ''
},
state: {
type: String,
default: ''
},
},
watch: {
model(val, oldVal) {
if (val === oldVal) return
// Dispatch an event from the current vm that propagates all the way up to it's $root
this.$dispatch('selected::option', val)
}
}
}
| // import dependencies
import {uniqueId} from '../../utils/helpers.js'
import template from './form-select.html'
// export component object
export default {
template: template,
replace: true,
computed: {
allOptions(){
if (this.defaultOption.length) {
return [this.defaultOption].concat(this.options)
}
return this.options
},
inputState() {
return !this.state || this.state === `default` ? `` : `has-${this.state}`
},
inputSize() {
return !this.size || this.size === `default` ? `` : `form-control-${this.size}`
},
},
props: {
model: {
twoWay: true,
required: true
},
options: {
type: Array,
default: [],
required: true,
},
id: {
type: String,
default: uniqueId
},
label: {
type: String,
default: false
},
defaultOption: {
type: Object,
default() {
return {}
}
},
description: {
type: String,
default: false
},
size: {
type: String,
default: ''
},
state: {
type: String,
default: ''
},
},
watch: {
model(val, oldVal) {
if (val === oldVal) return
// Dispatch an event from the current vm that propagates all the way up to it's $root
this.$dispatch('selected::option', val)
}
}
}
|
Rename option to caseSensitive to avoid double negation | "use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var caseSensitive = context.options[0].caseSensitive;
var ignoreMethods = context.options[0].ignoreMethods;
var MSG = "Property names in object literals should be sorted";
return {
"ObjectExpression": function(node) {
node.properties.reduce(function(lastProp, prop) {
if (ignoreMethods &&
prop.value.type === "FunctionExpression") {
return prop;
}
var lastPropId, propId;
if (prop.key.type === "Identifier") {
lastPropId = lastProp.key.name;
propId = prop.key.name;
} else if (prop.key.type === "Literal") {
lastPropId = lastProp.key.value;
propId = prop.key.value;
}
if (caseSensitive) {
lastPropId = lastPropId.toLowerCase();
propId = propId.toLowerCase();
}
if (propId < lastPropId) {
context.report(prop, MSG);
}
return prop;
}, node.properties[0]);
}
};
}
},
rulesConfig: {
"sort-object-props": [ 1, { caseSensitive: false, ignoreMethods: false } ]
}
};
| "use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var ignoreCase = context.options[0].ignoreCase;
var ignoreMethods = context.options[0].ignoreMethods;
var MSG = "Property names in object literals should be sorted";
return {
"ObjectExpression": function(node) {
node.properties.reduce(function(lastProp, prop) {
if (ignoreMethods &&
prop.value.type === "FunctionExpression") {
return prop;
}
var lastPropId, propId;
if (prop.key.type === "Identifier") {
lastPropId = lastProp.key.name;
propId = prop.key.name;
} else if (prop.key.type === "Literal") {
lastPropId = lastProp.key.value;
propId = prop.key.value;
}
if (ignoreCase) {
if (propId == null)
console.log(prop);
lastPropId = lastPropId.toLowerCase();
propId = propId.toLowerCase();
}
if (propId < lastPropId) {
context.report(prop, MSG);
}
return prop;
}, node.properties[0]);
}
};
}
},
rulesConfig: {
"sort-object-props": [ 1, { ignoreCase: true, ignoreMethods: false } ]
}
};
|
Remove duplicate version number and stability. | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>Package :: <?php echo $context->name; ?></h2>
<p><em><?php echo $context->summary; ?></em></p>
<p>
<?php
echo nl2br(trim($context->description));
?>
</p>
<?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>
</div>
<div class="grid_4 right releases">
<h3>Releases</h3>
<ul>
<?php
foreach ($context as $version => $release): ?>
<li>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?></a>
<span class="stability"><?php echo $release['stability']; ?></span>
<abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr>
<a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
| <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>Package :: <?php echo $context->name; ?></h2>
<p><em><?php echo $context->summary; ?></em></p>
<p>
<?php
echo nl2br(trim($context->description));
?>
</p>
<?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>
</div>
<div class="grid_4 right releases">
<h3>Releases</h3>
<ul>
<?php
foreach ($context as $version => $release): ?>
<li>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?></a>
<span class="stability"><?php echo $release['stability']; ?></span>
<?php echo $version; ?> <span class="stability"><?php echo $release['stability']; ?></span>
<abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr>
<a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
|
Change the name to match the repo
And decent naming conventions, underscores are yuck for names :p | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
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)
def version():
import gocd_cli
return gocd_cli.__version__
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='gocd-cli',
author='Björn Andersson',
author_email='ba@sanitarium.se',
license='MIT License',
description='A CLI client for interacting with Go Continuous Delivery',
long_description=README,
version=version(),
packages=find_packages(exclude=('tests',)),
namespace_packages=('gocd_cli', 'gocd_cli.commands',),
cmdclass={'test': PyTest},
install_requires=[
'gocd>=0.7,<1.0',
],
tests_require=[
'pytest',
'mock==1.0.1'
],
)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
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)
def version():
import gocd_cli
return gocd_cli.__version__
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='gocd_cli',
author='Björn Andersson',
author_email='ba@sanitarium.se',
license='MIT License',
description='A CLI client for interacting with Go Continuous Delivery',
long_description=README,
version=version(),
packages=find_packages(exclude=('tests',)),
namespace_packages=('gocd_cli', 'gocd_cli.commands',),
cmdclass={'test': PyTest},
install_requires=[
'gocd>=0.7,<1.0',
],
tests_require=[
'pytest',
'mock==1.0.1'
],
)
|
Replace out of date library | requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-3.3.0',
'knockout-validation': '../lib/knockout/knockout.validation',
'breeze': '../lib/breeze/breeze.min',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.11.2'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jQuery'
}
}
});
define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) {
// >>excludeStart("build", true);
system.debug(true);
// >>excludeEnd("build");
app.title = 'Durandal Application';
app.configurePlugins({
router:true,
dialog: true
});
app.start().then(function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
});
}); | requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-3.1.0',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.9.1'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jQuery'
}
}
});
define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) {
// >>excludeStart("build", true);
system.debug(true);
// >>excludeEnd("build");
app.title = 'Durandal Application';
app.configurePlugins({
router:true,
dialog: true
});
app.start().then(function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
});
}); |
Reduce number of DB calls in NowPlayingController | <?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;
class Api_NowplayingController extends \PVL\Controller\Action\Api
{
public function indexAction()
{
$file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
$np_raw = file_get_contents($file_path_api);
if ($this->hasParam('id') || $this->hasParam('station'))
{
$np_arr = @json_decode($np_raw, TRUE);
$np = $np_arr['result'];
if ($this->hasParam('id'))
{
$id = (int)$this->getParam('id');
foreach($np as $key => $station) {
if($station->id === $id) {
$sc = $key;
break;
}
}
return $this->returnError('Station not found!');
}
elseif ($this->hasParam('station'))
{
$sc = $this->getParam('station');
}
if (isset($np[$sc]))
$this->returnSuccess($np[$sc]);
else
return $this->returnError('Station not found!');
}
else
{
$this->returnRaw($np_raw, 'json');
}
}
} | <?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;
class Api_NowplayingController extends \PVL\Controller\Action\Api
{
public function indexAction()
{
$file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
$np_raw = file_get_contents($file_path_api);
if ($this->hasParam('id') || $this->hasParam('station'))
{
$np_arr = @json_decode($np_raw, TRUE);
$np = $np_arr['result'];
if ($this->hasParam('id'))
{
$id = (int)$this->getParam('id');
$station = Station::find($id);
if (!($station instanceof Station))
return $this->returnError('Station not found!');
else
$sc = $station->getShortName();
}
elseif ($this->hasParam('station'))
{
$sc = $this->getParam('station');
}
if (isset($np[$sc]))
$this->returnSuccess($np[$sc]);
else
return $this->returnError('Station not found!');
}
else
{
$this->returnRaw($np_raw, 'json');
}
}
} |
Use English for UI by default | import React, { Component } from "react";
import Quiz from "./Quiz";
import "./App.css";
import questions from "./questions.json";
import strings from "./strings.json";
class LanguageChooser extends Component {
handleChoice(language, evt) {
this.props.reporter(language);
}
render() {
const items = this.props.languages.map(language => {
const handler = this.handleChoice.bind(this, language)
return (
<li key={language} onClick={handler}>
{strings[language].__language__.displayName}
</li>
);
});
return <ol>{items}</ol>;
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {language: "en"};
this.handleLanguage = this.handleLanguage.bind(this);
}
handleLanguage(language) {
this.setState({language: language});
}
render() {
return (
<div>
<LanguageChooser
languages={["en", "ru"]}
reporter={this.handleLanguage} />
<Quiz
questions={questions} askCount={2}
strings={strings[this.state.language].quiz} />
</div>
);
}
}
| import React, { Component } from "react";
import Quiz from "./Quiz";
import "./App.css";
import questions from "./questions.json";
import strings from "./strings.json";
class LanguageChooser extends Component {
handleChoice(language, evt) {
this.props.reporter(language);
}
render() {
const items = this.props.languages.map(language => {
const handler = this.handleChoice.bind(this, language)
return (
<li key={language} onClick={handler}>
{strings[language].__language__.displayName}
</li>
);
});
return <ol>{items}</ol>;
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {language: "dummy"};
this.handleLanguage = this.handleLanguage.bind(this);
}
handleLanguage(language) {
this.setState({language: language});
}
render() {
return (
<div>
<LanguageChooser
languages={["en", "ru"]}
reporter={this.handleLanguage} />
<Quiz
questions={questions} askCount={2}
strings={strings[this.state.language].quiz} />
</div>
);
}
}
|
Save the players array correctly when saving game stats | const mongoskin = require('mongoskin');
const logger = require('../log.js');
class GameRepository {
save(game, callback) {
var db = mongoskin.db('mongodb://127.0.0.1:27017/throneteki');
if(!game.id) {
db.collection('games').insert(game, function(err, result) {
if(err) {
logger.info(err.message);
callback(err);
return;
}
callback(undefined, result.ops[0]._id);
});
} else {
db.collection('games').update({ _id: mongoskin.helper.toObjectID(game.id) }, {
'$set': {
startedAt: game.startedAt,
players: game.players,
winner: game.winner,
winReason: game.winReason,
finishedAt: game.finishedAt
}
});
}
}
}
module.exports = GameRepository;
| const mongoskin = require('mongoskin');
const logger = require('../log.js');
class GameRepository {
save(game, callback) {
var db = mongoskin.db('mongodb://127.0.0.1:27017/throneteki');
if(!game.id) {
db.collection('games').insert(game, function(err, result) {
if(err) {
logger.info(err.message);
callback(err);
return;
}
callback(undefined, result.ops[0]._id);
});
} else {
db.collection('games').update({ _id: mongoskin.helper.toObjectID(game.id) }, {
'$set': {
startedAt: game.startedAt,
players: game.playersAndSpectators,
winner: game.winner,
winReason: game.winReason,
finishedAt: game.finishedAt
}
});
}
}
}
module.exports = GameRepository;
|
Support 'none' as smtp encryption | <?php
namespace AppZap\PHPFramework\Mail;
use AppZap\PHPFramework\Configuration\Configuration;
class MailService {
/**
* @param MailMessage $message
*/
public function send(MailMessage $message) {
$transport = $this->createTransport();
$mailer = new \Swift_Mailer($transport);
$mailer->send($message);
}
/**
* @return \Swift_Transport
*/
protected function createTransport() {
$mailConfiguration = Configuration::getSection(
'phpframework',
'mail',
[
'smtp_encryption' => 'ssl',
'smtp_host' => 'localhost',
'smtp_password' => '',
'smtp_port' => FALSE,
'smtp_user' => FALSE,
]
);
if (!$mailConfiguration['smtp_user']) {
return \Swift_MailTransport::newInstance();
}
if ($mailConfiguration['smtp_encryption'] === 'none') {
$mailConfiguration['smtp_encryption'] = NULL;
}
if (!$mailConfiguration['smtp_port']) {
if ($mailConfiguration['smtp_encryption'] === 'ssl') {
$mailConfiguration['smtp_port'] = '465';
} else {
$mailConfiguration['smtp_port'] = '587';
}
}
$transport = \Swift_SmtpTransport::newInstance(
$mailConfiguration['smtp_host'],
$mailConfiguration['smtp_port'],
$mailConfiguration['smtp_encryption']
);
$transport->setUsername($mailConfiguration['smtp_user']);
$transport->setPassword($mailConfiguration['smtp_password']);
return $transport;
}
}
| <?php
namespace AppZap\PHPFramework\Mail;
use AppZap\PHPFramework\Configuration\Configuration;
class MailService {
/**
* @param MailMessage $message
*/
public function send(MailMessage $message) {
$transport = $this->createTransport();
$mailer = new \Swift_Mailer($transport);
$mailer->send($message);
}
/**
* @return \Swift_Transport
*/
protected function createTransport() {
$mailConfiguration = Configuration::getSection(
'phpframework',
'mail',
[
'smtp_encryption' => 'ssl',
'smtp_host' => 'localhost',
'smtp_password' => '',
'smtp_port' => FALSE,
'smtp_user' => FALSE,
]
);
if (!$mailConfiguration['smtp_user']) {
return \Swift_MailTransport::newInstance();
}
if (!$mailConfiguration['smtp_port']) {
if ($mailConfiguration['smtp_encryption'] === 'ssl') {
$mailConfiguration['smtp_port'] = '465';
} else {
$mailConfiguration['smtp_port'] = '587';
}
}
$transport = \Swift_SmtpTransport::newInstance(
$mailConfiguration['smtp_host'],
$mailConfiguration['smtp_port'],
$mailConfiguration['smtp_encryption']
);
$transport->setUsername($mailConfiguration['smtp_user']);
$transport->setPassword($mailConfiguration['smtp_password']);
return $transport;
}
}
|
Make "to" not inclusive in widget
To avoid exceeding possible values. | #!/usr/bin/env python
# coding=utf-8
from decimal import Decimal
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field, ValidationError
from tempo.django.widgets import ScheduleSetWidget
from tempo.schedule import Schedule
from tempo.scheduleset import ScheduleSet
class ScheduleSetField(Field):
widget = ScheduleSetWidget
def to_python(self, value):
if value is None:
return None
repeats = value['repeats']
if repeats == 'monthly':
return ScheduleSet(include=[
Schedule(days=[int(value['repeatOn'])])
])
elif repeats == 'weekly':
schedules = []
for repeat_on in value['repeatOn']:
if Decimal(repeat_on['from']) >= Decimal(repeat_on['to']):
raise ValidationError(_('"From" is greater than "to" '
'or equal to it.'),
code='invalid')
schedule = Schedule(
weekdays=[int(repeat_on['weekday'])],
days=[],
seconds_of_the_day=list(range(
int(Decimal(repeat_on['from']) * 60 * 60),
int(Decimal(repeat_on['to']) * 60 * 60))
),
seconds=[], minutes=[], hours=[]
)
schedules.append(schedule)
return ScheduleSet(include=schedules)
else:
raise ValueError
| #!/usr/bin/env python
# coding=utf-8
from decimal import Decimal
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field, ValidationError
from tempo.django.widgets import ScheduleSetWidget
from tempo.schedule import Schedule
from tempo.scheduleset import ScheduleSet
class ScheduleSetField(Field):
widget = ScheduleSetWidget
def to_python(self, value):
if value is None:
return None
repeats = value['repeats']
if repeats == 'monthly':
return ScheduleSet(include=[
Schedule(days=[int(value['repeatOn'])])
])
elif repeats == 'weekly':
schedules = []
for repeat_on in value['repeatOn']:
if Decimal(repeat_on['from']) > Decimal(repeat_on['to']):
raise ValidationError(_('"From" is greater than "to".'),
code='invalid')
schedule = Schedule(
weekdays=[int(repeat_on['weekday'])],
days=[],
seconds_of_the_day=list(range(
int(Decimal(repeat_on['from']) * 60 * 60),
int(Decimal(repeat_on['to']) * 60 * 60) + 1)
),
seconds=[], minutes=[], hours=[]
)
schedules.append(schedule)
return ScheduleSet(include=schedules)
else:
raise ValueError
|
Fix description of time until re-enable clicks | const helpers = require('./support/helpers.js');
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
require('./support/teardown.js');
});
describe('Prevent duplicate form submissions', () => {
let form;
let button;
let formSubmitSpy;
beforeEach(() => {
// set up DOM
document.body.innerHTML = `
<form action="/" method="post">
<button class="button" type="submit">Continue</button>
</form>`;
form = document.querySelector('form');
button = document.querySelector('button');
// requires a helper due to JSDOM not implementing the submit method
formSubmitSpy = helpers.spyOnFormSubmit(jest, form);
require('../../app/assets/javascripts/preventDuplicateFormSubmissions.js');
});
afterEach(() => {
document.body.innerHTML = '';
// we run the previewPane.js script every test
// the module cache needs resetting each time for the script to execute
jest.resetModules();
formSubmitSpy.mockClear();
});
test("It should prevent any clicks of the 'submit' button after the first one submitting the form", () => {
helpers.triggerEvent(button, 'click');
helpers.triggerEvent(button, 'click');
expect(formSubmitSpy.mock.calls.length).toEqual(1);
});
test("It should allow clicks again after 1.5 seconds", () => {
helpers.triggerEvent(button, 'click');
jest.advanceTimersByTime(1500);
helpers.triggerEvent(button, 'click');
expect(formSubmitSpy.mock.calls.length).toEqual(2);
});
});
| const helpers = require('./support/helpers.js');
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
require('./support/teardown.js');
});
describe('Prevent duplicate form submissions', () => {
let form;
let button;
let formSubmitSpy;
beforeEach(() => {
// set up DOM
document.body.innerHTML = `
<form action="/" method="post">
<button class="button" type="submit">Continue</button>
</form>`;
form = document.querySelector('form');
button = document.querySelector('button');
// requires a helper due to JSDOM not implementing the submit method
formSubmitSpy = helpers.spyOnFormSubmit(jest, form);
require('../../app/assets/javascripts/preventDuplicateFormSubmissions.js');
});
afterEach(() => {
document.body.innerHTML = '';
// we run the previewPane.js script every test
// the module cache needs resetting each time for the script to execute
jest.resetModules();
formSubmitSpy.mockClear();
});
test("It should prevent any clicks of the 'submit' button after the first one submitting the form", () => {
helpers.triggerEvent(button, 'click');
helpers.triggerEvent(button, 'click');
expect(formSubmitSpy.mock.calls.length).toEqual(1);
});
test("It should allow clicks again after 1.5 minutes", () => {
helpers.triggerEvent(button, 'click');
jest.advanceTimersByTime(1500);
helpers.triggerEvent(button, 'click');
expect(formSubmitSpy.mock.calls.length).toEqual(2);
});
});
|
Fix rmtree call for deleting user's homedirs | from django.core.management.base import BaseCommand, CommandError
from purefap.core.models import FTPUser, FTPStaff, FTPClient
import shutil
from datetime import datetime
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noop',
action='store_true',
dest='noop',
default=False,
help='Just print which users will be deleted'),
make_option('--files',
action='store_true',
dest='files',
default=False,
help='Delete user\'s homedir along with his account')
)
help = 'Delete expired/inactive users'
def handle(self, *args, **options):
for u in FTPClient.objects.all():
if u.expiry_date and u.expiry_date.isocalendar() < datetime.now().isocalendar():
self.stdout.write("User %s will be deleted" % u)
if options ['files']:
self.stdout.write(" - Directory %s and its contents will be deleted" % u.homedir)
if not options['noop']:
if options['files']:
shutil.rmtree(u.homedir.path)
u.delete()
| from django.core.management.base import BaseCommand, CommandError
from purefap.core.models import FTPUser, FTPStaff, FTPClient
import shutil
from datetime import datetime
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noop',
action='store_true',
dest='noop',
default=False,
help='Just print which users will be deleted'),
make_option('--files',
action='store_true',
dest='files',
default=False,
help='Delete user\'s homedir along with his account')
)
help = 'Delete expired/inactive users'
def handle(self, *args, **options):
for u in FTPClient.objects.all():
if u.expiry_date and u.expiry_date.isocalendar() < datetime.now().isocalendar():
self.stdout.write("User %s will be deleted" % u)
if options ['files']:
self.stdout.write(" - Directory %s and its contents will be deleted" % u.homedir)
if not options['noop']:
if options['files']:
shutil.rmtree(u.homedir)
u.delete()
|
Add -p option to invoke Python profiler | import sys
import getopt
from compiler import compile, visitor
import profile
def main():
VERBOSE = 0
DISPLAY = 0
PROFILE = 0
CONTINUE = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqdcp')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1
if k == '-q':
if sys.platform[:3]=="win":
f = open('nul', 'wb') # /dev/null fails on Windows...
else:
f = open('/dev/null', 'wb')
sys.stdout = f
if k == '-d':
DISPLAY = 1
if k == '-c':
CONTINUE = 1
if k == '-p':
PROFILE = 1
if not args:
print "no files to compile"
else:
for filename in args:
if VERBOSE:
print filename
try:
if PROFILE:
profile.run('compile(%s, %s)' % (`filename`, `DISPLAY`),
filename + ".prof")
else:
compile(filename, DISPLAY)
except SyntaxError, err:
print err
print err.lineno
if not CONTINUE:
sys.exit(-1)
if __name__ == "__main__":
main()
| import sys
import getopt
from compiler import compile, visitor
##import profile
def main():
VERBOSE = 0
DISPLAY = 0
CONTINUE = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqdc')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1
if k == '-q':
if sys.platform[:3]=="win":
f = open('nul', 'wb') # /dev/null fails on Windows...
else:
f = open('/dev/null', 'wb')
sys.stdout = f
if k == '-d':
DISPLAY = 1
if k == '-c':
CONTINUE = 1
if not args:
print "no files to compile"
else:
for filename in args:
if VERBOSE:
print filename
try:
compile(filename, DISPLAY)
## profile.run('compile(%s, %s)' % (`filename`, `DISPLAY`),
## filename + ".prof")
except SyntaxError, err:
print err
print err.lineno
if not CONTINUE:
sys.exit(-1)
if __name__ == "__main__":
main()
|
Remove template language hard initialization to dynamic initialization | <?php
namespace Uphp\web;
use \UPhp\ActionController\ActionController;
class Application
{
public static $appConfig = [];
public function __construct()
{
set_exception_handler("src\uphpExceptionHandler");
set_error_handler("src\uphpErrorHandler");
}
public function start($config)
{
//carregando os initializers
$this->loadAppConfig();
$this->getInitializersFiles();
$this->getRoutes();
$this->getLang();
ActionController::callController($config);
}
private function getInitializersFiles()
{
$this->requireAllDir("config/initializers/");
}
private function getRoutes()
{
return require("config/routes.php");
}
private function getLang()
{
$this->requireAllDir("app/languages/");
}
private function loadAppConfig(){
$config = require("config/application.php");
self::$appConfig = $config;
}
private function requireAllDir($path)
{
$directory = dir($path);
while ($file = $directory -> read()) {
if ($file != "." && $file != "..") {
if (is_dir($path . $file)) {
$this->requireAllDir($path . $file . "/");
} else {
require($path . $file);
}
}
}
$directory->close();
}
}
| <?php
namespace Uphp\web;
use src\Inflection;
use \UPhp\ActionDispach\Routes as Route;
use \UPhp\ActionController\ActionController;
class Application
{
public static $appConfig = [];
public static $templateConfig = [];
public function __construct()
{
//set_exception_handler("src\uphpExceptionHandler");
//set_error_handler("src\uphpErrorHandler");
}
public function start($config)
{
//carregando os initializers
$this->loadAppConfig();
$this->getInitializersFiles();
$this->getRoutes();
$this->getLang();
ActionController::callController($config);
}
private function getInitializersFiles()
{
$this->requireAllDir("config/initializers/");
}
private function getRoutes()
{
return require("config/routes.php");
}
private function getLang()
{
$this->requireAllDir("app/languages/");
}
private function loadAppConfig(){
$config = require("config/application.php");
if (isset($config["template"])) {
$templateConfig = require("config/" . Inflection::tableize($config["template"]) . ".php");
self::$templateConfig = $templateConfig;
}
self::$appConfig = $config;
}
private function requireAllDir($path)
{
$directory = dir($path);
while ($file = $directory -> read()) {
if ($file != "." && $file != "..") {
require($path . $file);
}
}
$directory->close();
}
}
|
Update heading on Remote Selector to use imperative tone
Previously the heading looked like an "error" message, however, this is really just a regular state that the user can appear in, and in future revisions this screen could be used for changing the remote directly from within the Github package, therefore an imperative tone fits better with the user's intent. | import React from 'react';
import PropTypes from 'prop-types';
import {RemoteSetPropType, BranchPropType} from '../prop-types';
export default class RemoteSelectorView extends React.Component {
static propTypes = {
remotes: RemoteSetPropType.isRequired,
currentBranch: BranchPropType.isRequired,
selectRemote: PropTypes.func.isRequired,
}
render() {
const {remotes, currentBranch, selectRemote} = this.props;
// todo: ask Ash how to test this before merging.
return (
<div className="github-RemoteSelector">
<div className="github-GitHub-LargeIcon icon icon-mirror" />
<h1>Select a Remote</h1>
<div className="initialize-repo-description">
<span>This repository has multiple remotes hosted at GitHub.com.
Select a remote to see pull requests associated
with the <strong>{currentBranch.getName()}</strong> branch:</span>
</div>
<ul>
{Array.from(remotes, remote => (
<li key={remote.getName()}>
<button className="btn btn-primary" onClick={e => selectRemote(e, remote)}>
{remote.getName()} ({remote.getOwner()}/{remote.getRepo()})
</button>
</li>
))}
</ul>
</div>
);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
import {RemoteSetPropType, BranchPropType} from '../prop-types';
export default class RemoteSelectorView extends React.Component {
static propTypes = {
remotes: RemoteSetPropType.isRequired,
currentBranch: BranchPropType.isRequired,
selectRemote: PropTypes.func.isRequired,
}
render() {
const {remotes, currentBranch, selectRemote} = this.props;
// todo: ask Ash how to test this before merging.
return (
<div className="github-RemoteSelector">
<div className="github-GitHub-LargeIcon icon icon-mirror" />
<h1>Multiple Remotes</h1>
<div className="initialize-repo-description">
<span>This repository has multiple remotes hosted at GitHub.com.
Select a remote to see pull requests associated
with the <strong>{currentBranch.getName()}</strong> branch:</span>
</div>
<ul>
{Array.from(remotes, remote => (
<li key={remote.getName()}>
<button className="btn btn-primary" onClick={e => selectRemote(e, remote)}>
{remote.getName()} ({remote.getOwner()}/{remote.getRepo()})
</button>
</li>
))}
</ul>
</div>
);
}
}
|
gluster: Return UNKNOWN status for GlusterTaskStatus
If the string value passed to GlusterTaskStatus is not
one of the enum options return UNKNOWN as the option
value.
Fixes 2 issues reported by coverity scan when converting
vdsm return value
GlusterAsyncTaskStatus.from((String)map.get(STATUS)).getJobExecutionStatus()
-- possible NPE
Change-Id: If8cd725af21639827ba19c5589fe2889e1c98c19
Signed-off-by: Sahina Bose <e470779b356412d02748affb76951ba845275668@redhat.com> | package org.ovirt.engine.core.common.asynctasks.gluster;
import org.ovirt.engine.core.common.job.JobExecutionStatus;
/**
* This enum represents the gluster volume async task status values returned from VDSM
*/
public enum GlusterAsyncTaskStatus {
COMPLETED("COMPLETED"),
STARTED("STARTED"),
STOPPED("STOPPED"),
FAILED("FAILED"),
UNKNOWN("UNKNOWN"),
NOT_STARTED("NOT STARTED")
;
private String statusMsg;
private GlusterAsyncTaskStatus(String status) {
statusMsg = status;
}
public String value() {
return statusMsg;
}
public static GlusterAsyncTaskStatus from(String status) {
for (GlusterAsyncTaskStatus taskStatus : values()) {
if (taskStatus.value().equalsIgnoreCase(status)) {
return taskStatus;
}
}
return GlusterAsyncTaskStatus.UNKNOWN;
}
public JobExecutionStatus getJobExecutionStatus() {
switch (this) {
case COMPLETED:
return JobExecutionStatus.FINISHED;
case STARTED:
return JobExecutionStatus.STARTED;
case STOPPED:
return JobExecutionStatus.ABORTED;
case FAILED:
return JobExecutionStatus.FAILED;
case UNKNOWN:
case NOT_STARTED:
default:
return JobExecutionStatus.UNKNOWN;
}
}
}
| package org.ovirt.engine.core.common.asynctasks.gluster;
import org.ovirt.engine.core.common.job.JobExecutionStatus;
/**
* This enum represents the gluster volume async task status values returned from VDSM
*/
public enum GlusterAsyncTaskStatus {
COMPLETED("COMPLETED"),
STARTED("STARTED"),
STOPPED("STOPPED"),
FAILED("FAILED"),
UNKNOWN("UNKNOWN"),
NOT_STARTED("NOT STARTED")
;
private String statusMsg;
private GlusterAsyncTaskStatus(String status) {
statusMsg = status;
}
public String value() {
return statusMsg;
}
public static GlusterAsyncTaskStatus from(String status) {
for (GlusterAsyncTaskStatus taskStatus : values()) {
if (taskStatus.value().equalsIgnoreCase(status)) {
return taskStatus;
}
}
return null;
}
public JobExecutionStatus getJobExecutionStatus() {
switch (this) {
case COMPLETED:
return JobExecutionStatus.FINISHED;
case STARTED:
return JobExecutionStatus.STARTED;
case STOPPED:
return JobExecutionStatus.ABORTED;
case FAILED:
return JobExecutionStatus.FAILED;
case UNKNOWN:
case NOT_STARTED:
default:
return JobExecutionStatus.UNKNOWN;
}
}
}
|
Highlight: Use lighter theme with good contrast. | // jscs:disable maximumLineLength
/**
* Highlight Module
*
*
* High Level API:
*
* api.init()
*
*
* Hooks To:
*
* 'document:loaded' ~> highlight.init();
*
*/
(function (global) {
function loadInitialScriptsAndStyles() {
var link =
document.createElement('link');
var mainScript =
document.createElement('script');
link.rel =
'stylesheet';
link.href =
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.5.0/styles/zenburn.min.css';
mainScript.src =
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.5.0/highlight.min.js';
// On main script load, configure marked
mainScript.addEventListener('load', function () {
marked.setOptions({
langPrefix: 'hljs lang-',
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
});
});
// Extend marked.js on edit page only
if ('marked' in global) {
document.body.appendChild(mainScript);
}
// Preview page requires scripts only
document.head.appendChild(link);
}
// High Level API
var api = {
init: function () {
loadInitialScriptsAndStyles();
},
};
// Hooks
if ('events' in global) {
events.subscribe('document:loaded', api.init);
}
}(window));
| // jscs:disable maximumLineLength
/**
* Highlight Module
*
*
* High Level API:
*
* api.init()
*
*
* Hooks To:
*
* 'document:loaded' ~> highlight.init();
*
*/
(function (global) {
function loadInitialScriptsAndStyles() {
var link =
document.createElement('link');
var mainScript =
document.createElement('script');
link.rel =
'stylesheet';
link.href =
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.5.0/styles/railscasts.min.css';
mainScript.src =
'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.5.0/highlight.min.js';
// On main script load, configure marked
mainScript.addEventListener('load', function () {
marked.setOptions({
langPrefix: 'hljs lang-',
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
});
});
// Extend marked.js on edit page only
if ('marked' in global) {
document.body.appendChild(mainScript);
}
// Preview page requires scripts only
document.head.appendChild(link);
}
// High Level API
var api = {
init: function () {
loadInitialScriptsAndStyles();
},
};
// Hooks
if ('events' in global) {
events.subscribe('document:loaded', api.init);
}
}(window));
|
Remove quotes from tests in normalizeArgs | import normalizeArgs, { __RewireAPI__ as rewireAPI } from '../../../src/server/process/normalizeArgs';
describe('normalizeArgs', () => {
afterEach(() => {
rewireAPI.__ResetDependency__('process');
});
it('should normalize for Windows with no COMSPEC', () => {
rewireAPI.__Rewire__('process', {
platform: 'win32',
env: {}
});
const result = normalizeArgs('echo Hello world');
expect(result).toEqual({
file: 'cmd.exe',
args: ['/s', '/c', 'echo Hello world'],
options: { windowsVerbatimArguments: true }
});
});
it('should normalize for Windows with COMSPEC defined', () => {
rewireAPI.__Rewire__('process', {
platform: 'win32',
env: { comspec: 'command.com' }
});
const result = normalizeArgs('echo Hello again');
expect(result).toEqual({
file: 'command.com',
args: ['/s', '/c', 'echo Hello again'],
options: { windowsVerbatimArguments: true }
});
});
it('should normalize for Unix-like systems', () => {
rewireAPI.__Rewire__('process', {
platform: 'darwin'
});
const result = normalizeArgs('echo Hello from the other side');
expect(result).toEqual({
file: '/bin/sh',
args: ['-c', 'echo Hello from the other side'],
options: {}
});
});
});
| import normalizeArgs, { __RewireAPI__ as rewireAPI } from '../../../src/server/process/normalizeArgs';
describe('normalizeArgs', () => {
afterEach(() => {
rewireAPI.__ResetDependency__('process');
});
it('should normalize for Windows with no COMSPEC', () => {
rewireAPI.__Rewire__('process', {
platform: 'win32',
env: {}
});
const result = normalizeArgs('echo Hello world');
expect(result).toEqual({
file: 'cmd.exe',
args: ['/s', '/c', '"echo Hello world"'],
options: { windowsVerbatimArguments: true }
});
});
it('should normalize for Windows with COMSPEC defined', () => {
rewireAPI.__Rewire__('process', {
platform: 'win32',
env: { comspec: 'command.com' }
});
const result = normalizeArgs('echo Hello again');
expect(result).toEqual({
file: 'command.com',
args: ['/s', '/c', '"echo Hello again"'],
options: { windowsVerbatimArguments: true }
});
});
it('should normalize for Unix-like systems', () => {
rewireAPI.__Rewire__('process', {
platform: 'darwin'
});
const result = normalizeArgs('echo Hello from the other side');
expect(result).toEqual({
file: '/bin/sh',
args: ['-c', 'echo Hello from the other side'],
options: {}
});
});
});
|
Fix for php notice error | <?php
namespace Luracast\Restler\Format;
/**
* Javascript Object Notation Packaged in a method (JSONP)
*
* @category Framework
* @package Restler
* @subpackage format
* @author R.Arul Kumaran <arul@luracast.com>
* @copyright 2010 Luracast
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://luracast.com/products/restler/
* @version 3.0.0rc4
*/
class JsFormat extends JsonFormat
{
const MIME = 'text/javascript';
const EXTENSION = 'js';
public static $callbackMethodName = 'parseResponse';
public static $callbackOverrideQueryString = 'callback';
public static $includeHeaders = true;
public function encode($data, $human_readable = false)
{
$r = array();
if (static::$includeHeaders) {
$r['meta'] = array();
foreach (headers_list() as $header) {
list($h, $v) = explode(': ', $header, 2);
$r['meta'][$h] = $v;
}
}
$r['data'] = $data;
if (isset($_GET[static::$callbackOverrideQueryString])) {
static::$callbackMethodName
= (string) $_GET[static::$callbackOverrideQueryString];
}
return static::$callbackMethodName . '('
. parent::encode($r, $human_readable) . ');';
}
}
| <?php
namespace Luracast\Restler\Format;
/**
* Javascript Object Notation Packaged in a method (JSONP)
*
* @category Framework
* @package Restler
* @subpackage format
* @author R.Arul Kumaran <arul@luracast.com>
* @copyright 2010 Luracast
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://luracast.com/products/restler/
* @version 3.0.0rc4
*/
class JsFormat extends JsonFormat
{
const MIME = 'text/javascript';
const EXTENSION = 'js';
public static $callbackMethodName = 'parseResponse';
public static $callbackOverrideQueryString = 'callback';
public static $includeHeaders = true;
public function encode($data, $human_readable = false)
{
$r = array();
if (static::$includeHeaders) {
$r['meta'] = array();
foreach (headers_list() as $header) {
list($h, $v) = explode(': ', $header, 2);
$r['meta'][$h] = $v;
}
}
$r['data'] = $data;
if ($_GET[static::$callbackOverrideQueryString]) {
static::$callbackMethodName
= $_GET[static::$callbackOverrideQueryString];
}
return static::$callbackMethodName . '('
. parent::encode($r, $human_readable) . ');';
}
}
|
Set $this->app to a variable so we can get the constants out | <?php
namespace Encore\Kernel;
class Timezone
{
public function __construct(Application $app, array $winTimezones)
{
$this->app = $app;
$this->timezones = $winTimezones;
}
public function set($timezone)
{
return date_default_timezone_set($timezone);
}
public function get()
{
return date_default_timezone_get();
}
public function setToSystem()
{
return $this->set($this->getSystemTimezone());
}
public function getSystemTimezone()
{
$app = $this->app;
if ($app->os() === $app::OS_WIN) {
return $this->getWindowsTimezone();
}
return $this->getUnitTimezone();
}
protected function getUnixTimezone()
{
return system('date +%Z');
}
protected function getWindowsTimezone()
{
$wmiObject = new COM("WinMgmts:\\\\.\\root\\cimv2");
$wmiObj = $wmiObject->ExecQuery("SELECT Bias FROM Win32_TimeZone");
foreach ($wmiObj as $objItem) {
$offset = $objItem->Bias;
break;
}
return array_key_exists($offset/60, $this->timezones) ? $this->timezones[$offset] : "UTC" ;
}
} | <?php
namespace Encore\Kernel;
class Timezone
{
public function __construct(Application $app, array $winTimezones)
{
$this->app = $app;
$this->timezones = $winTimezones;
}
public function set($timezone)
{
return date_default_timezone_set($timezone);
}
public function get()
{
return date_default_timezone_get();
}
public function setToSystem()
{
return $this->set($this->getSystemTimezone());
}
public function getSystemTimezone()
{
if ($this->app->os() === $this->app::OS_WIN) {
return $this->getWindowsTimezone();
}
return $this->getUnitTimezone();
}
protected function getUnixTimezone()
{
return system('date +%Z');
}
protected function getWindowsTimezone()
{
$wmiObject = new COM("WinMgmts:\\\\.\\root\\cimv2");
$wmiObj = $wmiObject->ExecQuery("SELECT Bias FROM Win32_TimeZone");
foreach ($wmiObj as $objItem) {
$offset = $objItem->Bias;
break;
}
return array_key_exists($offset/60, $this->timezones) ? $this->timezones[$offset] : "UTC" ;
}
} |
Make daphne serving thread idle better | import logging
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
logger = logging.getLogger(__name__)
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True, action_logger=None):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
self.action_logger = action_logger
def run(self):
self.factory = HTTPFactory(self.channel_layer, self.action_logger)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callLater(0, self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
channels = self.factory.reply_channels()
delay = 0.3
# Quit if reactor is stopping
if not reactor.running:
logging.debug("Backend reader quitting due to reactor stop")
return
# Don't do anything if there's no channels to listen on
if channels:
delay = 0.05
channel, message = self.channel_layer.receive_many(channels, block=False)
if channel:
delay = 0
logging.debug("Server got message on %s", channel)
# Deal with the message
self.factory.dispatch_reply(channel, message)
reactor.callLater(delay, self.backend_reader)
| import logging
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
logger = logging.getLogger(__name__)
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True, action_logger=None):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
self.action_logger = action_logger
def run(self):
self.factory = HTTPFactory(self.channel_layer, self.action_logger)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callLater(0, self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
logging.debug("Backend reader quitting due to reactor stop")
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=False)
if channel:
logging.debug("Server got message on %s", channel)
# Deal with the message
self.factory.dispatch_reply(channel, message)
reactor.callLater(0, self.backend_reader)
|
Load innovation story page based on QR code result |
var DiscoverView = function() {
this.initialize = function() {
// 'div' wrapper to attach html and events to
this.el = $('<div/>');
};
this.render = function() {
if (!this.homeView) {
this.homeView = { enteredName: "" }
}
var discover_view = DiscoverView.template(this.homeView));
this.el.html(discover);
this.scan();
return this;
};
this.scan = function() {
var self = this;
console.log('scan(): init');
// documentation said the syntax was this:
// var scanner = window.PhoneGap.require("cordova/plugin/BarcodeScanner");
// but playing with options, seems like it should be this:
//var scanner = window.cordova.require("cordova/plugin/BarcodeScanner");
if (!window.cordova) {
app.showAlert("Barcode Scanner not supported", "Error");
return;
}
cordova.plugins.barcodeScanner.scan(
function (result) {
var inner_template = Handlebars.compile($("#"+result.text_"-tpl").html());
var inner_html = inner_template(self.homeView));
$('#info-page').html(inner_html);
app.showAlert("Result: " + result.text + "\n"
+ "Format: " + result.format + "\n"
+ "Cancelled: " + result.cancelled,
"We got a barcode");
},
function (error) {
app.showAlert(err,"Scanning failed: ");
}
);
};
this.initialize();
}
DiscoverView.template = Handlebars.compile($("#discover-tpl").html());
|
var DiscoverView = function() {
this.initialize = function() {
// 'div' wrapper to attach html and events to
this.el = $('<div/>');
};
this.render = function() {
if (!this.homeView) {
this.homeView = { enteredName: "" }
}
this.el.html(DiscoverView.template(this.homeView));
this.scan();
return this;
};
this.scan = function() {
console.log('scan(): init');
// documentation said the syntax was this:
// var scanner = window.PhoneGap.require("cordova/plugin/BarcodeScanner");
// but playing with options, seems like it should be this:
//var scanner = window.cordova.require("cordova/plugin/BarcodeScanner");
if (!window.cordova) {
app.showAlert("Barcode Scanner not supported", "Error");
return;
}
cordova.plugins.barcodeScanner.scan(
function (result) {
app.showAlert("Result: " + result.text + "\n"
+ "Format: " + result.format + "\n"
+ "Cancelled: " + result.cancelled,
"We got a barcode");
},
function (error) {
app.showAlert(err,"Scanning failed: ");
}
);
};
this.initialize();
}
DiscoverView.template = Handlebars.compile($("#discover-tpl").html());
|
Use defs instead of symbol in SVG sprite | import fs from 'fs';
import glob from 'glob';
import path from 'path';
import SVGSprite from 'svg-sprite';
import vinyl from 'vinyl';
function SVGCompilerPlugin(options) {
this.options = {baseDir: path.resolve(options.baseDir)};
}
SVGCompilerPlugin.prototype.apply = function(compiler) {
var baseDir = this.options.baseDir;
compiler.plugin('emit', function(compilation, callback) {
let content = null;
let files = glob.sync('**/*.svg', {cwd: baseDir});
let svgSpriter = new SVGSprite({
mode: {
defs: true
},
shape: {
id: {
separator: '--'
}
}
});
files.forEach(function (file) {
svgSpriter.add(new vinyl({
path: path.join(baseDir, file),
base: baseDir,
contents: fs.readFileSync(path.join(baseDir, file))
}));
});
svgSpriter.compile(function (error, result, data) {
content = result.defs.sprite.contents.toString();
});
// Insert this list into the Webpack build as a new file asset:
compilation.assets['sprite.svg'] = {
source: function() {
return content;
},
size: function() {
return content.length;
}
};
callback();
});
};
module.exports = SVGCompilerPlugin;
| import fs from 'fs';
import glob from 'glob';
import path from 'path';
import SVGSprite from 'svg-sprite';
import vinyl from 'vinyl';
function SVGCompilerPlugin(options) {
this.options = {baseDir: path.resolve(options.baseDir)};
}
SVGCompilerPlugin.prototype.apply = function(compiler) {
var baseDir = this.options.baseDir;
compiler.plugin('emit', function(compilation, callback) {
let content = null;
let files = glob.sync('**/*.svg', {cwd: baseDir});
let svgSpriter = new SVGSprite({
mode: {
symbol: true
},
shape: {
id: {
separator: '--'
}
}
});
files.forEach(function (file) {
svgSpriter.add(new vinyl({
path: path.join(baseDir, file),
base: baseDir,
contents: fs.readFileSync(path.join(baseDir, file))
}));
});
svgSpriter.compile(function (error, result, data) {
content = result.symbol.sprite.contents.toString();
});
// Insert this list into the Webpack build as a new file asset:
compilation.assets['sprite.svg'] = {
source: function() {
return content;
},
size: function() {
return content.length;
}
};
callback();
});
};
module.exports = SVGCompilerPlugin;
|
Remove Registration form name so the name does not form part of the register JSON request body. | <?php
namespace Ice\ExternalUserBundle\Form\Type;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// parent::buildForm($builder, $options);
$builder
->add('plainPassword', 'password', array(
'description' => 'Plain text password. Encoded before new user is persisted.',
))
->add('email', 'email', array(
'description' => 'Email address. Must be unique.',
))
->add('title', 'text', array(
'description' => 'Salutation.',
))
->add('firstNames', 'text', array(
'description' => 'First name(s).',
))
->add('lastName', 'text', array(
'description' => 'Last name.',
))
->add('dob', 'date', array(
'widget' => 'single_text',
'description' => 'Date of birth.',
'required' => false,
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ice\ExternalUserBundle\Entity\User',
'csrf_protection' => false,
'validation_groups' => array('rest_register'),
));
}
public function getName()
{
return '';
}
}
| <?php
namespace Ice\ExternalUserBundle\Form\Type;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// parent::buildForm($builder, $options);
$builder
->add('plainPassword', 'password', array(
'description' => 'Plain text password. Encoded before new user is persisted.',
))
->add('email', 'email', array(
'description' => 'Email address. Must be unique.',
))
->add('title', 'text', array(
'description' => 'Salutation.',
))
->add('firstNames', 'text', array(
'description' => 'First name(s).',
))
->add('lastName', 'text', array(
'description' => 'Last name.',
))
->add('dob', 'date', array(
'widget' => 'single_text',
'description' => 'Date of birth.',
'required' => false,
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ice\ExternalUserBundle\Entity\User',
'csrf_protection' => false,
'validation_groups' => array('rest_register'),
));
}
public function getName()
{
return 'register';
}
}
|
Update UI tests for the `SearchCommand` | package jfdi.test.ui;
import static org.junit.Assert.assertEquals;
import jfdi.ui.Constants;
public class TestSearch extends UiTest {
TestSearch(TestMain main) {
super(main);
}
@Override
void run() {
testSingleSearchDone();
testMultipleSearchDone();
}
/*
* Test a simple "search" command with one single keyword
*/
public void testSingleSearchDone() {
main.addTask("test 1");
main.addTask("testing 2");
main.addTask("test 3");
main.addTask("testing 4");
main.addTask("test 2");
main.addTask("testing 3");
main.addTask("test 4");
main.execute("search test");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_1, "[test]"));
assertEquals(4, main.getImportantListSize());
}
/*
* Test a simple "search" command with multiple keywords
*/
public void testMultipleSearchDone() {
main.execute("search testing 2");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_2, "2 and testing"));
assertEquals(4, main.getImportantListSize());
main.execute("search test testing 2");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_2, "2, test and testing"));
assertEquals(7, main.getImportantListSize());
}
}
| package jfdi.test.ui;
import static org.junit.Assert.assertEquals;
import jfdi.ui.Constants;
public class TestSearch extends UiTest {
TestSearch(TestMain main) {
super(main);
}
@Override
void run() {
testSingleSearchDone();
testMultipleSearchDone();
}
/*
* Test a simple "search" command with one single keyword
*/
public void testSingleSearchDone() {
main.addTask("test 1");
main.addTask("testing 2");
main.addTask("test 3");
main.addTask("testing 4");
main.addTask("test 2");
main.addTask("testing 3");
main.addTask("test 4");
main.execute("search test");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_1, "[test]"));
assertEquals(4, main.getImportantListSize());
}
/*
* Test a simple "search" command with multiple keywords
*/
public void testMultipleSearchDone() {
main.execute("search testing 2");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_2, "2 and testing"));
assertEquals(1, main.getImportantListSize());
main.execute("search test testing 2");
main.assertResponseMessage(String.format(Constants.CMD_SUCCESS_SEARCH_2, "2, test and testing"));
assertEquals(0, main.getImportantListSize());
}
}
|
Revert back to version number | #!/usr/bin/env python
import subprocess
from setuptools import setup, find_packages
import os
def git_version():
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
out = subprocess.Popen(
cmd, stdout=subprocess.PIPE, env=env).communicate()[0]
return out
try:
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
GIT_REVISION = out.strip().decode('ascii')
except OSError:
GIT_REVISION = ""
return GIT_REVISION
def getVersion(version, release=True):
if os.path.exists('.git'):
_git_version = git_version()[:7]
else:
_git_version = ''
if release:
return version
else:
return version + '-dev.' + _git_version
setup(name='pymks',
version=getVersion('0.3.1', release=True),
description='Materials Knowledge Systems in Python (PyMKS)',
author='David Brough, Daniel Wheeler',
author_email='david.brough.0416@gmail.com',
url='http://pymks.org',
packages=find_packages(),
package_data={'': ['tests/*.py']},
)
| #!/usr/bin/env python
import subprocess
from setuptools import setup, find_packages
import os
def git_version():
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
out = subprocess.Popen(
cmd, stdout=subprocess.PIPE, env=env).communicate()[0]
return out
try:
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
GIT_REVISION = out.strip().decode('ascii')
except OSError:
GIT_REVISION = ""
return GIT_REVISION
def getVersion(version, release=True):
if os.path.exists('.git'):
_git_version = git_version()[:7]
else:
_git_version = ''
if release:
return version
else:
return version + '-dev.' + _git_version
setup(name='pymks',
version=getVersion('0.3.2', release=False),
description='Materials Knowledge Systems in Python (PyMKS)',
author='David Brough, Daniel Wheeler',
author_email='david.brough.0416@gmail.com',
url='http://pymks.org',
packages=find_packages(),
package_data={'': ['tests/*.py']},
)
|
Subsets and Splits