text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add chardet as a dependency | from setuptools import setup
import os
import imbox
version = imbox.__version__
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='imbox',
version=version,
description="Python IMAP for Human beings",
long_description=read('README.rst'),
keywords='email, IMAP, parsing emails',
author='Martin Rusev',
author_email='martin@amon.cx',
url='https://github.com/martinrusev/imbox',
license='MIT',
packages=['imbox', 'imbox.vendors'],
package_dir={'imbox': 'imbox'},
install_requires=[
'chardet',
],
zip_safe=False,
classifiers=(
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
),
test_suite='tests',
)
| from setuptools import setup
import os
import imbox
version = imbox.__version__
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='imbox',
version=version,
description="Python IMAP for Human beings",
long_description=read('README.rst'),
keywords='email, IMAP, parsing emails',
author='Martin Rusev',
author_email='martin@amon.cx',
url='https://github.com/martinrusev/imbox',
license='MIT',
packages=['imbox', 'imbox.vendors'],
package_dir={'imbox': 'imbox'},
zip_safe=False,
classifiers=(
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
),
test_suite='tests',
)
|
Use the test client to check all templates for correctness | from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_inherits_from_base_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'rotd/base.html')
def test_home_page_uses_correct_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'recipes/home.html')
def test_home_page_has_recipe(self):
Recipe.objects.create(name='test')
response = self.client.get('/')
self.assertIsInstance(response.context['recipe'], Recipe)
def test_home_page_shows_any_recipe_name(self):
Recipe.objects.create(name='test recipe')
request = HttpRequest()
response = home_page(request).content.decode()
self.assertTrue(any([(recipe.name in response)
for recipe in Recipe.objects.all()]))
| from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_inherits_from_base_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'rotd/base.html')
def test_home_page_uses_correct_template(self):
request = HttpRequest()
response = home_page(request)
expected = render_to_string('recipes/home.html')
self.assertEqual(response.content.decode(), expected)
def test_home_page_has_recipe(self):
Recipe.objects.create(name='test')
response = self.client.get('/')
self.assertIsInstance(response.context['recipe'], Recipe)
def test_home_page_shows_any_recipe_name(self):
Recipe.objects.create(name='test recipe')
request = HttpRequest()
response = home_page(request).content.decode()
self.assertTrue(any([(recipe.name in response)
for recipe in Recipe.objects.all()]))
|
Correct admin lookup layers for Geonames
The API label code expects that any record has admin lookup fields up to
and including the layer of the record itself. For example, regions
should have the region and region_a fields filled in by admin lookup. | /* Look up which admin fields should be populated for a record in a given layer.
*
* The logic is: look up eveything above in the WOF heirarchy, ignoring things like
* 'dependency'
*
* Note: this filtering really only matters for geonames currently, since OSM and OA
* consist entirely of venue and address records, which should have all fields
* looked up. WOF documents use the actual WOF heirarchy to fill in admin values,
* so they also won't be affected by this.
*/
function getAdminLayers(layer) {
switch (layer) {
case 'region':
return ['country', 'macroregion', 'region'];
case 'county':
return ['country', 'macroregion', 'region', 'macrocounty', 'county'];
case 'locality':
return ['country', 'macroregion', 'region', 'macrocounty', 'county', 'locality'];
default:
return undefined;//undefined means use all layers as normal
}
}
module.exports = getAdminLayers;
| /* Look up which admin fields should be populated for a record in a given layer.
*
* The logic is: look up eveything above in the WOF heirarchy, ignoring things like
* 'dependency'
*
* Note: this filtering really only matters for geonames currently, since OSM and OA
* consist entirely of venue and address records, which should have all fields
* looked up. WOF documents use the actual WOF heirarchy to fill in admin values,
* so they also won't be affected by this.
*/
function getAdminLayers(layer) {
switch (layer) {
case 'region':
return ['country', 'macroregion'];
case 'county':
return ['country', 'macroregion', 'region', 'macrocounty'];
case 'locality':
return ['country', 'macroregion', 'region', 'macrocounty', 'county'];
default:
return undefined;//undefined means use all layers as normal
}
}
module.exports = getAdminLayers;
|
Return the map as an object with a descriptive key. | const util = require('util');
const express = require('express');
const app = express();
const router = express.Router();
const Config = require('./Config');
class WebInterface {
constructor(state) {
this.state = state;
this.port = Config.get('webPort') || 9000;
}
init() {
util.log("this.state.PlayerManager.players", this.state.PlayerManager.players);
// Routes for the API's GET response.
router.get('/', (req, res) => res.json(this.state));
router.get('/npcs', (req, res) => res.json({ npcs: this.state.MobFactory }));
router.get('/players', (req, res) => res.json({ players: this.state.PlayerManager.players }));
router.get('/items', (req, res) => res.json({ items: this.state.ItemManager.items }));
router.get('/rooms', (req, res) => res.json({ rooms: this.state.RoomManager.rooms }));
router.get('/help', (req, res) => res.json({ help: this.state.HelpManager.helps }));
app.use('/api', router);
app.listen(this.port);
util.log(`WEB: Web API activated and running on port ${this.port}.`);
}
}
module.exports = WebInterface; | const util = require('util');
const express = require('express');
const app = express();
const router = express.Router();
const Config = require('./Config');
class WebInterface {
constructor(state) {
this.state = state;
this.port = Config.get('webPort') || 9000;
}
init() {
// Routes for the API's GET response.
router.get('/', (req, res) => res.json(this.state));
router.get('/npcs', (req, res) => res.json(this.state.MobFactory.npcs));
router.get('/players', (req, res) => res.json(this.state.PlayerManager.players));
router.get('/items', (req, res) => res.json(this.state.ItemManager.items));
router.get('/rooms', (req, res) => res.json(this.state.RoomManager.rooms));
router.get('/help', (req, res) => res.json(this.state.HelpManager.helps));
app.use('/api', router);
app.listen(this.port);
util.log(`WEB: Web API activated and running on port ${this.port}.`);
}
}
module.exports = WebInterface; |
Read doc version number from _metadata.py |
def _getvar(var, path, default=None):
with open(path) as f:
for line in f:
if var in line and "=" in line and "__all__" not in line:
g = {}
l = {}
exec line in g, l
return l[var]
return default
def _version():
import os
return _getvar("__version__", os.path.join(os.path.dirname(__file__),
"../../_metadata.py"),
"X.X")
def _repo():
return "staging"
version = _version()
repo = _repo()
install = "https://packagecloud.io/datawire/%s/install" % repo
script_rpm = "https://packagecloud.io/install/repositories/datawire/%s/script.rpm.sh" % repo
script_deb = "https://packagecloud.io/install/repositories/datawire/%s/script.deb.sh" % repo
|
def _getvar(var, path, default=None):
with open(path) as f:
for line in f:
if var in line:
g = {}
l = {}
exec line in g, l
return l[var]
return default
def _version():
import os
return _getvar("__version__", os.path.join(os.path.dirname(__file__),
"../../setup.py"),
"X.X")
def _repo():
return "staging"
version = _version()
repo = _repo()
install = "https://packagecloud.io/datawire/%s/install" % repo
script_rpm = "https://packagecloud.io/install/repositories/datawire/%s/script.rpm.sh" % repo
script_deb = "https://packagecloud.io/install/repositories/datawire/%s/script.deb.sh" % repo
|
Use redux compose with devToolsEnhancer | // @flow
/* eslint-disable arrow-body-style */
import { applyMiddleware, createStore, compose } from 'redux'
import { createEpicMiddleware } from 'redux-observable'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise-middleware'
import { routerMiddleware } from 'react-router-redux'
import { devToolsEnhancer } from 'redux-devtools-extension/logOnlyInProduction'
import rootEpic from './epics'
import rootReducer from './modules'
function configureStore (
preloadedState: Object, history: Object,
): Object {
const epicMiddleware = createEpicMiddleware(rootEpic)
const middleware = [
epicMiddleware,
thunk,
promiseMiddleware(),
routerMiddleware(history),
]
// only log redux actions in development
if (process.env.NODE_ENV === 'development') {
// logger needs to be last
// uncomment if needed
// middleware.push(require('redux-logger').createLogger())
}
// https://github.com/zalmoxisus/redux-devtools-extension
// https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f
const enhancer = compose(
applyMiddleware(...middleware),
devToolsEnhancer()
)
const store = createStore(rootReducer, preloadedState, enhancer)
return store
}
export default configureStore
| // @flow
/* eslint-disable arrow-body-style */
import { applyMiddleware, createStore } from 'redux'
import { createEpicMiddleware } from 'redux-observable'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise-middleware'
import { routerMiddleware } from 'react-router-redux'
import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction'
import rootEpic from './epics'
import rootReducer from './modules'
function configureStore (
preloadedState: Object, history: Object,
): Object {
const epicMiddleware = createEpicMiddleware(rootEpic)
const middleware = [
epicMiddleware,
thunk,
promiseMiddleware(),
routerMiddleware(history),
]
// only log redux actions in development
if (process.env.NODE_ENV === 'development') {
// logger needs to be last
// uncomment if needed
// middleware.push(require('redux-logger').createLogger())
}
// https://github.com/zalmoxisus/redux-devtools-extension
// https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f
const enhancer = composeWithDevTools(
applyMiddleware(...middleware)
)
const store = createStore(rootReducer, preloadedState, enhancer)
return store
}
export default configureStore
|
Add editable option to the timeline | /* global Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 600000,
editable: {
add: false,
updateTime: true,
updateGroup: false,
remove: true
}
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); | /* global Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 600000,
editable: true
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); |
Change data access script to issue SELECTs that actually return a value
This makes the part about tracing the SQL statements and tracing the
number of rows returned a little more interesting. | #!/usr/bin/env python
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
| #!/usr/bin/env python
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, 10000):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%1417773'")
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
|
Create new users with createdAt and loginAt props |
var config = require('tresdb-config');
var db = require('tresdb-db');
var bcrypt = require('bcryptjs');
exports.createUser = function (username, email, password, callback) {
// Create non-admin active user. Does not check if user exists.
//
// Parameters:
// username
// string
// email
// string
// password
// string
// callback
// function (err)
var users = db.collection('users');
var r = config.bcrypt.rounds;
bcrypt.hash(password, r, function (berr, pwdHash) {
if (berr) {
return callback(berr);
}
users.insert({
name: username,
email: email,
hash: pwdHash,
admin: false,
status: 'active', // options. 'active' | 'deactivated',
createdAt: (new Date()).toISOString(),
loginAt: (new Date()).toISOString(),
}, function (qerr) {
if (qerr) {
return callback(qerr);
}
// User inserted successfully
return callback();
});
});
};
|
var config = require('tresdb-config');
var db = require('tresdb-db');
var bcrypt = require('bcryptjs');
exports.createUser = function (username, email, password, callback) {
// Create non-admin active user. Does not check if user exists.
//
// Parameters:
// username
// string
// email
// string
// password
// string
// callback
// function (err)
var users = db.collection('users');
var r = config.bcrypt.rounds;
bcrypt.hash(password, r, function (berr, pwdHash) {
if (berr) {
return callback(berr);
}
users.insert({
name: username,
email: email,
hash: pwdHash,
admin: false,
status: 'active', // 'deactivated'
}, function (qerr) {
if (qerr) {
return callback(qerr);
}
// User inserted successfully
return callback();
});
});
};
|
Revert "Mock ActiveContainerStatistics as its constructor is package-private"
This reverts commit fa682ab2d9f18204c4c9018506104f0ba3744136. | // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
import com.yahoo.jdisc.core.ActiveContainerStatistics;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertTrue;
public class MetricUpdaterTest {
@Test
public void testFreeMemory() throws InterruptedException {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricProvider provider = MetricProviders.newInstance(consumer);
Metric metric = provider.get();
MetricUpdater updater = new MetricUpdater(metric, new ActiveContainerStatistics(), 10);
long start = System.currentTimeMillis();
boolean updated = false;
while (System.currentTimeMillis() - start < 60000 && !updated) {
Thread.sleep(10);
if (memoryMetricsUpdated(updater)) {
updated = true;
}
}
assertTrue(memoryMetricsUpdated(updater));
}
private boolean memoryMetricsUpdated(MetricUpdater updater) {
return updater.getFreeMemory()>0 && updater.getTotalMemory()>0;
}
}
| // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
import com.yahoo.jdisc.core.ActiveContainerStatistics;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertTrue;
public class MetricUpdaterTest {
@Test
public void testFreeMemory() throws InterruptedException {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricProvider provider = MetricProviders.newInstance(consumer);
Metric metric = provider.get();
MetricUpdater updater = new MetricUpdater(metric, Mockito.mock(ActiveContainerStatistics.class), 10);
long start = System.currentTimeMillis();
boolean updated = false;
while (System.currentTimeMillis() - start < 60000 && !updated) {
Thread.sleep(10);
if (memoryMetricsUpdated(updater)) {
updated = true;
}
}
assertTrue(memoryMetricsUpdated(updater));
}
private boolean memoryMetricsUpdated(MetricUpdater updater) {
return updater.getFreeMemory()>0 && updater.getTotalMemory()>0;
}
}
|
Add the ModelComponentSets to the number of subcomponents. | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printComponentsMatching(self):
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
self.assertEquals(num_matches, 144)
def test_attachGeometry_memory_management(self):
model = osim.Model()
model.getGround().attachGeometry(osim.Sphere(1.5))
| import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printComponentsMatching(self):
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
self.assertEquals(num_matches, 126)
def test_attachGeometry_memory_management(self):
model = osim.Model()
model.getGround().attachGeometry(osim.Sphere(1.5))
|
Fix weird distutils.log reloading/caching situation
For some reason `distutils.log` module is getting cached in `distutils.dist`
and then loaded again when we have the opportunity to patch it.
This implies: id(distutils.log) != id(distutils.dist.log).
We need to make sure the same module object is used everywhere. | import sys
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibilty with distutils.log but may change in
the future.
"""
err_handler = logging.StreamHandler()
err_handler.setLevel(logging.WARNING)
out_handler = logging.StreamHandler(sys.stdout)
out_handler.addFilter(_not_warning)
handlers = err_handler, out_handler
logging.basicConfig(
format="{message}", style='{', handlers=handlers, level=logging.DEBUG)
monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
# For some reason `distutils.log` module is getting cached in `distutils.dist`
# and then loaded again when we have the opportunity to patch it.
# This implies: id(distutils.log) != id(distutils.dist.log).
# We need to make sure the same module object is used everywhere:
distutils.dist.log = distutils.log
def set_threshold(level):
logging.root.setLevel(level*10)
return set_threshold.unpatched(level)
| import sys
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibilty with distutils.log but may change in
the future.
"""
err_handler = logging.StreamHandler()
err_handler.setLevel(logging.WARNING)
out_handler = logging.StreamHandler(sys.stdout)
out_handler.addFilter(_not_warning)
handlers = err_handler, out_handler
logging.basicConfig(
format="{message}", style='{', handlers=handlers, level=logging.DEBUG)
monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
def set_threshold(level):
logging.root.setLevel(level*10)
return set_threshold.unpatched(level)
|
Fix typo in 'job not found message' and jobs list output code | from django.core.management.base import BaseCommand
from django_schedulermanager.manager import manager
class Command(BaseCommand):
help = 'Schedules a job'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('jobs_name', nargs='+')
def handle(self, *args, **options):
jobs_to_schedule = options['jobs_name']
for job in jobs_to_schedule:
if job not in manager:
self.stdout.write(
'Unable to find job {}. Available jobs: {}'.format(job, ','.join(manager.jobs.keys()))
)
continue
if manager.is_scheduled(job):
self.stdout.write('Job {} already started'.format(job))
continue
job_options = manager.get_options(job)
# TODO: Implement settings override
manager.schedule(job, job_options)
self.stdout.write(self.style.SUCCESS('Successfully scheduled job {}!'.format(job)))
| from django.core.management.base import BaseCommand
from django_schedulermanager.manager import manager
class Command(BaseCommand):
help = 'Schedules a job'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('jobs_name', nargs='+')
def handle(self, *args, **options):
jobs_to_schedule = options['jobs_name']
for job in jobs_to_schedule:
if job not in manager:
self.stdout.write(
'Unable to find job {}. Avalable jobs: {}'.format(job, ','.join([job for job, _ in manager.jobs.items()]))
)
continue
if manager.is_scheduled(job):
self.stdout.write('Job {} already started'.format(job))
continue
job_options = manager.get_options(job)
# TODO: Implement settings override
manager.schedule(job, job_options)
self.stdout.write(self.style.SUCCESS('Successfully scheduled job {}!'.format(job)))
|
Allow half and combined plats to show up in list builder | #!/usr/bin/env python3
from ftplib import FTP
import re
excluded = [x.strip() for x in open('bad-zip-names.txt').readlines()]
counties = [x.strip() for x in open('counties.txt').readlines()]
conn = FTP('ftp.lmic.state.mn.us')
conn.login()
filter_regex = re.compile('.*[fh][ic]0.\.zip')
for county in counties:
print(county)
conn.cwd('/pub/data/basemaps/glo/{county}/Georeferenced/'.format(county=county))
zips = [x for x in conn.nlst() if x.endswith('.zip')]
fizips = [x for x in zips if filter_regex.match(x)]
final = [x for x in fizips if x not in excluded]
with open('counties/{county}.txt'.format(county=county), 'wt') as out:
for x in final:
out.write(x + '\n')
| #!/usr/bin/env python3
from ftplib import FTP
import re
excluded = [x.strip() for x in open('bad-zip-names.txt').readlines()]
counties = [x.strip() for x in open('counties.txt').readlines()]
conn = FTP('ftp.lmic.state.mn.us')
conn.login()
filter_regex = re.compile('.*fi0.\.zip')
for county in counties:
print(county)
conn.cwd('/pub/data/basemaps/glo/{county}/Georeferenced/'.format(county=county))
zips = [x for x in conn.nlst() if x.endswith('.zip')]
fizips = [x for x in zips if filter_regex.match(x)]
final = [x for x in fizips if x not in excluded]
with open('counties/{county}.txt'.format(county=county), 'wt') as out:
for x in final:
out.write(x + '\n')
|
Add helper to get translated configuration values
This will be used to get the proper translation for configuration values
like:
- Title
- Subtitle
- Description
This translations should be located in the `_data` folder of the Hexo
site, in files named like `config_<lang>.yml`.
Built from affa6376e67ab427d3294cf1e068b6d5ce303366. | var _ = require('lodash');
var regexCache = {
post: {}
};
hexo.extend.helper.register('is_post', function() {
var permalink = this.config.permalink;
var r = regexCache.post[permalink];
if (!r) {
var rUrl = permalink
.replace(':lang', '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*')
.replace(':id', '\\d+')
.replace(':category', '(\\w+\\/?)+')
.replace(':year', '\\d{4}')
.replace(/:(month|day)/g, '\\d{2}')
.replace(/:i_(month|day)/g, '\\d{1,2}')
.replace(/:title/, '[^\\/]+');
r = regexCache.post[permalink] = new RegExp(rUrl);
}
return r.test(this.path);
});
hexo.extend.helper.register('get_categories_for_lang', function(lang) {
var result = [];
_.each(this.site.data.categories, function(category, title) {
_.each(category, function(data, categoryLang) {
if (lang == categoryLang) {
result = result.concat({
title: data.name,
path: lang + '/' + data.slug
});
}
});
});
return result;
});
hexo.extend.helper.register('_c', function(string) {
return this.site.data['config_' + this.page.lang][string] || this.config[string];
});
| var _ = require('lodash');
var regexCache = {
post: {}
};
hexo.extend.helper.register('is_post', function() {
var permalink = this.config.permalink;
var r = regexCache.post[permalink];
if (!r) {
var rUrl = permalink
.replace(':lang', '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*')
.replace(':id', '\\d+')
.replace(':category', '(\\w+\\/?)+')
.replace(':year', '\\d{4}')
.replace(/:(month|day)/g, '\\d{2}')
.replace(/:i_(month|day)/g, '\\d{1,2}')
.replace(/:title/, '[^\\/]+');
r = regexCache.post[permalink] = new RegExp(rUrl);
}
return r.test(this.path);
});
hexo.extend.helper.register('get_categories_for_lang', function(lang) {
var result = [];
_.each(this.site.data.categories, function(category, title) {
_.each(category, function(data, categoryLang) {
if (lang == categoryLang) {
result = result.concat({
title: data.name,
path: lang + '/' + data.slug
});
}
});
});
return result;
});
|
Make configured email verification window available as service | <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupMiddleware\MiddlewareBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class SurfnetStepupMiddlewareMiddlewareExtension extends Extension
{
public function load(array $config, ContainerBuilder $container)
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), $config);
$definition = (new Definition())
->setClass('Surfnet\Stepup\Identity\Value\EmailVerificationWindow')
->setFactory('Surfnet\Stepup\Identity\Value\EmailVerificationWindow::fromSeconds')
->setArguments([$config['email_verification_window']]);
$container->setDefinition('identity.config.email_validation_window', $definition);
}
}
| <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupMiddleware\MiddlewareBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class SurfnetStepupMiddlewareMiddlewareExtension extends Extension
{
public function load(array $config, ContainerBuilder $container)
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), $config);
$container->setParameter('middleware.config.email_validation_window', $config['email_verification_window']);
}
}
|
Add disable and enable function. Refactor code. | import './sal.scss';
let options = {
rootMargin: '0px',
threshold: 0,
animateClassName: 'sal-animate',
selector: '[data-sal]',
disableFor: null,
};
let elements = [];
let intersectionObserver = null;
const animate = element => (
element.classList.add(options.animateClassName)
);
const isAnimated = element => (
element.classList.contains(options.animateClassName)
);
const onIntersection = (entries, observer) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
observer.unobserve(entry.target);
animate(entry.target);
}
});
};
const disable = () => {
intersectionObserver.disconnect();
intersectionObserver = null;
};
const enable = () => {
intersectionObserver = new IntersectionObserver(onIntersection, {
rootMargin: options.rootMargin,
threshold: options.threshold,
});
elements = [].filter.call(
document.querySelectorAll(options.selector),
element => !isAnimated(element, options.animateClassName),
);
elements.forEach(element => intersectionObserver.observe(element));
};
const init = (settings = options) => {
if (settings !== options) {
options = {
...options,
...settings,
};
}
if (!options.disableFor) {
enable();
}
return {
elements,
disable,
enable,
};
};
export default init;
| import './sal.scss';
const SELECTOR = '[data-sal]';
let options = {
rootMargin: '0px',
threshold: 0,
animateClassName: 'sal-animate',
};
let elements = [];
let intersectionObserver = null;
let initialized = false;
const animate = element => (
element.classList.add(options.animateClassName)
);
const isAnimated = element => (
element.classList.contains(options.animateClassName)
);
const onIntersection = (entries, observer) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
observer.unobserve(entry.target);
animate(entry.target);
}
});
};
export default function (settings = options) {
if (settings !== options) {
options = {
...options,
...settings,
};
}
if (!window.IntersectionObserver) {
throw Error(`
Your browser does not support IntersectionObserver!
Get a polyfill from here:
https://github.com/w3c/IntersectionObserver/tree/master/polyfill
`);
}
intersectionObserver = new IntersectionObserver(onIntersection, {
rootMargin: options.rootMargin,
threshold: options.threshold,
});
elements = [].filter.call(
document.querySelectorAll(SELECTOR),
element => !isAnimated(element, options.animateClassName),
);
elements.forEach(element => intersectionObserver.observe(element));
initialized = true;
return {
isInitialized: initialized,
};
}
|
Change team key to use only new [side]_team_key, add extra checks | import React from 'react'
import GameCard from './GameCard'
import { simpleFilter } from '../../lib/filter'
import { searchByAll } from '../../lib/search'
export default (props) => {
const userId = props.userId
const isAdmin = props.isAdmin || false
const teams = props.teams
let games = []
const gamesObj = props.games
const filterObj = props.filter || {}
const searchField = props.search || ''
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game.ownedByCurrentUser = game.owner_id === userId
games.push(game)
}
games = simpleFilter(games, filterObj)
games = searchByAll(games, searchField)
const fetchingGames = props.fetchingGames
const deleteGame = props.deleteGame
return (
<div className='games'>
{!fetchingGames
? (games.length
? games.map((game, key) => <GameCard key={key} game={game} deleteGame={deleteGame} isAdmin={isAdmin}
homeTeam={teams[game.home_team_key] && teams[game.home_team_key].name || "Can't find team"}
awayTeam={teams[game.away_team_key] && teams[game.away_team_key].name || "Can't find team"} />)
: <h3>No Games Found</h3>)
: <h3>Loading Games...</h3>
}
</div>
)
}
| import React from 'react'
import GameCard from './GameCard'
import { simpleFilter } from '../../lib/filter'
import { searchByAll } from '../../lib/search'
export default (props) => {
const userId = props.userId
const isAdmin = props.isAdmin || false
const teams = props.teams
let games = []
const gamesObj = props.games
const filterObj = props.filter || {}
const searchField = props.search || ''
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game.ownedByCurrentUser = game.owner_id === userId
games.push(game)
}
games = simpleFilter(games, filterObj)
games = searchByAll(games, searchField)
const fetchingGames = props.fetchingGames
const deleteGame = props.deleteGame
return (
<div className='games'>
{!fetchingGames
? (games.length
? games.map((game, key) => <GameCard key={key} game={game} deleteGame={deleteGame} isAdmin={isAdmin}
homeTeam={teams[game.home_team_key || game.home_team.key || game.home_team].name || "Can't find team"}
awayTeam={teams[game.away_team_key || game.away_team.key || game.away_team].name || "Can't find team"} />)
: <h3>No Games Found</h3>)
: <h3>Loading Games...</h3>
}
</div>
)
}
|
Add title and company columns to seeds file | 'use strict';
exports.seed = function(knex) {
return knex('contacts').del()
.then(() => {
return knex('contacts').insert([{
id: 1,
first_name: 'Bobby',
last_name: 'Kennedy',
email: 'admin@workflow.com',
phone: '5555555555',
title: 'President and CEO',
company: 'ABC Company',
linked_in_url: 'https://www.linkedin.com/in/bobby-joe-kennedy-40b5b0a2',
user_id: 1,
created_at: new Date('2016-08-13 11:14:00 UTC'),
updated_at: new Date('2016-08-13 11:14:00 UTC')
}]);
})
.then(() => {
return knex.raw(
"SELECT setval('contacts_id_seq', (SELECT MAX(id) FROM contacts));"
);
});
};
| 'use strict';
exports.seed = function(knex) {
return knex('contacts').del()
.then(() => {
return knex('contacts').insert([{
id: 1,
first_name: 'bobby',
last_name: 'kennedy',
email: 'admin@workflow.com',
phone: '5555555555',
linked_in_url: 'https://www.linkedin.com/in/bobby-joe-kennedy-40b5b0a2',
user_id: 1,
created_at: new Date('2016-08-13 11:14:00 UTC'),
updated_at: new Date('2016-08-13 11:14:00 UTC')
}]);
})
.then(() => {
return knex.raw(
"SELECT setval('contacts_id_seq', (SELECT MAX(id) FROM contacts));"
);
});
};
|
tests/instance-initializer-addon: Use alternative blueprint test helpers | 'use strict';
var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
var setupTestHooks = blueprintHelpers.setupTestHooks;
var emberNew = blueprintHelpers.emberNew;
var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
var chai = require('ember-cli-blueprint-test-helpers/chai');
var expect = chai.expect;
describe('Acceptance: ember generate and destroy instance-initializer-addon', function() {
setupTestHooks(this);
it('instance-initializer-addon foo', function() {
var args = ['instance-initializer-addon', 'foo'];
return emberNew({ target: 'addon' })
.then(() => emberGenerateDestroy(args, _file => {
expect(_file('app/instance-initializers/foo.js'))
.to.contain("export { default, initialize } from 'my-addon/instance-initializers/foo';");
}));
});
});
| 'use strict';
var tmpenv = require('ember-cli-blueprint-test-helpers/lib/helpers/tmp-env');
var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup');
var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper');
var generateAndDestroy = BlueprintHelpers.generateAndDestroy;
describe('Acceptance: ember generate and destroy instance-initializer-addon', function() {
setupTestHooks(this, tmpenv);
it('instance-initializer-addon foo', function() {
// pass any additional command line options in the arguments array
return generateAndDestroy(['instance-initializer-addon', 'foo'], {
// define files to assert, and their contents
target: 'addon',
files: [
{
file: 'app/instance-initializers/foo.js',
contains: "export { default, initialize } from 'my-addon/instance-initializers/foo';"
}
]
});
});
});
|
Enforce directs non-permitted users to Forbidden.php instead of LoginShopper.php | <?php
require_once 'database.php';
function rbacCheck($username, $url) {
$params = [$username, $url];
$rows = query(
"SELECT sh_username FROM Shopper
INNER JOIN AccessUserGroup ON shopper_id = AUG_Shopper_id
INNER JOIN AccessGroup ON AG_id = AUG_AG_id
INNER JOIN AccessGroupCommands ON AGC_AG_id = AG_id
INNER JOIN Commands ON AGC_Cmd_id = Cmd_id
WHERE sh_username = ?
AND Cmd_URL = ?", $params);
return $rows ? true : false;
}
function rbacEnforce() {
if (!isset($_SESSION['username']) ||
!rbacCheck($_SESSION['username'], basename($_SERVER["PHP_SELF"]))
) {
header('Location: Forbidden.php');
exit();
}
}
?>
| <?php
require_once 'database.php';
function rbacCheck($username, $url) {
$params = [$username, $url];
$rows = query(
"SELECT sh_username FROM Shopper
INNER JOIN AccessUserGroup ON shopper_id = AUG_Shopper_id
INNER JOIN AccessGroup ON AG_id = AUG_AG_id
INNER JOIN AccessGroupCommands ON AGC_AG_id = AG_id
INNER JOIN Commands ON AGC_Cmd_id = Cmd_id
WHERE sh_username = ?
AND Cmd_URL = ?", $params);
return $rows ? true : false;
}
function rbacEnforce() {
if (!isset($_SESSION['username']) ||
!rbacCheck($_SESSION['username'], basename($_SERVER["PHP_SELF"]))
) {
header('Location: LoginShopper.php');
exit();
}
}
?>
|
Allow kargs in resource factory | from .base import ResourceBase # noqa F401
from .bucket import Bucket # noqa F401
from .sql import SQLInstance # noqa F401
from .bigquery import BQDataset # noqa F401
class Resource():
@staticmethod
def factory(resource_data, **kargs):
resource_kind_map = {
'storage#bucket': Bucket,
'bigquery#dataset': BQDataset,
'sql#instance': SQLInstance
}
kind = resource_data.get('resource_kind')
if not kind:
assert 0, 'Unrecognized resource'
if kind not in resource_kind_map:
assert 0, 'Unrecognized resource'
cls = resource_kind_map.get(kind)
return cls(resource_data, **kargs)
| from .base import ResourceBase # noqa F401
from .bucket import Bucket # noqa F401
from .sql import SQLInstance # noqa F401
from .bigquery import BQDataset # noqa F401
class Resource():
@staticmethod
def factory(resource_data):
resource_kind_map = {
'storage#bucket': Bucket,
'bigquery#dataset': BQDataset,
'sql#instance': SQLInstance
}
kind = resource_data.get('resource_kind')
if not kind:
assert 0, 'Unrecognized resource'
if kind not in resource_kind_map:
assert 0, 'Unrecognized resource'
cls = resource_kind_map.get(kind)
return cls(resource_data)
|
Add scheduled cso_job method
- Retrieves the CSO status and updates the breathe rate | import bottle
from cso_parser import CsoParser
import waitress
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
from breathe import Breathe
from controller import Controller
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = Breathe()
cso_parser = CsoParser()
my_controller = Controller(bottle_app, breather)
@scheduler.scheduled_job(trigger='cron', hour=17, minute=30)
def on_job():
"""Start at 7:00pm PT"""
print('STARTING BREATHER')
breather.restart()
@scheduler.scheduled_job(trigger='cron', hour=19, minute=30)
def off_job():
"""End at 9:00pm PT"""
print("STOPPING BREATHER")
breather.stop()
@scheduler.scheduled_job(trigger='cron', hour=1, minute=30)
def cso_job():
"""Get CSO data at 1:30am and update the breather with the current status."""
print("Fetch CSO status and update breather.")
cso_parser.update()
if cso_parser.now_count or cso_parser.recent_count:
breather.erratic()
else:
breather.calm()
if __name__ == '__main__':
scheduler.start()
waitress.serve(bottle_app, host='0.0.0.0', port=7000)
| import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, breather)
@scheduler.scheduled_job(trigger='cron', hour=17, minute=30)
def on_job():
"""Start at 7:00pm PT"""
print('STARTING BREATHER')
breather.restart()
@scheduler.scheduled_job(trigger='cron', hour=19, minute=30)
def off_job():
"""End at 9:00pm PT"""
print("STOPPING BREATHER")
breather.stop()
if __name__ == '__main__':
scheduler.start()
waitress.serve(bottle_app, host='0.0.0.0', port=7000)
|
PYTHON: Create PyPI Release for 1.9.0.0.
Revision created by MOE tool push_codebase.
MOE_MIGRATION=6943 | """Setup specs for packaging, distributing, and installing gcs lib."""
import distribute_setup
distribute_setup.use_setuptools()
import setuptools
setuptools.setup(
name="GoogleAppEngineCloudStorageClient",
version="1.9.0.0",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.com",
keywords="google app engine cloud storage",
url="https://code.google.com/p/appengine-gcs-client/",
license="Apache License 2.0",
description=("This library is the preferred way of accessing Google "
"Cloud Storage from App Engine. It was designed to "
"replace the Files API. As a result it contains much "
"of the same functionality (streaming reads and writes but "
"not the complete set of GCS APIs). It also provides key "
"stability improvements and a better overall developer "
"experience."),
exclude_package_data={"": ["README"]},
zip_safe=True,
)
| """Setup specs for packaging, distributing, and installing gcs lib."""
import distribute_setup
distribute_setup.use_setuptools()
import setuptools
setuptools.setup(
name="GoogleAppEngineCloudStorageClient",
version="1.8.3.1",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.com",
keywords="google app engine cloud storage",
url="https://code.google.com/p/appengine-gcs-client/",
license="Apache License 2.0",
description=("This library is the preferred way of accessing Google "
"Cloud Storage from App Engine. It was designed to "
"replace the Files API. As a result it contains much "
"of the same functionality (streaming reads and writes but "
"not the complete set of GCS APIs). It also provides key "
"stability improvements and a better overall developer "
"experience."),
exclude_package_data={"": ["README"]},
zip_safe=True,
)
|
Remove --disable-gpu flag when starting headless chrome
The `--disable-gpu` flag is [no longer
necessary](https://bugs.chromium.org/p/chromium/issues/detail?id=737678) and, at
least in some cases, is [causing
issues](https://bugs.chromium.org/p/chromium/issues/detail?id=982977).
This flag has already been [removed from ember-cli's
blueprints](https://github.com/ember-cli/ember-cli/pull/8774)
As you may already know, this project's test suite is run as part of [Ember
Data](https://github.com/emberjs/data)'s test suite to help catch regressions.
The flag has already been [removed from Ember Data's own testem
config](https://github.com/emberjs/data/pull/6298) but Ember Data's complete
test suite cannot successfully run until all of our external integration
partners have also removed this flag. | module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
| module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
Set mainnet as default network and bump to 1.1.12 | const AppConstants = {
//Application name
appName: 'Nano Wallet',
version: 'BETA 1.1.12',
//Network
defaultNetwork: 104,
// Ports
defaultNisPort: 7890,
defaultWebsocketPort: 7778,
// Activate/Deactivate mainnet
mainnetDisabled: false,
// Activate/Deactivate mijin
mijinDisabled: true,
// Available languages
languages: [{
name: "English",
key: "en"
}, {
name: "Chinese",
key: "cn"
}/*, {
name: "Français",
key: "fr"
}*/],
// Transaction types
TransactionType: {
Transfer: 0x101, // 257
ImportanceTransfer: 0x801, // 2049
MultisigModification: 0x1001, // 4097
MultisigSignature: 0x1002, // 4098
MultisigTransaction: 0x1004, // 4100
ProvisionNamespace: 0x2001, // 8193
MosaicDefinition: 0x4001, // 16385
MosaicSupply: 0x4002, // 16386
}
};
export default AppConstants; | const AppConstants = {
//Application name
appName: 'Nano Wallet',
version: 'BETA 1.1.11',
//Network
defaultNetwork: -104,
// Ports
defaultNisPort: 7890,
defaultWebsocketPort: 7778,
// Activate/Deactivate mainnet
mainnetDisabled: false,
// Activate/Deactivate mijin
mijinDisabled: true,
// Available languages
languages: [{
name: "English",
key: "en"
}, {
name: "Chinese",
key: "cn"
}/*, {
name: "Français",
key: "fr"
}*/],
// Transaction types
TransactionType: {
Transfer: 0x101, // 257
ImportanceTransfer: 0x801, // 2049
MultisigModification: 0x1001, // 4097
MultisigSignature: 0x1002, // 4098
MultisigTransaction: 0x1004, // 4100
ProvisionNamespace: 0x2001, // 8193
MosaicDefinition: 0x4001, // 16385
MosaicSupply: 0x4002, // 16386
}
};
export default AppConstants; |
Allow admin creation after initial setup | from freeposte import manager, db
from freeposte.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, password):
""" Create an admin user
"""
domain = models.Domain.query.get(domain_name)
if not domain:
domain = models.Domain(name=domain_name)
db.session.add(domain)
user = models.User(
localpart=localpart,
domain=domain,
global_admin=True,
password=hash.sha512_crypt.encrypt(password)
)
db.session.add(user)
db.session.commit()
if __name__ == "__main__":
manager.run()
| from freeposte import manager, db
from freeposte.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, password):
""" Create an admin user
"""
domain = models.Domain(name=domain_name)
user = models.User(
localpart=localpart,
domain=domain,
global_admin=True,
password=hash.sha512_crypt.encrypt(password)
)
db.session.add(domain)
db.session.add(user)
db.session.commit()
if __name__ == "__main__":
manager.run()
|
Use os/exec to run editor | package commands
import (
"log"
"os"
"os/exec"
"path"
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/cobra"
"github.com/khlieng/name_pending/storage"
)
var (
editors = []string{"nano", "notepad", "vi", "emacs"}
configCmd = &cobra.Command{
Use: "config",
Short: "Edit config file",
Run: func(cmd *cobra.Command, args []string) {
if editor := findEditor(); editor != "" {
process := exec.Command(editor, path.Join(storage.AppDir, "config.toml"))
process.Stdin = os.Stdin
process.Stdout = os.Stdout
process.Stderr = os.Stderr
process.Run()
} else {
log.Println("Unable to locate editor")
}
},
}
)
func findEditor() string {
if editor := os.Getenv("EDITOR"); editor != "" {
editor, err := exec.LookPath(editor)
if err == nil {
return editor
}
}
for _, editor := range editors {
editor, err := exec.LookPath(editor)
if err == nil {
return editor
}
}
return ""
}
| package commands
import (
"log"
"os"
"os/exec"
"path"
"syscall"
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/cobra"
"github.com/khlieng/name_pending/storage"
)
var (
editors = []string{"nano", "notepad", "vi", "emacs"}
configCmd = &cobra.Command{
Use: "config",
Short: "Edit config file",
Run: func(cmd *cobra.Command, _ []string) {
if editor := findEditor(); editor != "" {
args := []string{editor, path.Join(storage.AppDir, "config.toml")}
syscall.Exec(editor, args, os.Environ())
} else {
log.Println("Unable to locate editor")
}
},
}
)
func findEditor() string {
if editor := os.Getenv("EDITOR"); editor != "" {
editor, err := exec.LookPath(editor)
if err == nil {
return editor
}
}
for _, editor := range editors {
editor, err := exec.LookPath(editor)
if err == nil {
return editor
}
}
return ""
}
|
Test extension's parameter access for a given period | from __future__ import unicode_literals, print_function, division, absolute_import
from nose.tools import raises
from openfisca_core.parameters import ParameterNode
from openfisca_country_template import CountryTaxBenefitSystem
tbs = CountryTaxBenefitSystem()
def test_extension_not_already_loaded():
assert tbs.get_variable('local_town_child_allowance') is None
def walk_and_count(node):
c = 0
for item_name, item in node.children.items():
if isinstance(item, ParameterNode):
c += walk_and_count(item)
else:
c += 1
return c
def test_load_extension():
assert len(tbs.variables) == 16
assert walk_and_count(tbs.parameters) == 8
tbs.load_extension('openfisca_extension_template')
assert len(tbs.variables) == 17
assert tbs.get_variable('local_town_child_allowance') is not None
assert walk_and_count(tbs.parameters) == 9
assert tbs.parameters('2016-01').local_town.child_allowance.amount == 100.0
assert tbs.parameters.local_town.child_allowance.amount is not None
def test_unload_extensions():
tbs = CountryTaxBenefitSystem()
assert tbs.get_variable('local_town_child_allowance') is None
@raises(ValueError)
def test_failure_to_load_extension_when_directory_doesnt_exist():
tbs.load_extension('/this/is/not/a/real/path')
| from __future__ import unicode_literals, print_function, division, absolute_import
from nose.tools import raises
from openfisca_core.parameters import ParameterNode
from openfisca_country_template import CountryTaxBenefitSystem
tbs = CountryTaxBenefitSystem()
def test_extension_not_already_loaded():
assert tbs.get_variable('local_town_child_allowance') is None
def walk_and_count(node):
c = 0
for item_name, item in node.children.items():
if isinstance(item, ParameterNode):
c += walk_and_count(item)
else:
c += 1
return c
def test_load_extension():
assert len(tbs.variables) == 16
assert walk_and_count(tbs.parameters) == 8
tbs.load_extension('openfisca_extension_template')
assert len(tbs.variables) == 17
assert tbs.get_variable('local_town_child_allowance') is not None
assert walk_and_count(tbs.parameters) == 9
assert tbs.parameters.local_town.child_allowance.amount is not None
def test_unload_extensions():
tbs = CountryTaxBenefitSystem()
assert tbs.get_variable('local_town_child_allowance') is None
@raises(ValueError)
def test_failure_to_load_extension_when_directory_doesnt_exist():
tbs.load_extension('/this/is/not/a/real/path')
|
Change export syntax for Typescript & eslint | export { default as AttachmentsController } from './controllers/api/v1/AttachmentsController';
export { default as FeedFactoriesController } from './controllers/api/v1/FeedFactoriesController';
export { default as GroupsController } from './controllers/api/v1/GroupsController';
export { default as PasswordsController } from './controllers/api/v1/PasswordsController';
export { default as PostsController } from './controllers/api/v1/PostsController';
export { default as SessionController } from './controllers/api/v1/SessionController';
export { default as UsersController } from './controllers/api/v1/UsersController';
export { default as GroupsControllerV2 } from './controllers/api/v2/GroupsController';
export { default as RequestsControllerV2 } from './controllers/api/v2/RequestsController';
export { default as UsersControllerV2 } from './controllers/api/v2/UsersController';
export { default as StatsControllerV2 } from './controllers/api/v2/StatsController';
export { default as ArchivesStatsControllerV2 } from './controllers/api/v2/ArchivesStatsController';
export { default as SearchController } from './controllers/api/v2/SearchController';
export { default as EventsController } from './controllers/api/v2/EventsController';
export { default as CommentLikesController } from './controllers/api/v2/CommentLikesController';
export { default as InvitationsController } from './controllers/api/v2/InvitationsController';
| /* eslint babel/semi: "error" */
export AttachmentsController from './controllers/api/v1/AttachmentsController';
export FeedFactoriesController from './controllers/api/v1/FeedFactoriesController';
export GroupsController from './controllers/api/v1/GroupsController';
export PasswordsController from './controllers/api/v1/PasswordsController';
export PostsController from './controllers/api/v1/PostsController';
export SessionController from './controllers/api/v1/SessionController';
export UsersController from './controllers/api/v1/UsersController';
export GroupsControllerV2 from './controllers/api/v2/GroupsController';
export RequestsControllerV2 from './controllers/api/v2/RequestsController';
export UsersControllerV2 from './controllers/api/v2/UsersController';
export StatsControllerV2 from './controllers/api/v2/StatsController';
export ArchivesStatsControllerV2 from './controllers/api/v2/ArchivesStatsController';
export SearchController from './controllers/api/v2/SearchController';
export EventsController from './controllers/api/v2/EventsController';
export CommentLikesController from './controllers/api/v2/CommentLikesController';
export InvitationsController from './controllers/api/v2/InvitationsController';
|
DOC: Add source of pickle hack | # This unfortunate monkey patch is necessary to make Py27, Py33 and Py34 work
# Source: http://stackoverflow.com/questions/34124270/pickling-method-descriptor-objects-in-python
# first import dill, which populates itself into pickle's dispatch
import dill
import pickle
# save the MethodDescriptorType from dill
MethodDescriptorType = type(type.__dict__['mro'])
if pickle.__dict__.get('_Pickler', None):
MethodDescriptorWrapper = pickle._Pickler.dispatch[MethodDescriptorType]
else:
MethodDescriptorWrapper = pickle.Pickler.dispatch[MethodDescriptorType]
# cloudpickle does the same, so let it update the dispatch table
import cloudpickle
# now, put the saved MethodDescriptorType back in
if pickle.__dict__.get('_Pickler', None):
pickle._Pickler.dispatch[MethodDescriptorType] = MethodDescriptorWrapper
else:
pickle.Pickler.dispatch[MethodDescriptorType] = MethodDescriptorWrapper
import pycalphad.variables as v
from pycalphad.model import Model
from pycalphad.io.database import Database
# Trigger format extension hooks
import pycalphad.io.tdb
from pycalphad.core.calculate import calculate
from pycalphad.core.equilibrium import equilibrium
from pycalphad.core.equilibrium import EquilibriumError, ConditionError
from pycalphad.plot.binary import binplot
from pycalphad.plot.eqplot import eqplot
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| #first import dill, which populates itself into pickle's dispatch
import dill
import pickle
# save the MethodDescriptorType from dill
MethodDescriptorType = type(type.__dict__['mro'])
if pickle.__dict__.get('_Pickler', None):
MethodDescriptorWrapper = pickle._Pickler.dispatch[MethodDescriptorType]
else:
MethodDescriptorWrapper = pickle.Pickler.dispatch[MethodDescriptorType]
# cloudpickle does the same, so let it update the dispatch table
import cloudpickle
# now, put the saved MethodDescriptorType back in
if pickle.__dict__.get('_Pickler', None):
pickle._Pickler.dispatch[MethodDescriptorType] = MethodDescriptorWrapper
else:
pickle.Pickler.dispatch[MethodDescriptorType] = MethodDescriptorWrapper
import pycalphad.variables as v
from pycalphad.model import Model
from pycalphad.io.database import Database
# Trigger format extension hooks
import pycalphad.io.tdb
from pycalphad.core.calculate import calculate
from pycalphad.core.equilibrium import equilibrium
from pycalphad.core.equilibrium import EquilibriumError, ConditionError
from pycalphad.plot.binary import binplot
from pycalphad.plot.eqplot import eqplot
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
Allow CJS node_modules in test browser bundles | const babel = require('rollup-plugin-babel');
const multiEntry = require('rollup-plugin-multi-entry');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const replace = require('rollup-plugin-replace');
const browserConfig = require('./browser-config.js');
const template = ({env}) => `${env}.js`;
module.exports = (userBabelConfig) => ({
formats: ['iife'],
template,
plugins: [
resolve({browser: true}),
commonjs({include: /node_modules/}),
multiEntry({exports: false}),
babel(Object.assign({}, browserConfig(userBabelConfig), {exclude: 'node_modules/**'})),
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
});
| const babel = require('rollup-plugin-babel');
const multiEntry = require('rollup-plugin-multi-entry');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const replace = require('rollup-plugin-replace');
const browserConfig = require('./browser-config.js');
const template = ({env}) => `${env}.js`;
module.exports = (userBabelConfig) => ({
formats: ['iife'],
template,
plugins: [
resolve({browser: true}),
commonjs({include: 'node_modules/**'}),
multiEntry({exports: false}),
babel(Object.assign({}, browserConfig(userBabelConfig), {exclude: 'node_modules/**'})),
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
});
|
Fix typo in provider iterator relating to source document from ES | <?php
namespace CascadeEnergy\DistributedOperations\Elasticsearch;
use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;
class ProviderIterator implements \Iterator
{
/** @var SearchHitIterator */
private $hitIterator;
public function __construct(SearchHitIterator $hitIterator)
{
$this->hitIterator = $hitIterator;
}
public function current()
{
$hit = $this->hitIterator->current();
$source = $hit['_source'];
$operation = new Operation($source['batchId'], $hit['_type'], $source['options']);
$operation->setState($source['state']);
$operation->setDisposition($source['disposition']);
return $operation;
}
public function next()
{
$this->hitIterator->next();
}
public function key()
{
return $this->hitIterator->key();
}
public function valid()
{
return $this->hitIterator->valid();
}
public function rewind()
{
$this->hitIterator->rewind();
}
}
| <?php
namespace CascadeEnergy\DistributedOperations\Elasticsearch;
use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;
class ProviderIterator implements \Iterator
{
/** @var SearchHitIterator */
private $hitIterator;
public function __construct(SearchHitIterator $hitIterator)
{
$this->hitIterator = $hitIterator;
}
public function current()
{
$hit = $this->hitIterator->current();
$source = $hit['source'];
$operation = new Operation($source['batchId'], $hit['_type'], $source['options']);
$operation->setState($source['state']);
$operation->setDisposition($source['disposition']);
return $operation;
}
public function next()
{
$this->hitIterator->next();
}
public function key()
{
return $this->hitIterator->key();
}
public function valid()
{
return $this->hitIterator->valid();
}
public function rewind()
{
$this->hitIterator->rewind();
}
}
|
Use a checked entity instead of an unchecked one | package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.Trackable;
import cgeo.geocaching.connector.UserAction;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import java.util.Collections;
import java.util.List;
public class UnknownTrackableConnector extends AbstractTrackableConnector {
@Override
public boolean canHandleTrackable(final String geocode) {
return false;
}
@NonNull
@Override
public String getServiceTitle() {
throw new IllegalStateException("this connector does not have a corresponding name.");
}
@Override
public boolean hasTrackableUrls() {
return false;
}
@Override
@Nullable
public Trackable searchTrackable(final String geocode, final String guid, final String id) {
return null;
}
@Override
@NonNull
public TrackableBrand getBrand() {
return TrackableBrand.UNKNOWN;
}
@Override
@NonNull
public List<UserAction> getUserActions() {
return Collections.emptyList();
}
}
| package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.Trackable;
import cgeo.geocaching.connector.UserAction;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import java.util.Collections;
import java.util.List;
public class UnknownTrackableConnector extends AbstractTrackableConnector {
@Override
public boolean canHandleTrackable(final String geocode) {
return false;
}
@NonNull
@Override
public String getServiceTitle() {
throw new IllegalStateException("this connector does not have a corresponding name.");
}
@Override
public boolean hasTrackableUrls() {
return false;
}
@Override
@Nullable
public Trackable searchTrackable(final String geocode, final String guid, final String id) {
return null;
}
@Override
@NonNull
public TrackableBrand getBrand() {
return TrackableBrand.UNKNOWN;
}
@Override
@NonNull
public List<UserAction> getUserActions() {
return Collections.EMPTY_LIST;
}
}
|
Add attending as column to Guest | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name', 'attending', ]
list_filter = ['last_name', 'first_name']
search_fields = ['last_name', 'first_name', ]
save_on_top = True
class LocationAdmin(AdminModel):
pass
class TableAdmin(AdminModel):
pass
class EventAdmin(AdminModel):
pass
class HotelAdmin(AdminModel):
pass
class PartyAdmin(admin.ModelAdmin):
filter_horizontal = ('guests',)
list_display = ['name', 'responded']
class SongAdmin(admin.ModelAdmin):
list_display = ['title', 'artist', 'votes']
admin.site.register(Guest, GuestAdmin)
admin.site.register(Location, LocationAdmin)
admin.site.register(Table, TableAdmin)
admin.site.register(Event, EventAdmin)
admin.site.register(Hotel, HotelAdmin)
admin.site.register(Party, PartyAdmin)
admin.site.register(Song, SongAdmin) | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name']
list_filter = ['last_name', 'first_name']
search_fields = ['last_name', 'first_name', ]
save_on_top = True
class LocationAdmin(AdminModel):
pass
class TableAdmin(AdminModel):
pass
class EventAdmin(AdminModel):
pass
class HotelAdmin(AdminModel):
pass
class PartyAdmin(admin.ModelAdmin):
filter_horizontal = ('guests',)
list_display = ['name', 'responded']
class SongAdmin(admin.ModelAdmin):
list_display = ['title', 'artist', 'votes']
admin.site.register(Guest, GuestAdmin)
admin.site.register(Location, LocationAdmin)
admin.site.register(Table, TableAdmin)
admin.site.register(Event, EventAdmin)
admin.site.register(Hotel, HotelAdmin)
admin.site.register(Party, PartyAdmin)
admin.site.register(Song, SongAdmin) |
Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6 | # -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
| # -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
Throw errors on non-zero cmd exit codes | var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var semver = require('semver');
var sh = require('execSync');
var packageJSONPath = path.join(process.cwd(), 'package.json');
var packageJSON = require(packageJSONPath);
module.exports = function(newVersion, commitMessage){
var newSemver = packageJSON.version = getNewSemver(newVersion);
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2));
commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver);
runCommand('git commit -am "' + commitMessage + '"');
runCommand('git tag v' + newSemver);
runCommand('git push origin --all');
runCommand('git push origin --tags');
if (!packageJSON.private) runCommand('npm publish');
};
function getNewSemver(newVersion) {
var newSemver = semver.valid(newVersion);
if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion);
if (!newSemver) throw new Error('Invalid new version');
return newSemver;
}
function getCommitMessage(commitMessage, newSemver) {
commitMessage = commitMessage || 'Release v%s';
return commitMessage.replace(/%s/g, newSemver);
}
function runCommand(cmd) {
if (sh.run(cmd)) throw new Error('[' + command + '] failed');
} | var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var semver = require('semver');
var sh = require('execSync');
var packageJSONPath = path.join(process.cwd(), 'package.json');
var packageJSON = require(packageJSONPath);
module.exports = function(newVersion, commitMessage){
var newSemver = packageJSON.version = getNewSemver(newVersion);
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2));
commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver);
runCommand('git commit -am "' + commitMessage + '"');
runCommand('git tag v' + newSemver);
runCommand('git push origin --all');
runCommand('git push origin --tags');
if (!packageJSON.private) runCommand('npm publish');
};
function getNewSemver(newVersion) {
var newSemver = semver.valid(newVersion);
if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion);
if (!newSemver) throw new Error('Invalid new version');
return newSemver;
}
function getCommitMessage(commitMessage, newSemver) {
commitMessage = commitMessage || 'Release v%s';
return commitMessage.replace(/%s/g, newSemver);
}
function runCommand(cmd) {
if (!sh.run(cmd)) throw new Error('[' + command + '] failed');
} |
Simplify checking when pop-ed value isn't int | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package lists
// MergeSorted merges int nodes from l and f sorted lists into the ordered list m.
// Note: when l or f contains different type from int then false is returned and
// merged list will contains some value(s) merged from l or f up to the different
// type.
func MergeSorted(l, f *List) (m *List, ok bool) {
m = new(List)
for l.Len() > 0 || f.Len() > 0 {
vl, nl, okl := PopInt(l)
vf, nf, okf := PopInt(f)
if !okl || !okf {
return m, false
}
ll, n := l, nl // The assumption is: vl <= vf.
switch {
case l.Len() == 0:
ll, n = f, nf
case f.Len() == 0:
ll, n = l, nl
case vl > vf:
ll, n = f, nf
}
m.Insert(ll.Remove(n))
}
return m, true
}
| // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package lists
// MergeSorted merges int nodes from l and f sorted lists into the ordered list m.
// Note: when l or f contains different type from int then false is returned and
// merged list will contains some value(s) merged from l or f up to the different
// type.
func MergeSorted(l, f *List) (m *List, ok bool) {
m = new(List)
for l.Len() > 0 || f.Len() > 0 {
vl, nl, okl := PopInt(l)
if !okl {
return m, false
}
vf, nf, okf := PopInt(f)
if !okf {
return m, false
}
ll, n := l, nl // The assumption is: vl <= vf.
switch {
case l.Len() == 0:
ll, n = f, nf
case f.Len() == 0:
ll, n = l, nl
case vl > vf:
ll, n = f, nf
}
m.Insert(ll.Remove(n))
}
return m, true
}
|
Switch to standard reporter for mocha | var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
gulp.task('pre-test', function() {
return gulp.src('src/*.js')
.pipe(istanbul())
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function() {
return gulp.src('test/*.js')
.pipe(mocha())
.pipe(istanbul.writeReports());
});
gulp.task('jscs', function() {
return gulp.src([
'src/*.js',
'test/*.js',
'gulpfile.js'
])
.pipe(jscs())
.pipe(jscs.reporter());
});
gulp.task('jshint', function() {
return gulp.src([
'src/*.js',
'test/*.js',
'gulpfile.js'
])
.pipe(jshint())
.pipe(jshint.reporter());
});
gulp.task('lint', ['jshint', 'jscs']);
gulp.task('default', ['lint', 'test']);
| var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
gulp.task('pre-test', function() {
return gulp.src('src/*.js')
.pipe(istanbul())
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function() {
return gulp.src('test/*.js')
.pipe(mocha({reporter: 'nyan'}))
.pipe(istanbul.writeReports());
});
gulp.task('jscs', function() {
return gulp.src([
'src/*.js',
'test/*.js',
'gulpfile.js'
])
.pipe(jscs())
.pipe(jscs.reporter());
});
gulp.task('jshint', function() {
return gulp.src([
'src/*.js',
'test/*.js',
'gulpfile.js'
])
.pipe(jshint())
.pipe(jshint.reporter());
});
gulp.task('lint', ['jshint', 'jscs']);
gulp.task('default', ['lint', 'test']);
|
Migrate to PhantomJS for testing in travis | // base path, that will be used to resolve files and exclude
basePath = '../';
// list of files / patterns to load in the browser
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.spec.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters = ['progress'];
// web server port
port = 9877;
// cli runner port
runnerPort = 9101;
// enable / disable colors in the output (reporters and logs)
colors = true;
urlRoot = '/__karma/';
proxies = {
'/': 'http://localhost:3000/'
};
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['PhantomJS'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true;
| // base path, that will be used to resolve files and exclude
basePath = '../';
// list of files / patterns to load in the browser
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.spec.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters = ['progress'];
// web server port
port = 9877;
// cli runner port
runnerPort = 9101;
// enable / disable colors in the output (reporters and logs)
colors = true;
urlRoot = '/__karma/';
proxies = {
'/': 'http://localhost:3000/'
};
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true; |
Add source map to prod | var path = require('path');
var webpack = require('webpack');
var webpackStripLoader = require('strip-loader');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
entry: ['./js/App.js'],
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
devtool: 'source-map',
module: {
rules: [{
test: /.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.png$/,
use: 'url-loader'
},
{
test: [/\.js$/, /\.jsx$/],
exclude: /node_modules/,
use: webpackStripLoader.loader('console.log')
}
]
}
};
| var path = require('path');
var webpack = require('webpack');
var webpackStripLoader = require('strip-loader');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
entry: ['./js/App.js'],
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
module: {
rules: [{
test: /.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.png$/,
use: 'url-loader'
},
{
test: [/\.js$/, /\.jsx$/],
exclude: /node_modules/,
use: webpackStripLoader.loader('console.log')
}
]
}
};
|
Make tracking_since return time in seconds rather than milliseconds | 'use strict'
const mongoose = require('mongoose')
var tweetSchema = new mongoose.Schema({
embed_id: String
}, {_id: false})
var articleSchema = new mongoose.Schema({
title: String,
description: String,
source: String,
link: String,
timestamp: Number,
media: String
}, {_id: false})
var keywordSchema = new mongoose.Schema({
word: String,
occurences: Number
}, {_id: false})
var trendSchema = new mongoose.Schema({
name: String,
rank: Number,
tracking_since: {type: Number, default: () => {return Math.round(Date.now() / 1000)}},
tweets_analyzed: Number,
sentiment_score: Number,
sentiment_description: String,
locations: [String],
tweet_volume: Number,
keywords: [keywordSchema],
tweets: [tweetSchema],
articles: [articleSchema]
})
var Trend = mongoose.model('Trend', trendSchema)
module.exports = Trend
| 'use strict'
const mongoose = require('mongoose')
var tweetSchema = new mongoose.Schema({
embed_id: String
}, {_id: false})
var articleSchema = new mongoose.Schema({
title: String,
description: String,
source: String,
link: String,
timestamp: Number,
media: String
}, {_id: false})
var keywordSchema = new mongoose.Schema({
word: String,
occurences: Number
}, {_id: false})
var trendSchema = new mongoose.Schema({
name: String,
rank: Number,
tracking_since: {type: Number, default: Date.now},
tweets_analyzed: Number,
sentiment_score: Number,
sentiment_description: String,
locations: [String],
tweet_volume: Number,
keywords: [keywordSchema],
tweets: [tweetSchema],
articles: [articleSchema]
})
var Trend = mongoose.model('Trend', trendSchema)
module.exports = Trend
|
Change to nicer check for FileReader | (function () {
// Check that the browser supports the FileReader API.
if (!window.FileReader) {
document.write('<strong>Sorry, your web browser does not support the FileReader API.</strong>');
return;
}
var handleFile = function (evt) {
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function (evt) {
try {
var exif = new ExifReader();
// Parse the Exif tags.
exif.load(evt.target.result);
// Or, with jDataView you would use this:
//exif.loadView(new jDataView(evt.target.result));
// Output the tags on the page.
var tags = exif.getAllTags();
var tableBody = document.getElementById('exif-table-body');
for (var name in tags) {
var tag = {'name': name, 'description': tags[name]};
var row = document.createElement('tr');
row.innerHTML = '<td>' + tag.name + '</td><td>' + tag.description + '</td>';
tableBody.appendChild(row);
}
}
catch (error) {
alert(error);
}
};
reader.readAsArrayBuffer(files[0]);
};
window.addEventListener("load", function () {
document.getElementById("file").addEventListener("change", handleFile, false);
}, false);
})();
| (function () {
// Check that the browser supports the FileReader API.
if (typeof FileReader === 'undefined') {
document.write('<strong>Sorry, your web browser does not support the FileReader API.</strong>');
return;
}
var handleFile = function (evt) {
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function (evt) {
try {
var exif = new ExifReader();
// Parse the Exif tags.
exif.load(evt.target.result);
// Or, with jDataView you would use this:
//exif.loadView(new jDataView(evt.target.result));
// Output the tags on the page.
var tags = exif.getAllTags();
var tableBody = document.getElementById('exif-table-body');
for (var name in tags) {
var tag = {'name': name, 'description': tags[name]};
var row = document.createElement('tr');
row.innerHTML = '<td>' + tag.name + '</td><td>' + tag.description + '</td>';
tableBody.appendChild(row);
}
}
catch (error) {
alert(error);
}
};
reader.readAsArrayBuffer(files[0]);
};
window.addEventListener("load", function () {
document.getElementById("file").addEventListener("change", handleFile, false);
}, false);
})();
|
Annotate parameter and field for better compiler checking | package com.veyndan.redditclient.ui.recyclerview.itemdecoration;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class MarginItemDecoration extends RecyclerView.ItemDecoration {
@Px private final int margin;
public MarginItemDecoration(@NonNull final Context context, @DimenRes final int marginRes) {
margin = context.getResources().getDimensionPixelOffset(marginRes);
}
@Override
public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
final RecyclerView.State state) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
final int position = params.getViewLayoutPosition();
final int marginTop = position == 0 ? margin : 0;
outRect.set(margin, marginTop, margin, margin);
}
}
| package com.veyndan.redditclient.ui.recyclerview.itemdecoration;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class MarginItemDecoration extends RecyclerView.ItemDecoration {
private final int margin;
public MarginItemDecoration(final Context context, @DimenRes final int marginRes) {
margin = context.getResources().getDimensionPixelOffset(marginRes);
}
@Override
public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
final RecyclerView.State state) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
final int position = params.getViewLayoutPosition();
final int marginTop = position == 0 ? margin : 0;
outRect.set(margin, marginTop, margin, margin);
}
}
|
Add development ip to allowed ips | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
$allowedIps = [gethostbyname('development'), '127.0.0.1', 'fe80::1', '::1'];
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], $allowedIps) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check ' . basename(__FILE__) . ' for more information.');
}
$loader = require_once __DIR__ . '/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__ . '/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Add default images for podcasts if necessary | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
if re.search('podcast', filename):
if re.search('^hero: ', contents[6]):
print filename
contents.insert(6, 'hero: /blog/images/category/podcasts.jpg\n')
f = file.open(filename, "w")
f.write("".join(contents))
f.close()
| import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
for key, line in enumerate(contents):
src = re.search('\!\[.*?\]\((.*?)\)', line)
if src:
wordpress_src = re.search('/blog/images/wordpress/(.*)', src.group(1))
if wordpress_src:
image_src = wordpress_src.group(1)
path = 'images/wordpress/'+image_src
print 'Retrieving ' + path + '...'
if not os.path.isfile(path):
print path
f = open(path, "w")
f.write(requests.get("http://blog.stackoverflow.com/wp-content/uploads/" + wordpress_src.group(1)).content)
f.close()
continue
f = open(filename, "w")
contents = "".join(contents)
f.write(contents)
f.close() |
Add a custom `log` to the example | var Fleur = require('..');
var Foo = Fleur.actions('foo', {
synchronous: function(state) {
return Fleur.assign(state, {
status: 'pending'
});
},
asynchronous: function(state, dispatch) {
dispatch(Foo.synchronous());
return Fleur.promise(function(resolve) {
setTimeout(function() {
resolve(Fleur.assign(state, {
items: [
{ title: 'foo', id: 1 },
{ title: 'bar', id: 2 },
{ title: 'baz', id: 3 }
],
status: 'success'
}));
}, 100);
});
}
});
var log = function(object) {
console.log(JSON.stringify(object, null, 2));
};
var store = Fleur.store();
store.dispatch(Foo.asynchronous())
.then(function() {
log(store.getState());
});
| var Fleur = require('..');
var Foo = Fleur.actions('foo', {
synchronous: function(state) {
return Fleur.assign(state, {
status: 'pending'
});
},
asynchronous: function(state, dispatch) {
dispatch(Foo.synchronous());
return Fleur.promise(function(resolve) {
setTimeout(function() {
resolve(Fleur.assign(state, {
items: [
{ title: 'foo', id: 1 },
{ title: 'bar', id: 2 },
{ title: 'baz', id: 3 }
],
status: 'success'
}));
}, 100);
});
}
});
var store = Fleur.store();
store.dispatch(Foo.asynchronous())
.then(function() {
console.log(store.getState());
});
|
Enforce camelCase for private and protected class members
This encodes some of the TypeScript style guides about identifiers
https://google.github.io/styleguide/tsguide.html#identifiers
(in particular the rules our codebase already adheres to).
The automatic enforcement will save time during code reviews.
The current TypeScript migration produces a lot of public class
properties and methods with leading underscores, so this CL only
enforces the rule for protected and private class members; the
rule can be enforced for public variables as well at a later
point in time.
Bug: chromium:1057042
Change-Id: Ic63b0a9b128f8b560020c015a0f91bbf72a9dd6d
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2672026
Commit-Queue: Sigurd Schneider <f04d242e109628a27a0f75fd49a87722bcf291fd@chromium.org>
Reviewed-by: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const path = require('path');
const rulesDirPlugin = require('eslint-plugin-rulesdir');
rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib');
module.exports = {
'overrides': [{
'files': ['*.ts'],
'rules': {
'@typescript-eslint/explicit-function-return-type': 2,
'rulesdir/kebab_case_events': 2,
'rulesdir/set_data_type_reference': 2,
'rulesdir/lit_html_data_as_type': 2,
'rulesdir/lit_no_style_interpolation': 2,
'@typescript-eslint/naming-convention': [
'error', {
'selector': 'property',
'modifiers': ['private', 'protected'],
'format': ['camelCase'],
},
{
'selector': 'method',
'modifiers': ['private', 'protected'],
'format': ['camelCase'],
}
]
}
}]
};
| // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const path = require('path');
const rulesDirPlugin = require('eslint-plugin-rulesdir');
rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib');
module.exports = {
'overrides': [{
'files': ['*.ts'],
'rules': {
'@typescript-eslint/explicit-function-return-type': 2,
'rulesdir/kebab_case_events': 2,
'rulesdir/set_data_type_reference': 2,
'rulesdir/lit_html_data_as_type': 2,
'rulesdir/lit_no_style_interpolation': 2,
}
}]
};
|
Add Since to LRPInstance struct
[#97600328] | package cc_messages
import "time"
type LRPInstanceState string
const (
LRPInstanceStateStarting LRPInstanceState = "STARTING"
LRPInstanceStateRunning LRPInstanceState = "RUNNING"
LRPInstanceStateCrashed LRPInstanceState = "CRASHED"
LRPInstanceStateUnknown LRPInstanceState = "UNKNOWN"
)
type LRPInstance struct {
ProcessGuid string `json:"process_guid"`
InstanceGuid string `json:"instance_guid"`
Index uint `json:"index"`
State LRPInstanceState `json:"state"`
Details string `json:"details,omitempty"`
Host string `json:"host,omitempty"`
Port uint16 `json:"port,omitempty"`
Uptime int64 `json:"uptime"`
Since int64 `json:"since"`
Stats *LRPInstanceStats `json:"stats,omitempty"`
}
type LRPInstanceStats struct {
Time time.Time `json:"time"`
CpuPercentage float64 `json:"cpu"`
MemoryBytes uint64 `json:"mem"`
DiskBytes uint64 `json:"disk"`
}
| package cc_messages
import "time"
type LRPInstanceState string
const (
LRPInstanceStateStarting LRPInstanceState = "STARTING"
LRPInstanceStateRunning LRPInstanceState = "RUNNING"
LRPInstanceStateCrashed LRPInstanceState = "CRASHED"
LRPInstanceStateUnknown LRPInstanceState = "UNKNOWN"
)
type LRPInstance struct {
ProcessGuid string `json:"process_guid"`
InstanceGuid string `json:"instance_guid"`
Index uint `json:"index"`
State LRPInstanceState `json:"state"`
Details string `json:"details,omitempty"`
Host string `json:"host,omitempty"`
Port uint16 `json:"port,omitempty"`
Uptime int64 `json:"uptime"`
Stats *LRPInstanceStats `json:"stats,omitempty"`
}
type LRPInstanceStats struct {
Time time.Time `json:"time"`
CpuPercentage float64 `json:"cpu"`
MemoryBytes uint64 `json:"mem"`
DiskBytes uint64 `json:"disk"`
}
|
Simplify test of rsqrt function. | import unittest
import numpy
import chainer.functions as F
from chainer import testing
#
# sqrt
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| import unittest
import numpy
import chainer.functions as F
from chainer import testing
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
#
# sqrt
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x, dtype=numpy.float32):
return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
# TODO(takagi) Fix test of rsqrt not to use this decorator.
@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
admin_base: Select latest event when logged in. | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from Instanssi.admin_base.misc.eventsel import get_selected_event
@login_required(login_url='/control/auth/login/')
def index(request):
# Select latest event as default
print get_selected_event(request)
# Redirect to events page
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
# Get redirect path
if 'r' in request.GET:
r = request.GET['r']
if r[0] != "/":
r = "/control/"
else:
r = "/control/"
# Set session variable
try:
request.session['m_event_id'] = int(event_id)
except:
raise Http404
# Redirect
return HttpResponseRedirect(r) | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
# Get redirect path
if 'r' in request.GET:
r = request.GET['r']
if r[0] != "/":
r = "/control/"
else:
r = "/control/"
# Set session variable
try:
request.session['m_event_id'] = int(event_id)
except:
raise Http404
# Redirect
return HttpResponseRedirect(r) |
Fix in EPC example - incorrect variable name. | #!/usr/bin/python
import smtplib
#SMTP server settings
SMTP_SERVER = 'smtp.server.com' #e.g. smtp.gmail.com
SMTP_PORT = 587
SMTP_USERNAME = 'yourname@server.com' #your login name, e.g. yourname@gmail.com
SMTP_PASSWORD = 'yourpassword' #CAUTION: This is stored in plain text!
#notification recipient and content
recipient = 'notification@recipient.com'
subject = 'Event notification [REX Control System]'
emailText = 'This is to inform you that an event ocurred.'
emailText = "" + emailText + ""
headers = ["From: " + SMTP_USERNAME,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(SMTP_USERNAME, SMTP_PASSWORD)
session.sendmail(SMTP_USERNAME, recipient, headers + "\r\n\r\n" + emailText)
session.quit()
| #!/usr/bin/python
import smtplib
#SMTP server settings
SMTP_SERVER = 'smtp.server.com' #e.g. smtp.gmail.com
SMTP_PORT = 587
SMTP_USERNAME = 'yourname@server.com' #your login name, e.g. yourname@gmail.com
SMTP_PASSWORD = 'yourpassword' #CAUTION: This is stored in plain text!
#notification recipient and content
recipient = 'notification@recipient.com'
subject = 'Event notification [REX Control System]'
emailText = 'This is to inform you that an event ocurred.'
emailText = "" + emailText + ""
headers = ["From: " + MAIL_USERNAME,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(SMTP_USERNAME, SMTP_PASSWORD)
session.sendmail(SMTP_USERNAME, recipient, headers + "\r\n\r\n" + emailText)
session.quit()
|
Fix typo in import and bump to 0.3.1 | from django.conf.urls.defaults import patterns, include, url
from django.views.generic import TemplateView
# ADMIN_BASE is the base URL for your Armstrong admin. It is highly
# recommended that you change this to a different URL unless you enforce a
# strict password-strength policy for your users.
ADMIN_BASE = "admin"
# Comment the next two lines out to disnable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', '{{ project_name }}.views.home', name='home'),
# url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')),
# Comment the admin/doc line below to disable admin documentation:
url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')),
# Comment the next line to disable the admin:
url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)),
# Load the Armstrong "success" page by default
url(r'^$', TemplateView.as_view(template_name="index.html")),
)
| from django.conf.urls.defaults import patterns, include, url
from django.view.generic import TemplateView
# ADMIN_BASE is the base URL for your Armstrong admin. It is highly
# recommended that you change this to a different URL unless you enforce a
# strict password-strength policy for your users.
ADMIN_BASE = "admin"
# Comment the next two lines out to disnable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', '{{ project_name }}.views.home', name='home'),
# url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')),
# Comment the admin/doc line below to disable admin documentation:
url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')),
# Comment the next line to disable the admin:
url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)),
# Load the Armstrong "success" page by default
url(r'^$', TemplateView.as_view(template_name="index.html")),
)
|
Fix GPTProtective partition type (0xee) for hybrid/protective MBRs | package mbr
// Type constants for the GUID for type of partition, see https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_entries
type Type byte
// List of GUID partition types
const (
Empty Type = 0x00
Fat12 Type = 0x01
XenixRoot Type = 0x02
XenixUsr Type = 0x03
Fat16 Type = 0x04
ExtendedCHS Type = 0x05
Fat16b Type = 0x06
NTFS Type = 0x07
CommodoreFAT Type = 0x08
Fat32CHS Type = 0x0b
Fat32LBA Type = 0x0c
Fat16bLBA Type = 0x0e
ExtendedLBA Type = 0x0f
Linux Type = 0x83
LinuxExtended Type = 0x85
LinuxLVM Type = 0x8e
Iso9660 Type = 0x96
MacOSXUFS Type = 0xa8
MacOSXBoot Type = 0xab
HFS Type = 0xaf
Solaris8Boot Type = 0xbe
GPTProtective Type = 0xee
EFISystem Type = 0xef
VMWareFS Type = 0xfb
VMWareSwap Type = 0xfc
)
| package mbr
// Type constants for the GUID for type of partition, see https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_entries
type Type byte
// List of GUID partition types
const (
Empty Type = 0x00
Fat12 Type = 0x01
XenixRoot Type = 0x02
XenixUsr Type = 0x03
Fat16 Type = 0x04
ExtendedCHS Type = 0x05
Fat16b Type = 0x06
NTFS Type = 0x07
CommodoreFAT Type = 0x08
Fat32CHS Type = 0x0b
Fat32LBA Type = 0x0c
Fat16bLBA Type = 0x0e
ExtendedLBA Type = 0x0f
Linux Type = 0x83
LinuxExtended Type = 0x85
LinuxLVM Type = 0x8e
Iso9660 Type = 0x96
MacOSXUFS Type = 0xa8
MacOSXBoot Type = 0xab
HFS Type = 0xaf
Solaris8Boot Type = 0xbe
GPTProtective Type = 0xef
EFISystem Type = 0xef
VMWareFS Type = 0xfb
VMWareSwap Type = 0xfc
)
|
Use setInnerText only which already solves XSS Attacks (Avoid duplication) | package gwt.material.design.client.base.mixin;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 GwtBootstrap3
* %%
* 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.
* #L%
*/
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.UIObject;
/**
* @author Ben Dol
*/
public class TextMixin<T extends UIObject> extends AbstractMixin<T> {
public TextMixin(final T uiObject) {
super(uiObject);
}
public String getText() {
return uiObject.getElement().getInnerText();
}
public void setText(final String text) {
uiObject.getElement().setInnerText(text);
}
}
| package gwt.material.design.client.base.mixin;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 GwtBootstrap3
* %%
* 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.
* #L%
*/
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.UIObject;
/**
* @author Ben Dol
*/
public class TextMixin<T extends UIObject> extends AbstractMixin<T> {
public TextMixin(final T uiObject) {
super(uiObject);
}
public String getText() {
return uiObject.getElement().getInnerText();
}
public void setText(final String text) {
uiObject.getElement().setInnerText(text != null ? SafeHtmlUtils.htmlEscape(text) : "");
}
}
|
Fix finish step submiting on the installer | <?php
use Installer\App;
use Installer\Models\ConfirmForm;
$action = isset($_POST['actionName']) ? trim($_POST['actionName']) : '';
$model = new ConfirmForm($this);
$model->run($action);
?>
<div class="alert alert-danger hidden" id="error">
<div class="error-message"></div>
<div>
<a href="#" class="error-page-url">Перейти</a>
</div>
</div>
<ul id="actions" class="install-actions list-group"></ul>
<form action="" method="post" id="confirm-form">
<a class="btn btn-default" href="<?= App::$app->createUrl(['page' => 'config']) ?>">
<span class="glyphicon glyphicon-chevron-left"></span>
<?= App::t('Back') ?>
</a>
<button class="btn btn-primary" type="submit" name="submit">
<?= App::t('Install') ?>
</button>
</form>
| <?php
use Installer\App;
use Installer\Models\ConfirmForm;
if (isset($_POST['back'])) {
header('Location: ' . App::$app->createUrl(['page' => 'config']));
exit;
}
$action = isset($_POST['actionName']) ? trim($_POST['actionName']) : '';
$model = new ConfirmForm($this);
$model->run($action);
?>
<div class="alert alert-danger hidden" id="error">
<div class="error-message"></div>
<div>
<a href="#" class="error-page-url">Перейти</a>
</div>
</div>
<ul id="actions" class="install-actions list-group"></ul>
<form action="" method="post" id="confirm-form">
<button class="btn btn-default" type="submit" name="back">
<span class="glyphicon glyphicon-chevron-left"></span>
<?= App::t('Back') ?>
</button>
<button class="btn btn-primary" type="submit" name="submit">
<?= App::t('Install') ?>
</button>
</form>
|
Fix an atom version check oopsie | const semver = require('semver');
const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.13.0';
if (atom.inDevMode() || atom.inSpecMode() || semver.satisfies(atomVersion, requiredVersion)) {
module.exports = startPackage();
} else {
module.exports = versionMismatch();
}
function versionMismatch() {
return {
activate: () => {
atom.notifications.addWarning('Incompatible Atom Version', {
description: 'The GitHub packages requires Atom ' + requiredVersion +
'. You are running ' + atomVersion + '. Please check for updates and try again.',
dismissable: true,
});
},
};
}
function startPackage() {
const GithubPackage = require('./github-package').default;
return new GithubPackage(
atom.workspace, atom.project, atom.commands, atom.notifications,
);
}
| import semver from 'semver';
const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.13.0';
if (atom.inDevMode() || atom.inSpecMode() || semver.satisfies(atomVersion, requiredVersion)) {
module.exports = startPackage();
} else {
module.exports = versionMismatch();
}
function versionMismatch() {
return {
activate: () => {
atom.notifications.addWarning('Incompatible Atom Version', {
description: `The GitHub packages requires Atom ${requiredVersion}. You are running ${atomVersion}.`,
dismissable: true,
});
},
};
}
function startPackage() {
const GithubPackage = require('./github-package').default;
return new GithubPackage(
atom.workspace, atom.project, atom.commands, atom.notifications,
);
}
|
Use CUnicode for width and height in ImageWidget | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = CUnicode(sync=True)
height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = Unicode(sync=True) # TODO: C unicode
height = Unicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) |
Indent only (PEP8) commit of simple counter. | # Copyright 2008 Google Inc.
#
# 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.
#
"""A module implementing a simple sharded counter."""
import random
from google.appengine.ext import ndb
NUM_SHARDS = 20
class SimpleCounterShard(ndb.Model):
"""Shards for the counter"""
count = ndb.IntegerProperty(required=True, default=0)
def get_count():
"""Retrieve the value for a given sharded counter."""
total = 0
for counter in SimpleCounterShard.query():
total += counter.count
return total
@ndb.transactional
def increment():
"""Increment the value for a given sharded counter."""
shard_index = random.randint(0, NUM_SHARDS - 1)
counter = SimpleCounterShard.get_by_id(shard_index)
if counter is None:
counter = SimpleCounterShard(id=shard_index)
counter.count += 1
counter.put()
| # Copyright 2008 Google Inc.
#
# 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.
#
"""A module implementing a simple sharded counter."""
import random
from google.appengine.ext import ndb
NUM_SHARDS = 20
class SimpleCounterShard(ndb.Model):
"""Shards for the counter"""
count = ndb.IntegerProperty(required=True, default=0)
def get_count():
"""Retrieve the value for a given sharded counter."""
total = 0
for counter in SimpleCounterShard.query():
total += counter.count
return total
@ndb.transactional
def increment():
"""Increment the value for a given sharded counter."""
shard_index = random.randint(0, NUM_SHARDS - 1)
counter = SimpleCounterShard.get_by_id(shard_index)
if counter is None:
counter = SimpleCounterShard(id=shard_index)
counter.count += 1
counter.put()
|
Modify test to pass with two new DB rows | package uk.ac.ebi.atlas.dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.inject.Inject;
import java.util.Map;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:solrContextIT.xml", "classpath:oracleContext.xml"})
public class OrganismEnsemblDAOIT {
@Inject
private OrganismEnsemblDAO subject;
@Test
public void getOrganismEnsemblNamesMap() throws Exception {
Map<String, String> organismEnsemblNames = subject.getEnsemblOrganismNamesMap();
assertThat(organismEnsemblNames.get("homo sapiens"), is("ensembl"));
assertThat(organismEnsemblNames.get("mus musculus"), is("ensembl"));
assertThat(organismEnsemblNames.size(), is(33));
assertThat(organismEnsemblNames.get("arabidopsis thaliana"), is("plants"));
}
}
| package uk.ac.ebi.atlas.dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.inject.Inject;
import java.util.Map;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:solrContextIT.xml", "classpath:oracleContext.xml"})
public class OrganismEnsemblDAOIT {
@Inject
private OrganismEnsemblDAO subject;
@Test
public void getOrganismEnsemblNamesMap() throws Exception {
Map<String, String> organismEnsemblNames = subject.getEnsemblOrganismNamesMap();
assertThat(organismEnsemblNames.get("homo sapiens"), is("ensembl"));
assertThat(organismEnsemblNames.get("mus musculus"), is("ensembl"));
assertThat(organismEnsemblNames.size(), is(31));
assertThat(organismEnsemblNames.get("arabidopsis thaliana"), is("plants"));
}
}
|
Update view for basic quote form. | from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self):
form = super(QuoteCreateView, self).get_form()
# form.fields['category'].queryset = Category.objects.all()
# form.fields['products'].queryset = Product.objects.all()
return form
def form_valid(self, form):
form.instance.user = self.request.user
return super(QuoteCreateView, self).form_valid(form)
class QuoteEditView(UpdateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self):
form = super(QuoteEditView, self).get_form()
form.fields['category'].queryset = Category.objects.all()
form.fields['products'].queryset = Product.objects.all()
return form
def form_valid(self, form):
form.instance.user = self.request.user
return super(QuoteEditView, self).form_valid(form)
| from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self, form):
form = super(QuoteCreateView, self).get_form()
form.fields['category'].queryset = Category.objects.all()
form.fields['products'].queryset = Product.objects.all()
return form
def form_valid(self, form):
form.instance.user = self.request.user
return super(QuoteCreateView, self).form_valid(form)
class QuoteEditView(UpdateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self, form):
form = super(QuoteEditView, self).get_form()
form.fields['category'].queryset = Category.objects.all()
form.fields['products'].queryset = Product.objects.all()
return form
def form_valid(self, form):
form.instance.user = self.request.user
return super(QuoteEditView, self).form_valid(form)
|
Switch search radius back to 150 | 'use strict';
const boom = require('boom');
const express = require('express');
const knex = require('../knex');
const { camelizeKeys, decamelizeKeys } = require('humps');
const jwt = require('jsonwebtoken');
const request = require('request-promise');
const router = express.Router(); //eslint-disable-line new-cap
router.get('/api/places/:location', (req, res, next) => {
const { location } = req.params
request({ uri:
`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location}&radius=150&type=bar&key=AIzaSyAFgyrpeZwrVMRD9zu5o8qNFOVH6FlO1Ps`,
json: true })
.then((response) => {
if (response.results.length === 0) {
throw boom.create(400, 'There are no bars in your area. Try again later.');
}
const bars = response.results.map((bar) => {
const name = bar.name;
const placeId = bar.place_id;
return { name, placeId };
});
return res.send(bars)
})
.catch((err) => {
next(boom.wrap(err));
});
})
module.exports = router;
| 'use strict';
const boom = require('boom');
const express = require('express');
const knex = require('../knex');
const { camelizeKeys, decamelizeKeys } = require('humps');
const jwt = require('jsonwebtoken');
const request = require('request-promise');
const router = express.Router(); //eslint-disable-line new-cap
router.get('/api/places/:location', (req, res, next) => {
const { location } = req.params
request({ uri:
`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location}&radius=10000&type=bar&key=AIzaSyAFgyrpeZwrVMRD9zu5o8qNFOVH6FlO1Ps`,
json: true })
.then((response) => {
if (response.results.length === 0) {
throw boom.create(400, 'There are no bars in your area. Try again later.');
}
const bars = response.results.map((bar) => {
const name = bar.name;
const placeId = bar.place_id;
return { name, placeId };
});
return res.send(bars)
})
.catch((err) => {
next(boom.wrap(err));
});
})
module.exports = router;
|
Remove title from api pages | @extends ('base')
@section ('scripts')
<script type="text/javascript" src="{{ asset('/js/api.js') }}"></script>
@stop
@section('subheader')
@stop
@section ('content')
@if ($isError)
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<div class="alert alert-danger">
Whoops! Something went terribly wrong here!
</div>
</div>
</div>
@endif
<div class="row">
<div class="">
@include('transfugio::api.sidebar')
</div>
<div class="row-item--grow-2">
@include('transfugio::api.main')
</div>
</div>
@if (isset($paginationCode))
<div class="row text-center">
{!! $paginationCode or '' !!}
</div>
@endif
@stop
| @extends ('base')
@section ('scripts')
<script type="text/javascript" src="{{ asset('/js/api.js') }}"></script>
@stop
@section('subheader')
<div class="col-xs-12 col-md-4 col-md-offset-4">
<h2>@lang('app.demo.title')</h2>
</div>
@stop
@section ('content')
@if ($isError)
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<div class="alert alert-danger">
Whoops! Something went terribly wrong here!
</div>
</div>
</div>
@endif
<div class="row">
<div class="">
@include('transfugio::api.sidebar')
</div>
<div class="row-item--grow-2">
@include('transfugio::api.main')
</div>
</div>
@if (isset($paginationCode))
<div class="row text-center">
{!! $paginationCode or '' !!}
</div>
@endif
@stop
|
Add new image to hug interaction | package com.avairebot.orion.commands.interaction;
import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.InteractionCommand;
import java.util.Arrays;
import java.util.List;
public class HugCommand extends InteractionCommand {
public HugCommand(Orion orion) {
super(orion, "hugs");
}
@Override
public List<String> getInteractionImages() {
return Arrays.asList(
"https://i.imgur.com/aBdIEEu.gif",
"https://i.imgur.com/03grRGj.gif",
"https://i.imgur.com/EuIBiLi.gif",
"https://i.imgur.com/8KgVR9j.gif",
"https://i.imgur.com/ZepPo0t.gif"
);
}
@Override
public String getName() {
return "Hug Command";
}
@Override
public List<String> getTriggers() {
return Arrays.asList("hug", "hugs");
}
}
| package com.avairebot.orion.commands.interaction;
import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.InteractionCommand;
import java.util.Arrays;
import java.util.List;
public class HugCommand extends InteractionCommand {
public HugCommand(Orion orion) {
super(orion, "hugs");
}
@Override
public List<String> getInteractionImages() {
return Arrays.asList(
"https://i.imgur.com/aBdIEEu.gif",
"https://i.imgur.com/03grRGj.gif",
"https://i.imgur.com/EuIBiLi.gif",
"https://i.imgur.com/8KgVR9j.gif"
);
}
@Override
public String getName() {
return "Hug Command";
}
@Override
public List<String> getTriggers() {
return Arrays.asList("hug", "hugs");
}
}
|
Use a simpler trace logger that does not prepend timestamps | #!/usr/bin/python
# Copyright (c) 2006 rPath, Inc
# All rights reserved
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary.repository.netrepos.netserver import ServerConfig
from conary import dbstore
class SimpleFileLog(tracelog.FileLog):
def printLog(self, level, msg):
self.fd.write("%s\n" % msg)
cnrPath = '/srv/conary/repository.cnr'
cfg = ServerConfig()
tracelog.FileLog = SimpleFileLog
tracelog.initLog(filename='stderr', level=2)
try:
cfg.read(cnrPath)
except cfgtypes.CfgEnvironmentError:
print "Error reading %s" % cnrPath
sys.exit(1)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
| #!/usr/bin/python
# Copyright (c) 2006 rPath, Inc
# All rights reserved
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary.repository.netrepos.netserver import ServerConfig
from conary import dbstore
cnrPath = '/srv/conary/repository.cnr'
cfg = ServerConfig()
tracelog.initLog(filename='stderr', level=2)
try:
cfg.read(cnrPath)
except cfgtypes.CfgEnvironmentError:
print "Error reading %s" % cnrPath
sys.exit(1)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
|
Add yaml to requires list | #!/usr/bin/env python2
from distutils.core import setup
setup(
name = 'periodical',
description = 'Create a Kindle periodical from given URL(s)',
version = '0.1.0',
author = 'Tom Vincent',
author_email = 'http://tlvince.com/contact/',
url = 'https://github.com/tlvince/periodical',
license = 'MIT',
scripts = ['src/periodical.py'],
requires = ['beautifulsoup4', 'boilerpipe', 'yaml'],
classifiers = [
'Programming Language :: Python :: 2',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Topic :: Office/Business',
'Topic :: Text Processing :: Markup :: HTML',
]
)
| #!/usr/bin/env python2
from distutils.core import setup
setup(
name = 'periodical',
description = 'Create a Kindle periodical from given URL(s)',
version = '0.1.0',
author = 'Tom Vincent',
author_email = 'http://tlvince.com/contact/',
url = 'https://github.com/tlvince/periodical',
license = 'MIT',
scripts = ['src/periodical.py'],
requires = ['beautifulsoup4', 'boilerpipe'],
classifiers = [
'Programming Language :: Python :: 2',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Topic :: Office/Business',
'Topic :: Text Processing :: Markup :: HTML',
]
)
|
Increase tollerance for heat demand test | """
Test the electricity demand
SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de>
SPDX-FileCopyrightText: Patrik Schönfeldt
SPDX-License-Identifier: MIT
"""
import numpy as np
from demandlib.examples import heat_demand_example
def test_heat_example():
"""Test the results of the heat example."""
ann_demands_per_type = {'efh': 25000,
'mfh': 80000,
'ghd': 140000}
demands = heat_demand_example.heat_example(
ann_demands_per_type=ann_demands_per_type,
testmode=True).sum()
for key in ann_demands_per_type:
assert np.isclose(demands[key], ann_demands_per_type[key], rtol=1e-04)
| """
Test the electricity demand
SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de>
SPDX-FileCopyrightText: Patrik Schönfeldt
SPDX-License-Identifier: MIT
"""
import numpy as np
from demandlib.examples import heat_demand_example
def test_heat_example():
"""Test the results of the heat example."""
ann_demands_per_type = {'efh': 25000,
'mfh': 80000,
'ghd': 140000}
demands = heat_demand_example.heat_example(
ann_demands_per_type=ann_demands_per_type,
testmode=True).sum()
for key in ann_demands_per_type:
assert np.isclose(demands[key], ann_demands_per_type[key])
|
Use importlib.metadata to set __version__
This way we don't have to remember to update the version in two places
every release. The version will only need to be set in pyproject.toml | # coding:utf-8
"""
Function decoration for backoff and retry
This module provides function decorators which can be used to wrap a
function such that it will be retried until some condition is met. It
is meant to be of use when accessing unreliable resources with the
potential for intermittent failures i.e. network resources and external
APIs. Somewhat more generally, it may also be of use for dynamically
polling resources for externally generated content.
For examples and full documentation see the README at
https://github.com/litl/backoff
"""
import importlib.metadata
from backoff._decorator import on_exception, on_predicate
from backoff._jitter import full_jitter, random_jitter
from backoff._wait_gen import constant, expo, fibo, runtime
__all__ = [
'on_predicate',
'on_exception',
'constant',
'expo',
'fibo',
'runtime',
'full_jitter',
'random_jitter',
]
__version__ = importlib.metadata.version("backoff")
| # coding:utf-8
"""
Function decoration for backoff and retry
This module provides function decorators which can be used to wrap a
function such that it will be retried until some condition is met. It
is meant to be of use when accessing unreliable resources with the
potential for intermittent failures i.e. network resources and external
APIs. Somewhat more generally, it may also be of use for dynamically
polling resources for externally generated content.
For examples and full documentation see the README at
https://github.com/litl/backoff
"""
from backoff._decorator import on_predicate, on_exception
from backoff._jitter import full_jitter, random_jitter
from backoff._wait_gen import constant, expo, fibo, runtime
__all__ = [
'on_predicate',
'on_exception',
'constant',
'expo',
'fibo',
'runtime',
'full_jitter',
'random_jitter',
]
__version__ = '2.1.0'
|
Replace `@Nullable` with `@NotNull` since method actually always returns non-null value
GitOrigin-RevId: 4e67fd4f27ef4779939739b978c319a2aacbe78c | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.buildout.config;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.util.NlsSafe;
import icons.PythonIcons;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public final class BuildoutCfgFileType extends LanguageFileType {
public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType();
public static final @NlsSafe String DEFAULT_EXTENSION = "cfg";
private static final @NlsSafe String NAME = "BuildoutCfg";
private static final @NlsSafe String DESCRIPTION = "Buildout config";
private BuildoutCfgFileType() {
super(BuildoutCfgLanguage.INSTANCE);
}
@Override
@NotNull
public String getName() {
return NAME;
}
@Override
@NotNull
public String getDescription() {
return DESCRIPTION;
}
@Override
@NotNull
public String getDefaultExtension() {
return DEFAULT_EXTENSION;
}
@Override
@NotNull
public Icon getIcon() {
return PythonIcons.Python.Buildout.Buildout;
}
}
| // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.buildout.config;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.util.NlsSafe;
import icons.PythonIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public final class BuildoutCfgFileType extends LanguageFileType {
public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType();
public static final @NlsSafe String DEFAULT_EXTENSION = "cfg";
private static final @NlsSafe String NAME = "BuildoutCfg";
private static final @NlsSafe String DESCRIPTION = "Buildout config";
private BuildoutCfgFileType() {
super(BuildoutCfgLanguage.INSTANCE);
}
@Override
@NotNull
public String getName() {
return NAME;
}
@Override
@NotNull
public String getDescription() {
return DESCRIPTION;
}
@Override
@NotNull
public String getDefaultExtension() {
return DEFAULT_EXTENSION;
}
@Override
@Nullable
public Icon getIcon() {
return PythonIcons.Python.Buildout.Buildout;
}
}
|
Remove the uniqueness rule here as it prevented saving changes when the email address was not changed. | <?php
namespace App\Validation\EntityRules;
use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;
class UserRules extends AbstractEntityRules
{
/**
* Return an array of rules for validating Users
*
* @param object $entity
* @return array
*/
protected function buildRules($entity)
{
return [
'name' => 'bail|required|min:2',
'email' => 'bail|required|email',
'password' => 'present',
];
}
/**
* @return array
*/
public function messages()
{
return [
'name' => 'Name must be at least two characters long.',
'email' => 'A person with that email address is already registered.',
'password' => 'Your password should be at least 8 characters long.',
];
}
/**
* Define the entity that this validator supports
*
* @param object $entity
* @return bool
*/
public function supports($entity)
{
return $entity instanceof User;
}
} | <?php
namespace App\Validation\EntityRules;
use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;
class UserRules extends AbstractEntityRules
{
/**
* Return an array of rules for validating Users
*
* @param object $entity
* @return array
*/
protected function buildRules($entity)
{
return [
'name' => 'bail|required|min:2',
'email' => 'bail|required|email|unique:'. User::class .',email',
'password' => 'present',
];
}
/**
* @return array
*/
public function messages()
{
return [
'name' => 'Name must be at least two characters long.',
'email' => 'A person with that email address is already registered.',
'password' => 'Your password should be at least 8 characters long.',
];
}
/**
* Define the entity that this validator supports
*
* @param object $entity
* @return bool
*/
public function supports($entity)
{
return $entity instanceof User;
}
} |
Add popdb() and edit descriptions | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db, populate_db()
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '--cfgfile', dest='config_file', type=abspath)
@manager.command
def createdb():
with app.app_context():
"""Creates database"""
db.create_all()
print 'Database created'
@manager.command
def cleardb():
with app.app_context():
"""Deletes all database tables"""
db.drop_all()
print 'Database cleared'
@manager.command
def resetdb():
with app.app_context():
"""Removes all content from database"""
db.drop_all()
db.create_all()
print 'Database reset'
@manager.command
def initdb():
with app.app_context():
"""Initializes database with default values"""
db.drop_all()
db.create_all()
init_db()
print 'Database initialized'
@manager.command
def popdb():
with app.app_context():
"""Populates database with sample data"""
db.drop_all()
db.create_all()
init_db()
populate_db()
print 'Database populated'
if __name__ == '__main__':
manager.run()
| from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '--cfgfile', dest='config_file', type=abspath)
@manager.command
def createdb():
with app.app_context():
"""Creates database"""
db.create_all()
print 'Database created'
@manager.command
def cleardb():
with app.app_context():
"""Clears database"""
db.drop_all()
print 'Database cleared'
@manager.command
def resetdb():
with app.app_context():
"""Resets database"""
db.drop_all()
db.create_all()
print 'Database reset'
@manager.command
def initdb():
with app.app_context():
"""Initializes database with test data"""
if prompt_bool('Are you sure you want to replace all data?'):
init_db()
print 'Database initialized'
else:
print 'Database initialization aborted'
if __name__ == '__main__':
manager.run()
|
Add missing connection section type value HIGHLIGHT | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
| from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order'] |
Test Sami with empty config | <?php
namespace PhakeBuilder\Tests;
class SamiTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testUpdateException()
{
$sami = new \PhakeBuilder\Sami('foobar');
$sami->update('blah');
}
public function testUpdate()
{
$sami = new \PhakeBuilder\Sami('foobar');
$result = $sami->update(__FILE__);
$this->assertEquals('foobar update ' . __FILE__, $result, "Invalid sami command [$result]");
}
public function testUpdateDefaultConfig()
{
$sami = new \PhakeBuilder\Sami('foobar');
$result = $sami->update();
$this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
}
public function testUpdateEmptyConfig()
{
$sami = new \PhakeBuilder\Sami('foobar');
$result = $sami->update(array());
$this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
}
}
| <?php
namespace PhakeBuilder\Tests;
class SamiTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testUpdateException()
{
$sami = new \PhakeBuilder\Sami('foobar');
$sami->update('blah');
}
public function testUpdate()
{
$sami = new \PhakeBuilder\Sami('foobar');
$result = $sami->update(__FILE__);
$this->assertEquals('foobar update ' . __FILE__, $result, "Invalid sami command [$result]");
}
public function testUpdateDefaultConfig()
{
$sami = new \PhakeBuilder\Sami('foobar');
$result = $sami->update();
$this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
}
}
|
Fix test to wait for output | var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
var result = "";
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
result += data;
});
process.on('error', function (error) {
assert(false, error);
next();
});
process.on('close', function() {
assert(result.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
done();
});
});
});
| var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
assert(data.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
process.kill();
done();
});
process.on('error', function (error) {
assert(false, error);
next();
})
});
});
|
Add use null instead of savedInstanceState in ReactActivity | package com.msupplymobile;
import com.facebook.react.ReactActivity;
import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage;
import io.realm.react.RealmReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import android.os.Bundle;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class MainActivity extends ReactActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "mSupplyMobile";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
| package com.msupplymobile;
import com.facebook.react.ReactActivity;
import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage;
import io.realm.react.RealmReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import android.os.Bundle;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class MainActivity extends ReactActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "mSupplyMobile";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
|
Fix NPE on player join
Fixes #77 | package de.epiceric.shopchest.listeners;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.event.ShopUpdateEvent;
import de.epiceric.shopchest.shop.Shop;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class ShopUpdateListener implements Listener {
private ShopChest plugin;
public ShopUpdateListener(ShopChest plugin) {
this.plugin = plugin;
}
@EventHandler
public void onShopUpdate(ShopUpdateEvent e) {
for (Player p : Bukkit.getOnlinePlayers()) {
plugin.getShopUtils().updateShops(p, p.getLocation());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent e) {
for (Shop shop : plugin.getShopUtils().getShops()) {
if (shop.getHologram() != null) shop.getHologram().hidePlayer(e.getPlayer());
if (shop.getItem() != null) shop.getItem().setVisible(e.getPlayer(), false);
}
}
}
| package de.epiceric.shopchest.listeners;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.event.ShopUpdateEvent;
import de.epiceric.shopchest.shop.Shop;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class ShopUpdateListener implements Listener {
private ShopChest plugin;
public ShopUpdateListener(ShopChest plugin) {
this.plugin = plugin;
}
@EventHandler
public void onShopUpdate(ShopUpdateEvent e) {
for (Player p : Bukkit.getOnlinePlayers()) {
plugin.getShopUtils().updateShops(p, p.getLocation());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent e) {
for (Shop shop : plugin.getShopUtils().getShops()) {
shop.getHologram().hidePlayer(e.getPlayer());
shop.getItem().setVisible(e.getPlayer(), false);
}
}
}
|
feat: Put graph activity intent extras into fragment's arguments | package com.sam_chordas.android.stockhawk.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.sam_chordas.android.stockhawk.R;
/**
* Created by frano on 21/03/2016.
*/
public class LineGraphActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_graph);
if (savedInstanceState == null) {
Bundle arguments = new Bundle();
arguments.putString(getString(R.string.line_graph_extra),
getIntent().getStringExtra(getString(R.string.line_graph_extra)));
LineGraphFragment fragment = new LineGraphFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.stock_detail_container, fragment)
.commit();
}
}
}
| package com.sam_chordas.android.stockhawk.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.sam_chordas.android.stockhawk.R;
/**
* Created by frano on 21/03/2016.
*/
public class LineGraphActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_graph);
if (savedInstanceState == null) {
LineGraphFragment fragment = new LineGraphFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.stock_detail_container, fragment)
.commit();
}
}
}
|
Change default button ripple color to almost-black | import { createMuiTheme } from '@material-ui/core/styles'
// Theme
const primaryMainColor = '#9d4ba3'
const primaryContrastTextColor = '#fff'
const secondaryMainColor = '#4a90e2'
const secondaryContrastTextColor = '#fff'
const theme = createMuiTheme({
palette: {
primary: {
// light: will be calculated from palette.primary.main,
main: primaryMainColor,
// dark: will be calculated from palette.primary.main,
contrastText: primaryContrastTextColor
},
secondary: {
// light: will be calculated from palette.primary.main,
main: secondaryMainColor,
// dark: will be calculated from palette.primary.main,
contrastText: secondaryContrastTextColor
}
},
typography: {
fontSize: 14,
fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif'
},
overrides: {
MuiButtonBase: {
root: {
color: 'rgba(0, 0, 0, 0.87)'
}
},
MuiListSubheader: {
root: {
fontSize: 12,
textTransform: 'uppercase'
}
}
}
})
export default theme
| import { createMuiTheme } from '@material-ui/core/styles'
// Theme
const primaryMainColor = '#9d4ba3'
const primaryContrastTextColor = '#fff'
const secondaryMainColor = '#4a90e2'
const secondaryContrastTextColor = '#fff'
const theme = createMuiTheme({
palette: {
primary: {
// light: will be calculated from palette.primary.main,
main: primaryMainColor,
// dark: will be calculated from palette.primary.main,
contrastText: primaryContrastTextColor
},
secondary: {
// light: will be calculated from palette.primary.main,
main: secondaryMainColor,
// dark: will be calculated from palette.primary.main,
contrastText: secondaryContrastTextColor
}
},
typography: {
fontSize: 14,
fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif'
},
overrides: {
MuiButtonBase: {
root: {
color: primaryMainColor
}
},
MuiListSubheader: {
root: {
fontSize: 12,
textTransform: 'uppercase'
}
}
}
})
export default theme
|
Make showWait() available to other scripts. | var showWait = function() {
var selector = "run_link";
var waiting_id = null;
var counting_id = null;
var timer_dom = 'counter';
var wait_dom = 'please_wait';
var wait_secs = 20;
var counter = 0;
var hideWait = function() {
waiting_id = null;
clearInterval(counting_id);
counting_id = null;
$(timer_dom).update('completed');
$(wait_dom).hide();
}
var update_counter = function() {
$(timer_dom).update(counter);
counter = counter -1;
}
if (waiting_id || counting_id) {
return;
}
waiting_id = setTimeout(hideWait,wait_secs * 1000);
$(timer_dom).update(wait_secs);
counting_id = setInterval(update_counter,1000);
counter=wait_secs;
$(wait_dom).show();
};
document.observe("dom:loaded", function() {
$$(".run_link").each(function(item) {
item.observe("click", showWait);
});
});
| (function() {
var selector = "run_link";
var waiting_id = null;
var counting_id = null;
var timer_dom = 'counter';
var wait_dom = 'please_wait';
var wait_secs = 20;
var counter = 0;
var hideWait = function() {
waiting_id = null;
clearInterval(counting_id);
counting_id = null;
$(timer_dom).update('completed');
$(wait_dom).hide();
}
var update_counter = function() {
$(timer_dom).update(counter);
counter = counter -1;
}
var showWait = function() {
if (waiting_id || counting_id) {
return;
}
waiting_id = setTimeout(hideWait,wait_secs * 1000);
$(timer_dom).update(wait_secs);
counting_id = setInterval(update_counter,1000);
counter=wait_secs;
$(wait_dom).show();
};
document.observe("dom:loaded", function() {
$$("." + selector).each(function(item) {
item.observe("click", showWait);
});
});
}());
|
Reset timer reference when timer is stopped
- Not resetting it make the timer not start
the next time
Signed-off-by: Felipe Milani <6def120dcec8fcb28aed4723fac713cfff66d853@gmail.com> | import { compose, withHandlers, withState } from 'recompose';
import moment from 'moment';
/**
* Higher order component that gives a 'now' prop that indicates the current
* time, a handler to keep udpating it and a handler to stop the update.
*/
const withTimer = compose(
withState('now', 'updateNow', moment().toDate()),
withState('timer', 'updateTimer', null),
withHandlers({
startTimer: ({ timer, updateNow, updateTimer }) => () => {
if (timer) {
// we don't want to start a new timer if we already have
// one running =)
return;
}
updateNow(moment().toDate());
updateTimer(setInterval(() => updateNow(moment().toDate()), 100));
},
stopTimer: ({ timer, updateTimer }) => () => {
if (timer) {
clearInterval(timer);
updateTimer(null);
}
},
}),
);
export default withTimer;
| import { compose, withHandlers, withState } from 'recompose';
import moment from 'moment';
/**
* Higher order component that gives a 'now' prop that indicates the current
* time, a handler to keep udpating it and a handler to stop the update.
*/
const withTimer = compose(
withState('now', 'updateNow', moment().toDate()),
withState('timer', 'updateTimer', null),
withHandlers({
startTimer: ({ timer, updateNow, updateTimer }) => () => {
if (timer) {
// we don't want to start a new timer if we already have
// one running =)
return;
}
updateNow(moment().toDate());
updateTimer(setInterval(() => updateNow(moment().toDate()), 1000));
},
stopTimer: ({ timer }) => () => {
if (timer) {
clearInterval(timer);
}
},
}),
);
export default withTimer;
|
Set decodeEntities to false for cheerio. | 'use strict';
var mediaQueryText = require('mediaquery-text'),
cheerio = require('cheerio');
module.exports = function (html, options, callback) {
var results = {},
$ = cheerio.load(html, {
decodeEntities: false
}),
styleDataList,
styleData;
results.css = [];
$('style').each(function (index, element) {
styleDataList = element.childNodes;
if (styleDataList.length !== 1) {
callback(new Error('empty style element'));
return;
}
styleData = styleDataList[0].data;
if (options.applyStyleTags) {
results.css.push(styleData);
}
if (options.removeStyleTags) {
if (options.preserveMediaQueries) {
var mediaQueries = mediaQueryText(element.childNodes[0].nodeValue);
element.childNodes[0].nodeValue = mediaQueries;
} else {
$(element).remove();
}
}
});
results.html = $.html();
callback(null, results);
};
| 'use strict';
var mediaQueryText = require('mediaquery-text'),
cheerio = require('cheerio');
module.exports = function (html, options, callback) {
var results = {},
$ = cheerio.load(html),
styleDataList,
styleData;
results.css = [];
$('style').each(function (index, element) {
styleDataList = element.childNodes;
if (styleDataList.length !== 1) {
callback(new Error('empty style element'));
return;
}
styleData = styleDataList[0].data;
if (options.applyStyleTags) {
results.css.push(styleData);
}
if (options.removeStyleTags) {
if (options.preserveMediaQueries) {
var mediaQueries = mediaQueryText(element.childNodes[0].nodeValue);
element.childNodes[0].nodeValue = mediaQueries;
} else {
$(element).remove();
}
}
});
results.html = $.html();
callback(null, results);
};
|
Add management of the popup hide callback. |
"use strict";
function $(id) {
return document.getElementById(id);
}
// This is here because setTimeout() doesn't seem to call member functions correctly
function Hide(popupManager)
{
popupManager.HidePopup();
}
var popUpDuration = 3000;
define( [
],
function (
) {
var PopUpManager = function (services) {
this.services = services;
this.hideTimeoutID = 0;
this.overlay = $("overlay");
this.line1 = $("overlay-line1");
this.line2 = $("overlay-line2");
this.HidePopup();
};
PopUpManager.prototype.CreatePopUp = function(line1, line2)
{
this.line1.childNodes[0].data = line1;
this.line2.childNodes[0].data = line2;
this.ShowPopUp();
clearTimeout( this.hideTimeoutID );
this.hideTimeoutID = setTimeout( Hide, popUpDuration, this );
}
PopUpManager.prototype.ShowPopUp = function()
{
this.overlay.style.visibility = 'visible';
}
PopUpManager.prototype.HidePopup = function()
{
this.overlay.style.visibility = 'hidden';
}
return PopUpManager;
});
|
"use strict";
function $(id) {
return document.getElementById(id);
}
// This is here because setTimeout() doesn't seem to call member functions correctly
function Hide(popupManager)
{
popupManager.HidePopup();
}
var popUpDuration = 10000;
define( [
],
function (
) {
var PopUpManager = function (services) {
this.services = services;
this.overlay = $("overlay");
this.line1 = $("overlay-line1");
this.line2 = $("overlay-line2");
this.HidePopup();
};
PopUpManager.prototype.CreatePopUp = function(line1, line2)
{
this.line1.childNodes[0].data = line1;
this.line2.childNodes[0].data = line2;
this.ShowPopUp();
setTimeout( Hide, popUpDuration, this );
}
PopUpManager.prototype.ShowPopUp = function()
{
this.overlay.style.visibility = 'visible';
}
PopUpManager.prototype.HidePopup = function()
{
this.overlay.style.visibility = 'hidden';
}
return PopUpManager;
});
|
title: Mark `narrow` param optional in `getIsInTopicOrStreamNarrow`.
Because `isStreamNarrow` and `isTopicNarrow` handle this case and
return false, this function does the same.
In fact, we already call it with `narrow` undefined: it's called by
`getTitleBackgroundColor` and `getTitleTextColor`, which can be called
from any screen, so if it is not chat screen then narrow will be
undefined. So fix the type signature to reflect that. | /* @flow */
import { createSelector } from 'reselect';
import type { Narrow } from '../types';
import { BRAND_COLOR } from '../styles';
import { getSubscriptions } from '../directSelectors';
import { getCurrentRouteName } from '../nav/navSelectors';
import { foregroundColorFromBackground } from '../utils/color';
import { isStreamNarrow, isTopicNarrow } from '../utils/narrow';
import { NULL_SUBSCRIPTION } from '../nullObjects';
export const getIsInTopicOrStreamNarrow = (narrow?: Narrow) =>
createSelector(
getCurrentRouteName,
routeName => (routeName === 'chat' ? isStreamNarrow(narrow) || isTopicNarrow(narrow) : false),
);
export const getTitleBackgroundColor = (narrow: Narrow) =>
createSelector(
getSubscriptions,
getIsInTopicOrStreamNarrow(narrow),
(subscriptions, isInTopicOrStreamNarrow) =>
isInTopicOrStreamNarrow
? (subscriptions.find(sub => narrow[0].operand === sub.name) || NULL_SUBSCRIPTION).color
: 'transparent',
);
export const getTitleTextColor = (narrow: Narrow) =>
createSelector(
getTitleBackgroundColor(narrow),
getIsInTopicOrStreamNarrow(narrow),
(backgroundColor, isInTopicOrStreamNarrow) =>
backgroundColor && isInTopicOrStreamNarrow
? foregroundColorFromBackground(backgroundColor)
: BRAND_COLOR,
);
| /* @flow */
import { createSelector } from 'reselect';
import type { Narrow } from '../types';
import { BRAND_COLOR } from '../styles';
import { getSubscriptions } from '../directSelectors';
import { getCurrentRouteName } from '../nav/navSelectors';
import { foregroundColorFromBackground } from '../utils/color';
import { isStreamNarrow, isTopicNarrow } from '../utils/narrow';
import { NULL_SUBSCRIPTION } from '../nullObjects';
export const getIsInTopicOrStreamNarrow = (narrow: Narrow) =>
createSelector(
getCurrentRouteName,
routeName => (routeName === 'chat' ? isStreamNarrow(narrow) || isTopicNarrow(narrow) : false),
);
export const getTitleBackgroundColor = (narrow: Narrow) =>
createSelector(
getSubscriptions,
getIsInTopicOrStreamNarrow(narrow),
(subscriptions, isInTopicOrStreamNarrow) =>
isInTopicOrStreamNarrow
? (subscriptions.find(sub => narrow[0].operand === sub.name) || NULL_SUBSCRIPTION).color
: 'transparent',
);
export const getTitleTextColor = (narrow: Narrow) =>
createSelector(
getTitleBackgroundColor(narrow),
getIsInTopicOrStreamNarrow(narrow),
(backgroundColor, isInTopicOrStreamNarrow) =>
backgroundColor && isInTopicOrStreamNarrow
? foregroundColorFromBackground(backgroundColor)
: BRAND_COLOR,
);
|
api: Fix need to manually update list of integrations.
(imported from commit 6842230f939483d32acb023ad38c53cb627df149) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
import os.path
from distutils.core import setup
setup(name='humbug',
version=humbug.__version__,
description='Bindings for the Humbug message API',
author='Humbug, Inc.',
author_email='humbug@humbughq.com',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Communications :: Chat',
],
url='https://humbughq.com/dist/api/',
packages=['humbug'],
data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \
[(os.path.join('share/humbug/', relpath),
glob.glob(os.path.join(relpath, '*'))) for relpath in
glob.glob("integrations/*")
],
scripts=["bin/humbug-send"],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
from distutils.core import setup
setup(name='humbug',
version=humbug.__version__,
description='Bindings for the Humbug message API',
author='Humbug, Inc.',
author_email='humbug@humbughq.com',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Communications :: Chat',
],
url='https://humbughq.com/dist/api/',
packages=['humbug'],
data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"]),
('share/humbug/integrations/trac', glob.glob('integrations/trac/*')),
('share/humbug/integrations/nagios', glob.glob('integrations/nagios/*')),
],
scripts=["bin/humbug-send"],
)
|
Load it once, not every time, Jeeves. | #!/usr/bin/env node
var updater = require('update-notifier'),
pkg = require('../package.json');
updater({pkg: pkg}).notify();
var yargs = require('yargs')
.option('registry', {
description: 'fully-qualified hostname of the registry to use',
default: 'registry.npmjs.org'
})
.help('help')
.version(function() { return require('../package').version; })
.describe('version', 'show version information')
.usage('the helpful wombat tool');
var requireDirectory = require('require-directory'),
commands = requireDirectory(module, '../commands');
Object.keys(commands).forEach(function(c)
{
var cmd = commands[c];
yargs.command(commands[c]);
if (cmd.aliases)
{
cmd.aliases.forEach(function(alias) { yargs.command(alias, false, cmd); });
}
});
var argv = yargs.argv;
// wombat : npm :: hub : git
if (!argv._handled)
{
var spawn = require('child_process').spawn;
var opts = {
cwd: process.cwd,
env: process.env,
stdio: 'inherit',
};
var original = process.argv.slice(2);
spawn('npm', original, opts);
}
| #!/usr/bin/env node
var updater = require('update-notifier'),
pkg = require('../package.json');
updater({pkg: pkg}).notify();
var yargs = require('yargs')
.option('registry', {
description: 'fully-qualified hostname of the registry to use',
default: 'registry.npmjs.org'
})
.help('help')
.version(function() { return require('../package').version; })
.describe('version', 'show version information')
.usage('the helpful wombat tool');
var requireDirectory = require('require-directory'),
commands = requireDirectory(module, '../commands');
Object.keys(commands).forEach(function(c)
{
var cmd = commands[c];
yargs.command(commands[c]);
if (cmd.aliases)
{
cmd.aliases.forEach(function(alias) { yargs.command(cmd).command(alias, false, cmd); });
}
});
var argv = yargs.argv;
// wombat : npm :: hub : git
if (!argv._handled)
{
var spawn = require('child_process').spawn;
var opts = {
cwd: process.cwd,
env: process.env,
stdio: 'inherit',
};
var original = process.argv.slice(2);
spawn('npm', original, opts);
}
|
Add support for Android TV YouTube app | package com.peterjosling.scroball.transforms;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;
import java.util.Collection;
import java.util.List;
public class MetadataTransformers {
private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();
private static final List<MetadataTransform> VIDEO_TRANSFORMS =
ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER);
private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
ImmutableMultimap.<String, MetadataTransform>builder()
.putAll("com.google.android.youtube", VIDEO_TRANSFORMS)
.putAll("com.google.android.youtube.tv", VIDEO_TRANSFORMS)
.build();
public Track transformForPackageName(String packageName, Track track) {
Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);
for (MetadataTransform transform : transforms) {
track = transform.transform(track);
}
return track;
}
}
| package com.peterjosling.scroball.transforms;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;
import java.util.Collection;
public class MetadataTransformers {
private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();
private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
ImmutableMultimap.<String, MetadataTransform>builder()
.putAll(
"com.google.android.youtube", ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER))
.build();
public Track transformForPackageName(String packageName, Track track) {
Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);
for (MetadataTransform transform : transforms) {
track = transform.transform(track);
}
return track;
}
}
|
Remove the --env default setting, it's not needed when testing a command | <?php
namespace ParaunitTestCase\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* Class ParaunitCommandTestCase
* @package ParaunitTestCase\TestCase
*/
abstract class ParaunitCommandTestCase extends ParaunitWebTestCase
{
/**
* Runs a command and returns it output
*
* @param ContainerAwareCommand $command
* @param array $input
* @return string
*/
public function runCommandTesterAndReturnOutput(ContainerAwareCommand $command, array $input = [])
{
$kernel = self::createKernel();
$kernel->boot();
$application = new Application($kernel);
$application->add($command);
$container = $kernel->getContainer();
$this->injectManagersInContainer($container);
$command->setContainer($container);
$input['command'] = $command->getName();
$tester = new CommandTester($command);
$tester->execute($input);
return $tester->getDisplay();
}
}
| <?php
namespace ParaunitTestCase\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* Class ParaunitCommandTestCase
* @package ParaunitTestCase\TestCase
*/
abstract class ParaunitCommandTestCase extends ParaunitWebTestCase
{
/**
* Runs a command and returns it output
*
* @param ContainerAwareCommand $command
* @param array $input
* @return string
*/
public function runCommandTesterAndReturnOutput(ContainerAwareCommand $command, array $input = [])
{
$kernel = self::createKernel();
$kernel->boot();
$application = new Application($kernel);
$application->add($command);
$container = $kernel->getContainer();
$this->injectManagersInContainer($container);
$command->setContainer($container);
$input['command'] = $command->getName();
$input['--env'] = isset($input['--env']) ? $input['--env'] : 'test';
$tester = new CommandTester($command);
$tester->execute($input);
return $tester->getDisplay();
}
}
|
Use config.log for print added in last commit | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChildren()
if cnames.count(SKOLEBESTYELSE_NAME):
config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']')
cnames.remove(SKOLEBESTYELSE_NAME)
for cname in cnames:
skoleintra.schildren.skoleSelectChild(cname)
skoleintra.pgContactLists.skoleContactLists()
skoleintra.pgFrontpage.skoleFrontpage()
skoleintra.pgDialogue.skoleDialogue()
skoleintra.pgDocuments.skoleDocuments()
skoleintra.pgWeekplans.skoleWeekplans()
| #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChildren()
if cnames.count(SKOLEBESTYELSE_NAME):
print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']'
cnames.remove(SKOLEBESTYELSE_NAME)
for cname in cnames:
skoleintra.schildren.skoleSelectChild(cname)
skoleintra.pgContactLists.skoleContactLists()
skoleintra.pgFrontpage.skoleFrontpage()
skoleintra.pgDialogue.skoleDialogue()
skoleintra.pgDocuments.skoleDocuments()
skoleintra.pgWeekplans.skoleWeekplans()
|
Use another way to set title. | define([
'lib/underscore',
'lib/backbone',
'component/grid/projection/base',
], function (_, Backbone, BaseProjection) {
var Model = BaseProjection.extend({
name: 'column-hovertext',
update: function (options) {
if (Model.__super__.update.call(this, options)) {
var model = this.src.data;
var columns = model.get('columns');
_.each(columns, function(column) {
column.$metadata = _.result(column, '$metadata', {});
column.$metadata['attr.head'] = _.result(column.$metadata, 'attr.head', {});
column.$metadata['attr.head'].title = _.result(column.config, 'hoverText') || _.result(column.config, 'title') || '';
});
this.patch({ columns: columns });
}
},
});
return Model;
});
| define([
'lib/underscore',
'lib/backbone',
'component/grid/projection/base',
], function (_, Backbone, BaseProjection) {
var Model = BaseProjection.extend({
name: 'column-hovertext',
update: function (options) {
if (Model.__super__.update.call(this, options)) {
var model = this.src.data;
var columns = model.get('columns');
_.each(columns, function(column) {
_.extend(column, {
$metadata: {
'attr.head': {
title: _.result(column.config, 'hoverText') || _.result(column.config, 'title') || '',
},
},
});
});
this.patch({ columns: columns });
}
},
});
return Model;
});
|
Check if menu exists before attaching events to it. | window.addEventListener("load", function(event) {
var menu = document.getElementById("contentAreaContextMenu");
if (menu) {
menu.addEventListener("popupshowing", setupMenuItems, false);
}
}, false);
function setupMenuItems(event) {
var menuItems = ['window', 'tab'];
for (var i=0; i < menuItems.length; i++) {
var item = document.getElementById('imgctrl-' + menuItems[i]);
item.hidden = !gContextMenu.onImage;
}
}
function imgctrl(where) {
var url = gContextMenu.imageURL || gContextMenu.mediaURL;
switch(where) {
case "window":
window.open(url);
break;
default:
window.getBrowser().addTab(url);
}
} | window.addEventListener("load", function(event) {
var menu = document.getElementById("contentAreaContextMenu");
menu.addEventListener("popupshowing", setupMenuItems, false);
}, false);
function setupMenuItems(event) {
var menuItems = ['window', 'tab'];
for (var i=0; i < menuItems.length; i++) {
var item = document.getElementById('imgctrl-' + menuItems[i]);
item.hidden = !gContextMenu.onImage;
}
}
function imgctrl(where) {
var url = gContextMenu.imageURL || gContextMenu.mediaURL;
switch(where) {
case "window":
window.open(url);
break;
default:
window.getBrowser().addTab(url);
}
} |
Fix PHP notice on query parameter without equals sign | <?
/*
Add license block if adding additional code
*/
class Zotero_URL {
/**
* By Evan K on http://us.php.net/manual/en/function.parse-str.php
*/
public static function proper_parse_str($str) {
if (!$str) {
return array();
}
$arr = array();
$pairs = explode('&', $str);
foreach ($pairs as $i) {
// Skip if no equals sign
if (strpos($i, '=') === false) {
continue;
}
list($name, $value) = explode('=', $i, 2);
// Skip if empty value
if (!$value && $value !== '0') {
continue;
}
// Added by Dan S.
$value = urldecode($value);
// if name already exists
if (isset($arr[$name])) {
// stick multiple values into an array
if (is_array($arr[$name])) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
// otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
return $arr;
}
}
| <?
/*
Add license block if adding additional code
*/
class Zotero_URL {
/**
* By Evan K on http://us.php.net/manual/en/function.parse-str.php
*/
public static function proper_parse_str($str) {
if (!$str) {
return array();
}
$arr = array();
$pairs = explode('&', $str);
foreach ($pairs as $i) {
list($name, $value) = explode('=', $i, 2);
// Empty value
if (!$value && $value !== '0') {
continue;
}
// Added by Dan S.
$value = urldecode($value);
// if name already exists
if (isset($arr[$name])) {
// stick multiple values into an array
if (is_array($arr[$name])) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
// otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
return $arr;
}
}
|
Make it work with proper import again. | /* eslint-disable no-undef */
import { fork, call, select } from 'redux-saga/effects';
import { isIos } from 'worona-deps';
import * as deps from '../deps';
function* redirectHome() {
const contentType = yield select(deps.selectors.getContentType);
if (contentType === 'Home') {
const { type, category, page } = yield select(
deps.selectorCreators.getSetting('theme', 'frontPage'),
);
if (type === 'category') {
yield call(deps.libs.push, `?cat=${category}`);
} else if (type === 'page') {
yield call(deps.libs.push, `?page_id=${page}`);
}
}
}
function hideIosStatusBar() {
if (isIos && StatusBar) {
StatusBar.hide();
}
}
export default function* starterProSagas() {
yield [
fork(redirectHome),
fork(hideIosStatusBar),
];
}
| /* eslint-disable no-undef */
import { fork, call, select } from 'redux-saga/effects';
import worona from 'worona-deps';
import * as deps from '../deps';
function* redirectHome() {
const contentType = yield select(deps.selectors.getContentType);
if (contentType === 'Home') {
const { type, category, page } = yield select(
deps.selectorCreators.getSetting('theme', 'frontPage'),
);
if (type === 'category') {
yield call(deps.libs.push, `?cat=${category}`);
} else if (type === 'page') {
yield call(deps.libs.push, `?page_id=${page}`);
}
}
}
function hideIosStatusBar() {
console.log(worona);
if (worona.isIos && StatusBar) {
StatusBar.hide();
console.log('hiden!');
}
}
export default function* starterProSagas() {
yield [
fork(redirectHome),
fork(hideIosStatusBar),
];
}
|
Append logs (before it was truncating the log file) | var ini = require('ini');
var fs = require('graceful-fs');
var Log = require('log');
var arguments = require(__dirname + '/lib/arguments.js');
global.log = new Log(
'debug',
fs.createWriteStream(__dirname + '/crawler.log', {
flags: 'a',
encoding: null,
mode: 0666
})
);
global.parameters = ini.parse(
fs.readFileSync(__dirname + '/config/parameters.ini', 'utf-8')
).parameters;
global.filmError = {};
arguments.getAction(function (action, id) {
var crawler = require(__dirname + '/lib/actions/' + action + '.js');
process.on('uncaughtException', function (err) {
// console.log('UNCAUGHT EXCEPTION - keeping process alive:', err);
});
if (action === 'user_friends' || action === 'id') {
crawler.start(id);
} else {
crawler.start();
}
});
| var ini = require('ini');
var fs = require('graceful-fs');
var Log = require('log');
var arguments = require(__dirname + '/lib/arguments.js');
global.log = new Log('debug', fs.createWriteStream(__dirname + '/crawler.log'));
global.parameters = ini.parse(
fs.readFileSync(__dirname + '/config/parameters.ini', 'utf-8')
).parameters;
global.filmError = {};
arguments.getAction(function(action, id) {
var crawler = require(__dirname + '/lib/actions/' + action + '.js');
process.on('uncaughtException', function (err) {
// console.log('UNCAUGHT EXCEPTION - keeping process alive:', err);
});
if (action === 'user_friends' || action === 'id') {
crawler.start(id);
} else {
crawler.start();
}
});
|
Remove unit tests that were based on previous functionality | var Connection = require('../models/Connection');
var User = require('../models/User');
exports.userRegistersConnections = function(test) {
test.expect(6);
var conn1 = new Connection({});
var conn2 = new Connection({});
var conn3 = new Connection({});
var user1 = new User("test1");
var user2 = new User("test2");
user1.add(conn1);
user1.add(conn2);
user1.add(conn3);
test.equal(user1.connections.count(), 3, "3 connections added");
user1.add(conn1);
test.equal(user1.connections.count(), 3, "Conn1 only added once");
user1.remove(conn1);
test.equal(user1.connections.count(), 2, "Conn1 removed");
test.equal(user1.connections.has(conn2.id), true, "Conn1 removed, 2 still there");
test.equal(user1.connections.has(conn3.id), true, "Conn1 removed, 3 still there");
user2.add(conn1);
user2.add(conn2);
/* user does not listen to CLOSE of connections, needs to be done by usermanager */
test.done();
};
| var Connection = require('../models/Connection');
var User = require('../models/User');
exports.userRegistersConnections = function(test) {
test.expect(8);
var conn1 = new Connection({});
var conn2 = new Connection({});
var conn3 = new Connection({});
var user1 = new User("test1");
var user2 = new User("test2");
user1.add(conn1);
user1.add(conn2);
user1.add(conn3);
test.equal(user1.connections.count(), 3, "3 connections added");
user1.add(conn1);
test.equal(user1.connections.count(), 3, "Conn1 only added once");
user1.remove(conn1);
test.equal(user1.connections.count(), 2, "Conn1 removed");
test.equal(user1.connections.has(conn2.id), true, "Conn1 removed, 2 still there");
test.equal(user1.connections.has(conn3.id), true, "Conn1 removed, 3 still there");
user2.add(conn1);
user2.add(conn2);
conn1.close();
test.equal(user1.connections.count(), 2, "closed conn removed");
conn2.close();
conn3.close();
console.log(user1.connections.count());
test.equal(user1.connections.count(), 0, "all closed conn removed");
test.equal(user2.connections.count(), 0, "all closed conn removed");
test.done();
};
|
Switch to OSI license for Pypi | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "deisss@free.fr",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sockjsroom
# Setup library
setup(
# Pypi name
name = "sockjsroom",
# Release version
version = sockjsroom.__version__,
# Associated package
packages = find_packages(),
# Author
author = "Deisss",
author_email = "deisss@free.fr",
# Package description
description = "Sockjs-tornado multi room system",
long_description = open('README.md').read(),
# Require sockjs-tornado
install_requires = ["tornado", "sockjs-tornado"],
# Add MANIFEST.in
include_package_data = True,
# Github url
url = "https://github.com/Deisss/python-sockjsroom",
# Metadata
classifiers=[
"Programming Language :: Python",
"Development Status :: 1 - Planning",
"License :: MIT Licence",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Topic :: Communications",
],
) |
TASK: Adjust test assertions to PHPUnit 8 | <?php
namespace Neos\Flow\Tests\Unit\Http\Helper;
use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;
/**
* Tests for the RequestInformationHelper
*/
class RequestInformationHelperTest extends UnitTestCase
{
/**
* @test
*/
public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
{
$request = ServerRequest::fromGlobals()
->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
->withAddedHeader('Authorization', 'Bearer SomeToken');
$renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
self::assertStringNotContainsString('SomePassword', $renderedHeaders);
self::assertStringNotContainsString('SomeToken', $renderedHeaders);
}
}
| <?php
namespace Neos\Flow\Tests\Unit\Http\Helper;
use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;
/**
* Tests for the RequestInformationHelper
*/
class RequestInformationHelperTest extends UnitTestCase
{
/**
* @test
*/
public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
{
$request = ServerRequest::fromGlobals()
->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
->withAddedHeader('Authorization', 'Bearer SomeToken');
$renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
self::assertStringContainsString('SomePassword', $renderedHeaders);
self::assertStringContainsString('SomeToken', $renderedHeaders);
}
}
|
Change connection port to a secure one | package main
import (
"fmt"
"github.com/jasonpuglisi/ircutil"
)
// main requests a server and user which it uses establish a connection. It
// runs a loop to keep the client alive until it is no longer active.
func main() {
// Request a server with the specified details.
server, err := ircutil.CreateServer("irc.rizon.net", 6697, true, "");
if err != nil {
fmt.Println(err.Error())
return
}
// Request a user with the specified details.
user, err := ircutil.CreateUser("Inami", "inami", "Mahiru Inami", 8)
if err != nil {
fmt.Println(err.Error())
return
}
// Establish a connection and get a client using user and server details.
client, err := ircutil.EstablishConnection(server, user);
if err != nil {
fmt.Println(err.Error())
return
}
// Loop until client is no longer active.
for client.Active {}
}
| package main
import (
"fmt"
"github.com/jasonpuglisi/ircutil"
)
// main requests a server and user which it uses establish a connection. It
// runs a loop to keep the client alive until it is no longer active.
func main() {
// Request a server with the specified details.
server, err := ircutil.CreateServer("irc.rizon.net", 6667, true, "");
if err != nil {
fmt.Println(err.Error())
return
}
// Request a user with the specified details.
user, err := ircutil.CreateUser("Inami", "inami", "Mahiru Inami", 8)
if err != nil {
fmt.Println(err.Error())
return
}
// Establish a connection and get a client using user and server details.
client, err := ircutil.EstablishConnection(server, user);
if err != nil {
fmt.Println(err.Error())
return
}
// Loop until client is no longer active.
for client.Active {}
}
|
Add min.php to skip session list | <?php
// test disconnection from skeleton.mics.me
if (Site::$hostname == 'skeleton.emr.ge') {
Site::$autoPull = false;
}
Site::$debug = true; // set to true for extended query logging
//Site::$production = true; // set to true for heavy file caching
// these resolved paths will skip initializing a user session
Site::$skipSessionPaths[] = 'thumbnail.php';
Site::$skipSessionPaths[] = 'min.php';
// uncomment or set to an array of specific hostnames to enable CORS
//Site::$permittedOrigins = '*';
// Custom routing called if a page isn't found in site-root
/*Site::$onNotFound = function($message) {
switch($action = Site::$requestPath[0])
{
default:
if($Page = Page::getByHandle($action))
{
return Page::renderPage();
}
else
{
header('HTTP/1.0 404 Not Found');
die($message);
}
}
};*/ | <?php
// test disconnection from skeleton.mics.me
if (Site::$hostname == 'skeleton.emr.ge') {
Site::$autoPull = false;
}
Site::$debug = true; // set to true for extended query logging
//Site::$production = true; // set to true for heavy file caching
// these resolved paths will skip initializing a user session
Site::$skipSessionPaths[] = 'thumbnail.php';
// uncomment or set to an array of specific hostnames to enable CORS
//Site::$permittedOrigins = '*';
// Custom routing called if a page isn't found in site-root
/*Site::$onNotFound = function($message) {
switch($action = Site::$requestPath[0])
{
default:
if($Page = Page::getByHandle($action))
{
return Page::renderPage();
}
else
{
header('HTTP/1.0 404 Not Found');
die($message);
}
}
};*/ |
Disable default lookup & active generation logging | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: '<%= modulePrefix %>',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: '<%= modulePrefix %>',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Fix the CSS selector in the modified source page. | var casper = require('casper').create({verbose: true});
var id = casper.cli.args[0];
var password = casper.cli.args[1];
var sourceNumber = casper.cli.args[2];
casper.start('https://www.acmicpc.net/login');
casper.then(function() {
casper.fill('form.reg-page', {
'login_user_id': id,
'login_password': password
}, true);
});
casper.thenOpen('https://www.acmicpc.net/source/' + sourceNumber, function() {
casper.then(function() {
var sourceInfo = casper.evaluate(function() {
return {
source: document.querySelector('[name~=source]').value,
problemNumber: __utils__.findOne('.table-striped tr td:nth-child(3) a').innerHTML,
problemTitle: __utils__.findOne('.table-striped tr td:nth-child(4)').innerHTML,
language: __utils__.findOne('.table-striped tr td:nth-child(8)').innerHTML,
private: document.querySelector('#code_open_close').checked
}
});
casper.echo(JSON.stringify(sourceInfo, null, 4));
});
});
casper.run(function() {
casper.exit();
});
| var casper = require('casper').create({verbose: true});
var id = casper.cli.args[0];
var password = casper.cli.args[1];
var sourceNumber = casper.cli.args[2];
casper.start('https://www.acmicpc.net/login');
casper.then(function() {
casper.fill('form.reg-page', {
'login_user_id': id,
'login_password': password
}, true);
});
casper.thenOpen('https://www.acmicpc.net/source/' + sourceNumber, function() {
casper.then(function() {
var sourceInfo = casper.evaluate(function() {
return {
source: document.querySelector('#source').value,
problemNumber: __utils__.findOne('.table-striped tr td:nth-child(3) a').innerHTML,
problemTitle: __utils__.findOne('.table-striped tr td:nth-child(4)').innerHTML,
language: __utils__.findOne('.table-striped tr td:nth-child(8)').innerHTML,
private: document.querySelector('#code_open_close').checked
}
});
casper.echo(JSON.stringify(sourceInfo, null, 4));
});
});
casper.run(function() {
casper.exit();
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.