text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change search route
remove multiple createuser routes
change getAllRegular to getAll Role
|
import express from 'express';
import userController from '../controllers/userController';
// import documentController from '../controllers/documentController';
import auth from '../middleware/auth';
// import utils from '../middlewares/utils';
const user = express.Router();
user.route('/api/user')
.get(auth.verifyToken, auth.adminAccess, userController.getAllUsers)
.post(userController.createUser);
user.route('/api/user/profile')
.get(auth.verifyToken, userController.getProfile);
user.route('/api/user/admin')
.get(auth.verifyToken, auth.adminAccess, userController.getAllAdmin);
user.route('/api/user/role')
.get(auth.verifyToken, userController.getAllRole);
user.route('/api/user/:id')
.get(auth.verifyToken, userController.getUser)
.put(auth.verifyToken, userController.updateUser)
.delete(auth.verifyToken, userController.deleteUser);
// user.route('/api/user/:id/documents')
// .all(auth.verifyToken)
// .get(documentsController.getUserDocuments);
user.route('/api/user/login')
.post(userController.login);
user.route('/api/search/user')
.get(auth.verifyToken, userController.searchUsers);
user.route('/api/user/logout')
.post(auth.verifyToken, userController.logout);
module.exports = () => user;
|
import express from 'express';
import userController from '../controllers/userController';
// import documentController from '../controllers/documentController';
import auth from '../middleware/auth';
// import utils from '../middlewares/utils';
const user = express.Router();
user.route('/api/user')
.get(auth.verifyToken, auth.adminAccess, userController.getAllUsers)
.post(userController.createUser);
user.route('/api/user/profile')
.get(auth.verifyToken, userController.getProfile);
user.route('/api/user/admin')
.get(auth.verifyToken, auth.adminAccess, userController.getAllAdmin)
.post(auth.verifyToken, auth.adminAccess, userController.createUser);
user.route('/api/user/regular')
.get(auth.verifyToken, userController.getAllRegular)
.post(auth.verifyToken, userController.createUser);
user.route('/api/user/:id')
.get(auth.verifyToken, userController.getUser)
.put(auth.verifyToken, userController.updateUser)
.delete(auth.verifyToken, userController.deleteUser);
// user.route('/api/user/:id/documents')
// .all(auth.verifyToken)
// .get(documentsController.getUserDocuments);
user.route('/api/user/login')
.post(userController.login);
user.route('/api/user/logout')
.post(auth.verifyToken, userController.logout);
module.exports = () => user;
|
Make it easier to repro tests in the wild
|
;(function(){
console.log('# ' + location);
var __filename = (function(){
var scripts = document.getElementsByTagName('script');
var a = document.createElement('a');
a.href = scripts[scripts.length-1].src;
return a.pathname;
}());
var __dirname = __filename.split('/').reverse().slice(1).reverse().join('/');
document.head.appendChild(function(){
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = __dirname + '/../vendor/jasmine/jasmine.css';
return link;
}());
var cacheBust = '?_=' + Date.now().toString(36);
window.ReactWebWorker_URL = __dirname + '/../src/test/worker.js' + cacheBust;
document.write('<script src="' + __dirname + '/../build/jasmine.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../build/react.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../build/react-test.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../node_modules/jasmine-tapreporter/src/tapreporter.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../test/the-files-to-test.generated.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../test/jasmine-execute.js' + cacheBust + '"><\/script>');
}());
|
;(function(){
var __filename = (function(){
var scripts = document.getElementsByTagName('script');
var a = document.createElement('a');
a.href = scripts[scripts.length-1].src;
return a.pathname;
}());
var __dirname = __filename.split('/').reverse().slice(1).reverse().join('/');
document.head.appendChild(function(){
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = __dirname + '/../vendor/jasmine/jasmine.css';
return link;
}());
var cacheBust = '?_=' + Date.now().toString(36);
window.ReactWebWorker_URL = __dirname + '/../src/test/worker.js' + cacheBust;
document.write('<script src="' + __dirname + '/../build/jasmine.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../build/react.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../build/react-test.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../node_modules/jasmine-tapreporter/src/tapreporter.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../test/the-files-to-test.generated.js' + cacheBust + '"><\/script>');
document.write('<script src="' + __dirname + '/../test/jasmine-execute.js' + cacheBust + '"><\/script>');
}());
|
Use form variable instead hard-coding
|
from .utils import SESSION_KEY_CURRENT_OS
from .forms import OSForm
class CurrentOSMixin(object):
allowed_oses = OSForm.OS_CHOICES
def get_context_data(self, **kwargs):
"""Inject current active OS key and the choice form into context.
"""
# Zip the 2-tuple into a [keys, values] generator, and use next() to
# get its first item (i.e. keys).
allowed_os_keys = next(zip(*self.allowed_oses))
os = self.request.session.get(SESSION_KEY_CURRENT_OS)
if os not in allowed_os_keys:
os = OSForm.OS_CHOICES[0][0]
os_form = OSForm(initial={'os': os})
kwargs.update({'current_os': os, 'os_form': os_form})
return super().get_context_data(**kwargs)
|
from .utils import SESSION_KEY_CURRENT_OS
from .forms import OSForm
class CurrentOSMixin(object):
allowed_oses = OSForm.OS_CHOICES
def get_context_data(self, **kwargs):
"""Inject current active OS key and the choice form into context.
"""
# Zip the 2-tuple into a [keys, values] generator, and use next() to
# get its first item (i.e. keys).
allowed_os_keys = next(zip(*self.allowed_oses))
os = self.request.session.get(SESSION_KEY_CURRENT_OS)
if os not in allowed_os_keys:
os = 'windows'
os_form = OSForm(initial={'os': os})
kwargs.update({'current_os': os, 'os_form': os_form})
return super().get_context_data(**kwargs)
|
Implement a bad sig test
|
#!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest.TestCase):
def setUp(self):
super(ECC_Verify_Tests, self).setUp()
self.ecc = pyecc.ECC(public=DEFAULT_PUBKEY, private=DEFAULT_PRIVKEY)
def test_BasicVerification(self):
assert self.ecc.verify(DEFAULT_DATA, DEFAULT_SIG), ('Failed to verify signature',
DEFAULT_DATA, DEFAULT_SIG, DEFAULT_PUBKEY, DEFAULT_PRIVKEY)
def test_BadVerification(self):
assert self.ecc.verify(DEFAULT_DATA, "FAIL") == False , ('Verified on a bad sig',
DEFAULT_DATA, DEFAULT_SIG, DEFAULT_PUBKEY, DEFAULT_PRIVKEY)
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
'''
Copyright 2009 Slide, Inc.
'''
import unittest
import pyecc
DEFAULT_DATA = 'This message will be signed\n'
DEFAULT_SIG = '$HPI?t(I*1vAYsl$|%21WXND=6Br*[>k(OR9B!GOwHqL0s+3Uq'
DEFAULT_PUBKEY = '8W;>i^H0qi|J&$coR5MFpR*Vn'
DEFAULT_PRIVKEY = 'my private key'
class ECC_Verify_Tests(unittest.TestCase):
def test_BasicVerification(self):
ecc = pyecc.ECC(public=DEFAULT_PUBKEY, private=DEFAULT_PRIVKEY)
assert ecc.verify(DEFAULT_DATA, DEFAULT_SIG), ('Failed to verify signature',
DEFAULT_DATA, DEFAULT_SIG, DEFAULT_PUBKEY, DEFAULT_PRIVKEY)
if __name__ == '__main__':
unittest.main()
|
Remove debug print from view
|
import six
from django.http import HttpResponseRedirect
from django.shortcuts import reverse
from django.conf import settings
from openid.consumer import consumer
import wargaming
wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru')
def auth_callback(request):
oidconsumer = consumer.Consumer(request.session, None)
url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback'))
result = oidconsumer.complete(request.GET, url)
if result.status == consumer.SUCCESS:
identifier = result.getDisplayIdentifier()
user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-')
request.session['user_id'] = user_id
request.session['username'] = username
request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id']
return HttpResponseRedirect('/')
def auth_login(request):
oidconsumer = consumer.Consumer(dict(request.session), None)
openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/')
trust_root = 'http://%s' % request.META['HTTP_HOST']
return_to = '%s%s' % (trust_root, reverse('auth_callback'))
redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False)
return HttpResponseRedirect(redirect_to)
|
import six
from django.http import HttpResponseRedirect
from django.shortcuts import reverse
from django.conf import settings
from openid.consumer import consumer
import wargaming
wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru')
def auth_callback(request):
oidconsumer = consumer.Consumer(request.session, None)
url = 'http://%s%s' % (request.META['HTTP_HOST'], reverse('auth_callback'))
result = oidconsumer.complete(request.GET, url)
if result.status == consumer.SUCCESS:
identifier = result.getDisplayIdentifier()
print identifier
user_id, username = six.moves.urllib_parse.urlparse(identifier).path.split('/')[2].split('-')
request.session['user_id'] = user_id
request.session['username'] = username
request.session['user_clan_id'] = wot.account.info(account_id=user_id)[str(user_id)]['clan_id']
return HttpResponseRedirect('/')
def auth_login(request):
oidconsumer = consumer.Consumer(dict(request.session), None)
openid_request = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/')
trust_root = 'http://%s' % request.META['HTTP_HOST']
return_to = '%s%s' % (trust_root, reverse('auth_callback'))
redirect_to = openid_request.redirectURL(trust_root, return_to, immediate=False)
return HttpResponseRedirect(redirect_to)
|
Include longer playlist in pagination example
Signed-off-by: Noah Stride <1db01d43e08596f43a65fb393d969b98ee5b4dc6@noahstride.co.uk>
|
package main
import (
"context"
"log"
"os"
"github.com/zmb3/spotify"
"golang.org/x/oauth2/clientcredentials"
)
func main() {
config := &clientcredentials.Config{
ClientID: os.Getenv("SPOTIFY_ID"),
ClientSecret: os.Getenv("SPOTIFY_SECRET"),
TokenURL: spotify.TokenURL,
}
token, err := config.Token(context.Background())
if err != nil {
log.Fatalf("couldn't get token: %v", err)
}
client := spotify.Authenticator{}.NewClient(token)
tracks, err := client.GetPlaylistTracks("57qttz6pK881sjxj2TAEEo")
if err != nil {
log.Fatal(err)
}
log.Printf("Playlist has %d total tracks", tracks.Total)
for page := 1; ; page++ {
log.Printf(" Page %d has %d tracks", page, len(tracks.Tracks))
err = client.NextPage(tracks)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
log.Fatal(err)
}
}
}
|
package main
import (
"context"
"log"
"os"
"github.com/zmb3/spotify"
"golang.org/x/oauth2/clientcredentials"
)
func main() {
config := &clientcredentials.Config{
ClientID: os.Getenv("SPOTIFY_ID"),
ClientSecret: os.Getenv("SPOTIFY_SECRET"),
TokenURL: spotify.TokenURL,
}
token, err := config.Token(context.Background())
if err != nil {
log.Fatalf("couldn't get token: %v", err)
}
client := spotify.Authenticator{}.NewClient(token)
tracks, err := client.GetPlaylistTracks("37i9dQZF1DWWzVPEmatsUB")
if err != nil {
log.Fatal(err)
}
log.Printf("Playlist has %d total tracks", tracks.Total)
for page := 1; ; page++ {
log.Printf(" Page %d has %d tracks", page, len(tracks.Tracks))
err = client.NextPage(tracks)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
log.Fatal(err)
}
}
}
|
Fix suggested solution for failure to clone.
|
from __future__ import division, absolute_import, print_function
import contextlib
from punic.logger import logger
class RepositoryNotClonedError(Exception):
pass
class CartfileNotFound(Exception):
def __init__(self, path):
self.path = path
class PunicRepresentableError(Exception):
pass
class NoSuchRevision(Exception):
def __init__(self, repository, revision):
self.repository = repository
self.revision = revision
@contextlib.contextmanager
def error_handling():
try:
yield
except RepositoryNotClonedError:
logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?')
exit(-1)
except CartfileNotFound as e:
logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path))
exit(-1)
except NoSuchRevision as e:
logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository))
logger.error(
'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`')
exit(-1)
except PunicRepresentableError as e:
logger.error(e.message)
exit(-1)
except:
raise
|
from __future__ import division, absolute_import, print_function
import contextlib
from punic.logger import logger
class RepositoryNotClonedError(Exception):
pass
class CartfileNotFound(Exception):
def __init__(self, path):
self.path = path
class PunicRepresentableError(Exception):
pass
class NoSuchRevision(Exception):
def __init__(self, repository, revision):
self.repository = repository
self.revision = revision
@contextlib.contextmanager
def error_handling():
try:
yield
except RepositoryNotClonedError:
logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?')
exit(-1)
except CartfileNotFound as e:
logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path))
exit(-1)
except NoSuchRevision as e:
logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository))
logger.error(
'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`')
exit(-1)
except PunicRepresentableError as e:
logger.error(e.message)
exit(-1)
except:
raise
|
Add Opbeat performance flag for client
|
import initOpbeat from 'opbeat-react';
import 'opbeat-react/router';
let opbeat_app_id = process.env.REACT_APP_OPBEAT_APP_ID;
let opbeat_org_id = process.env.REACT_APP_OPBEAT_ORG_ID;
if(process.env.NODE_ENV === 'production' && opbeat_app_id && opbeat_org_id) {
initOpbeat({
appId: opbeat_app_id,
orgId: opbeat_org_id,
performance: {
'initial-page-load': true
},
});
}
import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import Routes from './routes';
const store = configureStore();
import './index.css';
import './semantic-ui/semantic.min.css';
ReactDOM.render(
<Provider store={store}>
<Routes history={browserHistory} />
</Provider>,
document.getElementById('root')
);
|
import initOpbeat from 'opbeat-react';
import 'opbeat-react/router';
let opbeat_app_id = process.env.REACT_APP_OPBEAT_APP_ID;
let opbeat_org_id = process.env.REACT_APP_OPBEAT_ORG_ID;
if(process.env.NODE_ENV === 'production' && opbeat_app_id && opbeat_org_id) {
initOpbeat({
appId: opbeat_app_id,
orgId: opbeat_org_id,
});
}
import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import Routes from './routes';
const store = configureStore();
import './index.css';
import './semantic-ui/semantic.min.css';
ReactDOM.render(
<Provider store={store}>
<Routes history={browserHistory} />
</Provider>,
document.getElementById('root')
);
|
Remove explicit initialize_tpu_system call from model garden.
PiperOrigin-RevId: 290354680
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Initializes TPU system for TF 2.0."""
import tensorflow as tf
def tpu_initialize(tpu_address):
"""Initializes TPU for TF 2.0 training.
Args:
tpu_address: string, bns address of master TPU worker.
Returns:
A TPUClusterResolver.
"""
cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
tpu=tpu_address)
if tpu_address not in ('', 'local'):
tf.config.experimental_connect_to_cluster(cluster_resolver)
return cluster_resolver
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Initializes TPU system for TF 2.0."""
import tensorflow as tf
def tpu_initialize(tpu_address):
"""Initializes TPU for TF 2.0 training.
Args:
tpu_address: string, bns address of master TPU worker.
Returns:
A TPUClusterResolver.
"""
cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
tpu=tpu_address)
if tpu_address not in ('', 'local'):
tf.config.experimental_connect_to_cluster(cluster_resolver)
tf.tpu.experimental.initialize_tpu_system(cluster_resolver)
return cluster_resolver
|
Include migrations in package data
|
from setuptools import setup, find_packages
setup(
name = "countries",
version = "0.1.1-2",
description = 'Provides models for a "complete" list of countries',
author = 'David Danier',
author_email = 'david.danier@team23.de',
url = 'https://github.com/ddanier/django_countries',
long_description=open('README.rst', 'r').read(),
packages = [
'countries',
'countries.management',
'countries.management.commands',
'countries.templatetags',
'countries.utils',
'countries.migrations',
],
package_data = {
'countries': ['fixtures/*', 'locale/*/LC_MESSAGES/*'],
},
install_requires = [
'Django >=1.2',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
from setuptools import setup, find_packages
setup(
name = "countries",
version = "0.1.1-1",
description = 'Provides models for a "complete" list of countries',
author = 'David Danier',
author_email = 'david.danier@team23.de',
url = 'https://github.com/ddanier/django_countries',
long_description=open('README.rst', 'r').read(),
packages = [
'countries',
'countries.management',
'countries.management.commands',
'countries.templatetags',
'countries.utils',
],
package_data = {
'countries': ['fixtures/*', 'locale/*/LC_MESSAGES/*'],
},
install_requires = [
'Django >=1.2',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
Fix bug that arose through grammar tweaking
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
info = self.create_information()
super(Source, self).transmit(to_whom=to_whom, what=info)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self):
info = Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
return info
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self, what=None, to_whom=None):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
self.create_information(what=what, to_whom=to_whom)
super(Source, self).transmit(to_whom=to_whom, what=what)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self, what=None, to_whom=None):
Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
|
import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER',
'filebrowser' in settings.INSTALLED_APPS)
if 'staticfiles' in settings.INSTALLED_APPS or \
'django.contrib.staticfiles' in settings.INSTALLED_APPS:
JS_URL = os.path.join(getattr(settings, 'STATIC_URL', ''), 'tiny_mce/tiny_mce.js')
JS_ROOT = os.path.join(getattr(settings, 'STATIC_ROOT', ''), 'tiny_mce')
else:
JS_URL = getattr(settings, 'TINYMCE_JS_URL',
'%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL)
JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT',
os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce'))
JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
|
import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER',
'filebrowser' in settings.INSTALLED_APPS)
if 'staticfiles' in settings.INSTALLED_APPS:
JS_URL = os.path.join(settings.STATIC_URL, 'tiny_mce/tiny_mce.js')
JS_ROOT = os.path.join(settings.STATIC_ROOT, 'tiny_mce')
else:
JS_URL = getattr(settings, 'TINYMCE_JS_URL',
'%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL)
JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT',
os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce'))
JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
|
Update divs to ExampleContainer component
|
import React from 'react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import { SprkDivider } from '@sparkdesignsystem/spark-core-react';
import ExampleContainer from '../../containers/ExampleContainer/ExampleContainer';
const SprkDividerDocs = () => {
return (
<CentralColumnLayout>
<ExampleContainer>
<h2 className="drizzle-b-h2">Divider as span</h2>
<SprkDivider idString="divider-1" element="span"></SprkDivider>
</ExampleContainer>
<ExampleContainer>
<h2 className="drizzle-b-h2">Divider as hr</h2>
<SprkDivider idString="divider-1" element="hr"></SprkDivider>
</ExampleContainer>
</CentralColumnLayout>
)
}
export default SprkDividerDocs;
|
import React from 'react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import { SprkDivider } from '@sparkdesignsystem/spark-core-react';
const SprkDividerDocs = () => {
return (
<CentralColumnLayout>
<div className="sprk-u-mbm">
<h2 className="drizzle-b-h2">Divider as span</h2>
<SprkDivider idString="divider-1" element="span"></SprkDivider>
</div>
<div className="sprk-u-mbm">
<h2 className="drizzle-b-h2">Divider as hr</h2>
<SprkDivider idString="divider-1" element="hr"></SprkDivider>
</div>
</CentralColumnLayout>
)
}
export default SprkDividerDocs;
|
Add flag for new module loader.
|
/*
___ usage ___ en_US ___
usage: prolific udp <options>
-u, --url <string>
The URL of the logging destination.
--help
Display this message.
___ $ ___ en_US ___
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.command.params.help)
var response = {
moduleName: 'prolific.udp/udp.processor',
parameters: { params: program.command.param },
argv: program.argv,
terminal: program.command.terminal
}
if (process.mainModule == module) {
console.log(response)
}
return response
}))
module.exports.isProlific = true
|
/*
___ usage ___ en_US ___
usage: prolific udp <options>
-u, --url <string>
The URL of the logging destination.
--help
Display this message.
___ $ ___ en_US ___
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.command.params.help)
var response = {
moduleName: 'prolific.udp/udp.processor',
parameters: { params: program.command.param },
argv: program.argv,
terminal: program.command.terminal
}
if (process.mainModule == module) {
console.log(response)
}
return response
}))
|
Exclude bin files from built zips.
|
/**
* Gulp copy task.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
const gulp = require( 'gulp' );
module.exports = function() {
const globs = [
'readme.txt',
'google-site-kit.php',
'dist/*.js',
'dist/assets/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
];
return gulp.src( globs, { base: '.' } ).pipe( gulp.dest( 'release/google-site-kit' ) );
};
|
/**
* Gulp copy task.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
const gulp = require( 'gulp' );
module.exports = function() {
const globs = [
'readme.txt',
'google-site-kit.php',
'dist/*.js',
'dist/assets/**/*',
'bin/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!bin/local-env/**/*',
'!bin/local-env/',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
];
return gulp.src( globs, { base: '.' } ).pipe( gulp.dest( 'release/google-site-kit' ) );
};
|
Fix pandoc statement
Update version number
|
#!/usr/bin/env python
#pandoc -t rst -f markdown README.mkd -o README
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='mass',
version='0.1.3',
description='Merge and Simplify Scripts: an automated tool for managing, combining and minifying javascript assets for web projects.',
long_description=read('README'),
author='jack boberg alex padgett',
author_email='info@codedbyhand.com',
url='https://github.com/coded-by-hand/mass',
license='BSD License',
platforms=['Mac OSX'],
packages=['mass'],
install_requires=['distribute','jsmin','macfsevents'],
zip_safe = False,
entry_points = {
'console_scripts': [
"mass = mass.monitor:main"
],
}
)
|
#!/usr/bin/env python
#pandoc -f rst -t markdown README.mkd -o README
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='mass',
version='0.1.2',
description='Merge and Simplify Scripts: an automated tool for managing, combining and minifying javascript assets for web projects.',
long_description=read('README'),
author='jack boberg alex padgett',
author_email='info@codedbyhand.com',
url='https://github.com/coded-by-hand/mass',
license='BSD License',
platforms=['Mac OSX'],
packages=['mass'],
install_requires=['distribute','jsmin','macfsevents'],
zip_safe = False,
entry_points = {
'console_scripts': [
"mass = mass.monitor:main"
],
}
)
|
Fix mismatched horizontal and vertical proptypes
|
import React, { PropTypes } from 'react';
import Radium from 'radium';
import resolveCellStyles from './util/resolve-cell-styles';
import omit from 'lodash.omit';
const Cell = Radium(props => {
const styles = resolveCellStyles(props);
console.log(styles);
return (
<div style={styles}>
{props.children}
</div>
);
});
const horizontalPropType = PropTypes.oneOf(['left', 'center', 'right']);
const verticalPropType = PropTypes.oneOf(['top', 'middle', 'bottom']);
Cell.propTypes = {
width: PropTypes.number,
horizontalAlign: horizontalPropType,
verticalAlign: verticalPropType,
smallWidth: PropTypes.number,
smallHorizontalAlign: horizontalPropType,
smallVerticalAlign: verticalPropType,
mediumWidth: PropTypes.number,
mediumHorizontalAlign: horizontalPropType,
mediumVerticalAlign: verticalPropType,
largeWidth: PropTypes.number,
largeHorizontalAlign: horizontalPropType,
largeVerticalAlign: verticalPropType,
xlargeWidth: PropTypes.number,
xlargeHorizontalAlign: horizontalPropType,
xlargeVerticalAlign: verticalPropType,
order: PropTypes.number,
children: React.PropTypes.node
};
export default Cell;
|
import React, { PropTypes } from 'react';
import Radium from 'radium';
import resolveCellStyles from './util/resolve-cell-styles';
import omit from 'lodash.omit';
const Cell = Radium(props => {
const styles = resolveCellStyles(props);
console.log(styles);
return (
<div style={styles}>
{props.children}
</div>
);
});
const horizontalPropType = PropTypes.oneOf(['left', 'center', 'right']);
const verticalPropType = PropTypes.oneOf(['top', 'middle', 'bottom']);
Cell.propTypes = {
width: PropTypes.number,
horizontalAlign: verticalPropType,
verticalAlign: horizontalPropType,
smallWidth: PropTypes.number,
smallHorizontalAlign: verticalPropType,
smallVerticalAlign: horizontalPropType,
mediumWidth: PropTypes.number,
mediumHorizontalAlign: verticalPropType,
mediumVerticalAlign: horizontalPropType,
largeWidth: PropTypes.number,
largeHorizontalAlign: verticalPropType,
largeVerticalAlign: horizontalPropType,
xlargeWidth: PropTypes.number,
xlargeHorizontalAlign: verticalPropType,
xlargeVerticalAlign: horizontalPropType,
order: PropTypes.number,
children: React.PropTypes.node
};
export default Cell;
|
Fix layout for Eiger example
|
'''Virtual datasets: The 'Eiger' use case
https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''
import h5py
import numpy as np
files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape.
layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float)
M_start = 0
for i, filename in enumerate(files):
M_end = M_start + sh[0]
vsource = h5py.VirtualSource(filename, entry_key, shape=sh)
layout[M_start:M_end:1, :, :] = vsource
M_start = M_end
with h5py.File("eiger_vds.h5", 'w', libver='latest') as f:
f.create_virtual_dataset('data', layout, fillvalue=0)
|
'''Virtual datasets: The 'Eiger' use case
https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''
import h5py
import numpy as np
files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape.
layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float)
M_start = 0
for i, filename in enumerate(files):
M_end = M_start + sh[0]
vsource = h5py.VirtualSource(filename, entry_key, shape=sh)
layout[M_start:M_end:1, :, :] = vsource
M_start = M_end
with h5py.File("eiger_vds.h5", 'w', libver='latest') as f:
f.create_virtual_dataset('data', layout, fillvalue=0)
|
Use the bridge in the router
|
<?php
/**
* @author Aaron Scherer <aequasi@gmail.com>
* @date 2013
* @license http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
*/
namespace Aequasi\Bundle\CacheBundle\DependencyInjection\Compiler;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Reference;
/**
*
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class RouterCompilerPass extends BaseCompilerPass
{
/**
* @return void
*/
protected function prepare()
{
$router = $this->container->getParameter($this->getAlias() . '.router');
if (!$router['enabled']) {
return;
}
$instance = $router['instance'];
$def = $this->container->findDefinition('router');
$def->setClass('Aequasi\Bundle\CacheBundle\Routing\Router');
$def->addMethodCall('setCache', [new Reference(sprintf('aequasi_cache.instance.%s.bridge', $instance))]);
}
}
|
<?php
/**
* @author Aaron Scherer <aequasi@gmail.com>
* @date 2013
* @license http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
*/
namespace Aequasi\Bundle\CacheBundle\DependencyInjection\Compiler;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Reference;
/**
*
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class RouterCompilerPass extends BaseCompilerPass
{
/**
* @return void
*/
protected function prepare()
{
$router = $this->container->getParameter($this->getAlias() . '.router');
if (!$router['enabled']) {
return;
}
$instance = $router['instance'];
$def = $this->container->findDefinition('router');
$def->setClass('Aequasi\Bundle\CacheBundle\Routing\Router');
$def->addMethodCall('setCache', [new Reference('aequasi_cache.instance.' . $instance)]);
}
}
|
Fix test for new bands_inspect version.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
import tempfile
import numpy as np
import bands_inspect as bi
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
def test_cli_eigenvals(sample):
samples_dir = sample('cli_eigenvals')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli, [
'eigenvals', '-o', out_file.name, '-k',
os.path.join(samples_dir, 'kpoints.hdf5'), '-i',
os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bi.io.load(out_file.name)
reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5'))
np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
import tempfile
import numpy as np
import bands_inspect as bi
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
def test_cli_eigenvals(sample):
samples_dir = sample('cli_eigenvals')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli, [
'eigenvals', '-o', out_file.name, '-k',
os.path.join(samples_dir, 'kpoints.hdf5'), '-i',
os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bi.io.load(out_file.name)
reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5'))
np.testing.assert_allclose(bi.compare.difference.general(res, reference), 0, atol=1e-10)
|
Add option for suffix when wrapping API
|
module.exports = function promisifyNvim(nvim, opts) {
//promisify APIs
var interfaces = {
Nvim: nvim.constructor,
Buffer: nvim.Buffer,
Window: nvim.Window,
Tabpage: nvim.Tabpage,
};
var options = opts || {};
Object.keys(interfaces).forEach(function(key) {
var name = key;
Object.keys(interfaces[key].prototype).forEach(function(method) {
const oldMethod = interfaces[key].prototype[method];
interfaces[key].prototype[method + options.suffix] = function() {
const args = Array.prototype.slice.call(arguments);
const context = this;
return new Promise(function(resolve, reject) {
args.push(function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
oldMethod.apply(context, args);
});
};
})
});
}
|
module.exports = function promisifyNvim(nvim) {
//promisify APIs
var interfaces = {
Nvim: nvim.constructor,
Buffer: nvim.Buffer,
Window: nvim.Window,
Tabpage: nvim.Tabpage,
};
Object.keys(interfaces).forEach(function(key) {
var name = key;
Object.keys(interfaces[key].prototype).forEach(function(method) {
const oldMethod = interfaces[key].prototype[method];
interfaces[key].prototype[method] = function() {
const args = Array.prototype.slice.call(arguments);
const context = this;
return new Promise(function(resolve, reject) {
args.push(function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
oldMethod.apply(context, args);
});
};
})
});
}
|
Remove referee.isArrayLike from public API
This is not used by referee itself
|
"use strict";
var isArguments = require("lodash.isarguments");
var actualMessageValues = require("../actual-message-values");
module.exports = function(referee) {
function isArrayLike(object) {
return (
Array.isArray(object) ||
(Boolean(object) &&
typeof object.length === "number" &&
typeof object.splice === "function") ||
isArguments(object)
);
}
referee.add("isArrayLike", {
assert: function(actual) {
return isArrayLike(actual);
},
assertMessage: "${customMessage}Expected ${actual} to be array like",
refuteMessage:
"${customMessage}Expected ${actual} not to be array like",
expectation: "toBeArrayLike",
values: actualMessageValues
});
};
|
"use strict";
var isArguments = require("lodash.isarguments");
var actualMessageValues = require("../actual-message-values");
module.exports = function(referee) {
function isArrayLike(object) {
return (
Array.isArray(object) ||
(Boolean(object) &&
typeof object.length === "number" &&
typeof object.splice === "function") ||
isArguments(object)
);
}
referee.isArrayLike = isArrayLike;
referee.add("isArrayLike", {
assert: function(actual) {
return isArrayLike(actual);
},
assertMessage: "${customMessage}Expected ${actual} to be array like",
refuteMessage:
"${customMessage}Expected ${actual} not to be array like",
expectation: "toBeArrayLike",
values: actualMessageValues
});
};
|
Fix latex output for splitted up/down values
|
#!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# First we need to write out the headers
for row in dict:
for column in dict[row]:
fp.write("& %s " % (column))
fp.write("\\\\\n")
break
fp.write(" \\hline\n")
# Now read all rows and output them as well
for row in dict:
fp.write(" %s " % (row))
for column in dict[row]:
fp.write("& %s / %s " % (dict[row][column][0], dict[row][column][1]))
fp.write("\\\\\n")
fp.write(" \\hline\n")
fp.write("\\end{tabular}\n")
|
#!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# First we need to write out the headers
for row in dict:
for column in dict[row]:
fp.write("& %s " % (column))
fp.write("\\\\\n")
break
fp.write(" \\hline\n")
# Now read all rows and output them as well
for row in dict:
fp.write(" %s " % (row))
for column in dict[row]:
fp.write("& %s " % dict[row][column])
fp.write("\\\\\n")
fp.write(" \\hline\n")
fp.write("\\end{tabular}\n")
|
Remove import DatabaseTransactions as causes conflict
|
<?php
use Laracasts\Integrated\Extensions\Selenium as IntegrationTest;
# use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserRegistrationProcessTest extends IntegrationTest
{
# use DatabaseTransactions;
# protected $baseUrl = 'http://localhost:8000';
/** @test */
public function testRegistrationSuccess()
{
$this->visit('/lang/en_US.utf8')
->visit('/auth/register')
->type('John', '#name')
->type('test@timegrid.io', '#email')
->type('password', '#password')
->type('password', '#password_confirmation')
->press('Register')
->see('I run a business');
}
/** @test */
public function testRegistrationPasswordMissmatch()
{
$this->visit('/lang/en_US.utf8')
->visit('/auth/register')
->type('John', '#name')
->type('test@timegrid.io', '#email')
->type('password', '#password')
->type('wrong', '#password_confirmation')
->press('Register')
->see('Please confirm your password correctly');
}
}
|
<?php
use Laracasts\Integrated\Extensions\Selenium as IntegrationTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserRegistrationProcessTest extends IntegrationTest
{
use DatabaseTransactions;
# protected $baseUrl = 'http://localhost:8000';
/** @test */
public function testRegistrationSuccess()
{
$this->visit('/lang/en_US.utf8')
->visit('/auth/register')
->type('John', '#name')
->type('test@timegrid.io', '#email')
->type('password', '#password')
->type('password', '#password_confirmation')
->press('Register')
->see('I run a business');
}
/** @test */
public function testRegistrationPasswordMissmatch()
{
$this->visit('/lang/en_US.utf8')
->visit('/auth/register')
->type('John', '#name')
->type('test@timegrid.io', '#email')
->type('password', '#password')
->type('wrong', '#password_confirmation')
->press('Register')
->see('Please confirm your password correctly');
}
}
|
Use underlying table name in foreign key
|
export default function(sequelize, DataTypes) {
let BSDCallAssignment = sequelize.define('BSDCallAssignment', {
name: DataTypes.STRING
}, {
underscored: true,
tableName: 'bsd_call_assignments',
classMethods: {
associate: (models) => {
BSDCallAssignment.belongsTo(models.BSDSurvey, {foreignKey: 'signup_form_id', as: 'survey'})
BSDCallAssignment.belongsTo(models.BSDGroup, {as: 'intervieweeGroup'});
BSDCallAssignment.belongsTo(models.BSDGroup, {as: 'callerGroup'});
BSDCallAssignment.hasMany(models.BSDAssignedCall, {
as: 'assignedCalls',
foreignKey: {
name: 'call_assignment_id'
}
})
}
}
})
return BSDCallAssignment;
}
|
export default function(sequelize, DataTypes) {
let BSDCallAssignment = sequelize.define('BSDCallAssignment', {
name: DataTypes.STRING
}, {
underscored: true,
tableName: 'bsd_call_assignments',
classMethods: {
associate: (models) => {
BSDCallAssignment.belongsTo(models.BSDSurvey, {foreignKey: 'bsd_survey_id', as: 'survey'})
BSDCallAssignment.belongsTo(models.BSDGroup, {as: 'intervieweeGroup'});
BSDCallAssignment.belongsTo(models.BSDGroup, {as: 'callerGroup'});
BSDCallAssignment.hasMany(models.BSDAssignedCall, {
as: 'assignedCalls',
foreignKey: {
name: 'call_assignment_id'
}
})
}
}
})
return BSDCallAssignment;
}
|
Change DataIndex to restrict on published and archived flags only
In addition, the warnings of the deprecated settings have been removed.
Fix #290
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
|
from haystack import indexes
from avocado.models import DataConcept, DataField
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True, archived=False)
def read_queryset(self, using=None):
return self.index_queryset()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
|
import warnings
from haystack import indexes
from avocado.conf import settings
from avocado.models import DataConcept, DataField
# Warn if either of the settings are set to false
if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \
not getattr(settings, 'FIELD_SEARCH_ENABLED', True):
warnings.warn('CONCEPT_SEARCH_ENABLED and FIELD_SEARCH_ENABLED have been '
'deprecated due to changes in Haystack 2.x API. To exclude '
'an index from being discovered, add the path to the class '
'to EXCLUDED_INDEXES in the appropriate '
'HAYSTACK_CONNECTIONS entry in settings.')
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.published()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
|
Add missing UnexpectedResponseFormat for backward compatability
Signed-off-by: Abhijeet Kasurde <6334fd0c217b1f2a15926284df229acde5b4fc3a@redhat.com>
|
# -*- coding: utf-8 -*-
class PysnowException(Exception):
pass
class InvalidUsage(PysnowException):
pass
class UnexpectedResponseFormat(PysnowException):
pass
class ResponseError(PysnowException):
message = "<empty>"
detail = "<empty>"
def __init__(self, error):
if "message" in error:
self.message = error["message"] or self.message
if "detail" in error:
self.detail = error["detail"] or self.detail
def __str__(self):
return "Error in response. Message: %s, Details: %s" % (
self.message,
self.detail,
)
class MissingResult(PysnowException):
pass
class NoResults(PysnowException):
pass
class EmptyContent(PysnowException):
pass
class MultipleResults(PysnowException):
pass
class MissingToken(PysnowException):
pass
class TokenCreateError(PysnowException):
def __init__(self, error, description, status_code):
self.error = error
self.description = description
self.snow_status_code = status_code
class QueryTypeError(PysnowException):
pass
class QueryMissingField(PysnowException):
pass
class QueryEmpty(PysnowException):
pass
class QueryExpressionError(PysnowException):
pass
class QueryMultipleExpressions(PysnowException):
pass
|
# -*- coding: utf-8 -*-
class PysnowException(Exception):
pass
class InvalidUsage(PysnowException):
pass
class ResponseError(PysnowException):
message = "<empty>"
detail = "<empty>"
def __init__(self, error):
if "message" in error:
self.message = error["message"] or self.message
if "detail" in error:
self.detail = error["detail"] or self.detail
def __str__(self):
return "Error in response. Message: %s, Details: %s" % (
self.message,
self.detail,
)
class MissingResult(PysnowException):
pass
class NoResults(PysnowException):
pass
class EmptyContent(PysnowException):
pass
class MultipleResults(PysnowException):
pass
class MissingToken(PysnowException):
pass
class TokenCreateError(PysnowException):
def __init__(self, error, description, status_code):
self.error = error
self.description = description
self.snow_status_code = status_code
class QueryTypeError(PysnowException):
pass
class QueryMissingField(PysnowException):
pass
class QueryEmpty(PysnowException):
pass
class QueryExpressionError(PysnowException):
pass
class QueryMultipleExpressions(PysnowException):
pass
|
Change interval: 10 -> 20
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
Allow falsey but not null and undefined values to come through
|
/*
* Copyright 2018, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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.
*/
import Identifier from './Identifier';
import Rule from '../../parser/Rule';
import SequenceExpression from '../../parser/SequenceExpression';
import {navigate} from '@ultraq/object-utils';
/**
* Variable expressions, `${variable}`. Represents a value to be retrieved from
* the current context.
*
* @author Emanuel Rabina
*/
export default new Rule('VariableExpression',
new SequenceExpression(
/\${/,
Identifier.name,
/\}/
),
([, identifier]) => context => {
let result = navigate(context, identifier);
return result !== null && result !== undefined ? result : '';
}
);
|
/*
* Copyright 2018, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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.
*/
import Identifier from './Identifier';
import Rule from '../../parser/Rule';
import SequenceExpression from '../../parser/SequenceExpression';
import {navigate} from '@ultraq/object-utils';
/**
* Variable expressions, `${variable}`. Represents a value to be retrieved from
* the current context.
*
* @author Emanuel Rabina
*/
export default new Rule('VariableExpression',
new SequenceExpression(
/\${/,
Identifier.name,
/\}/
),
([, identifier]) => context => {
return navigate(context, identifier) || '';
}
);
|
Add isConfidential function to client entity trait
|
<?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities\Traits;
trait ClientTrait
{
/**
* @var string
*/
protected $name;
/**
* @var string|string[]
*/
protected $redirectUri;
/**
* @var bool
*/
protected $isConfidential;
/**
* Get the client's name.
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
return $this->name;
}
/**
* Returns the registered redirect URI (as a string).
*
* Alternatively return an indexed array of redirect URIs.
*
* @return string|string[]
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* Returns true if the client is confidential.
*
* @return bool
*/
public function isConfidential()
{
return $this->isConfidential;
}
}
|
<?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities\Traits;
trait ClientTrait
{
/**
* @var string
*/
protected $name;
/**
* @var string|string[]
*/
protected $redirectUri;
/**
* Get the client's name.
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
return $this->name;
}
/**
* Returns the registered redirect URI (as a string).
*
* Alternatively return an indexed array of redirect URIs.
*
* @return string|string[]
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
}
|
Increase storage prefix in order to clear old data
|
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import reducers from './reducers';
import Router from './components/Router';
const preloadedState = window.__PRELOADED_STATE__;
// Allow the passed state to be garbage-collected
delete window.__PRELOADED_STATE__;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, preloadedState, composeEnhancers(
applyMiddleware(thunk, routerMiddleware(browserHistory)),
autoRehydrate()
)
);
persistStore(store, {
keyPrefix: 'v0.0.5:',
whitelist: [
'profile'
]
});
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} />
</Provider>,
document.getElementById('root')
);
|
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import reducers from './reducers';
import Router from './components/Router';
const preloadedState = window.__PRELOADED_STATE__;
// Allow the passed state to be garbage-collected
delete window.__PRELOADED_STATE__;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, preloadedState, composeEnhancers(
applyMiddleware(thunk, routerMiddleware(browserHistory)),
autoRehydrate()
)
);
persistStore(store, {
keyPrefix: 'v0.0.4:',
whitelist: [
'profile'
]
});
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} />
</Provider>,
document.getElementById('root')
);
|
Add Setting model creation test
|
from django.test import TestCase
from .models import Author, Publisher, Edition, Setting, Adventure
class AuthorTests(TestCase):
def test_create_author(self):
gygax = Author.objects.create(name='Gary Gygax')
self.assertEqual(Author.objects.first(), gygax)
self.assertEqual(Author.objects.count(), 1)
class PublisherTests(TestCase):
def test_create_author(self):
wotc = Publisher.objects.create(name='Wizards of the Coast')
self.assertEqual(Publisher.objects.first(), wotc)
self.assertEqual(Publisher.objects.count(), 1)
class EditionTests(TestCase):
def test_create_author(self):
odandd = Edition.objects.create(name='OD&D')
self.assertEqual(Edition.objects.first(), odandd)
self.assertEqual(Edition.objects.count(), 1)
class SettingTests(TestCase):
def test_create_author(self):
fr = Setting.objects.create(name='Forgotten Realms')
self.assertEqual(Setting.objects.first(), fr)
self.assertEqual(Setting.objects.count(), 1)
|
from django.test import TestCase
from .models import Author, Publisher, Edition, Setting, Adventure
class AuthorTests(TestCase):
def test_create_author(self):
gygax = Author.objects.create(name='Gary Gygax')
self.assertEqual(Author.objects.first(), gygax)
self.assertEqual(Author.objects.count(), 1)
class PublisherTests(TestCase):
def test_create_author(self):
wotc = Publisher.objects.create(name='Wizards of the Coast')
self.assertEqual(Publisher.objects.first(), wotc)
self.assertEqual(Publisher.objects.count(), 1)
class EditionTests(TestCase):
def test_create_author(self):
odandd = Edition.objects.create(name='OD&D')
self.assertEqual(Edition.objects.first(), odandd)
self.assertEqual(Edition.objects.count(), 1)
|
Remove declare strict to be consistent with rest of code base
|
<?php
/*
* This file is part of the php-code-coverage package.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeCoverage\Report\Xml;
use TheSeer\Tokenizer\NamespaceUri;
use TheSeer\Tokenizer\Tokenizer;
use TheSeer\Tokenizer\XMLSerializer;
class Source
{
/** @var \DOMElement */
private $context;
/**
* @param \DOMElement $context
*/
public function __construct(\DOMElement $context)
{
$this->context = $context;
}
/**
* @param string $source
*/
public function setSourceCode($source)
{
$context = $this->context;
$tokens = (new Tokenizer())->parse($source);
$srcDom = (new XMLSerializer(new NamespaceUri($context->namespaceURI)))->toDom($tokens);
$context->parentNode->replaceChild(
$context->ownerDocument->importNode($srcDom->documentElement, true),
$context
);
}
}
|
<?php declare(strict_types = 1);
/*
* This file is part of the php-code-coverage package.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeCoverage\Report\Xml;
use TheSeer\Tokenizer\NamespaceUri;
use TheSeer\Tokenizer\Tokenizer;
use TheSeer\Tokenizer\XMLSerializer;
class Source
{
/** @var \DOMElement */
private $context;
/**
* @param \DOMElement $context
*/
public function __construct(\DOMElement $context)
{
$this->context = $context;
}
/**
* @param string $source
*/
public function setSourceCode($source)
{
$context = $this->context;
$tokens = (new Tokenizer())->parse($source);
$srcDom = (new XMLSerializer(new NamespaceUri($context->namespaceURI)))->toDom($tokens);
$context->parentNode->replaceChild(
$context->ownerDocument->importNode($srcDom->documentElement, true),
$context
);
}
}
|
[FIX] Use var instead of let for variable declaration
ES2015 will probably not be available on the Raspberry Pi.
|
Template.dashboard.onCreated( () => {
Template.instance().subscribe( 'train' );
});
Template.dashboard.helpers({
getTargetspeed: function() {
var query = Train.findOne({ targetspeed: {$ne: "" } }, { fields: {'targetspeed': 1 }} );
if(query) {
return query.targetspeed;
} else {
return 0;
}
},
getCurrentspeed: function() {
var query = Train.findOne({ currentspeed: {$ne: "" } }, { fields: {'currentspeed': 1 }} );
if(query) {
return query.currentspeed;
} else {
return 0;
}
},
/*
top: function() {
dep.depend();
var serverTime = (new Date).getTime() + Session.get("serverDiff");
var totalTime = (this.finishAt - this.createdAt);
var elapsedTime = (serverTime - this.createdAt);
var percentage = Math.min(1, elapsedTime / totalTime);
return this.source_top + (this.target_top - this.source_top) * percentage;
},*/
});
Template.dashboard.events({
"change #targetspeed": function (event) {
// current value: $(event.currentTarget).val()
Meteor.call("setTargetspeed", $(event.currentTarget).val());
},
});
|
Template.dashboard.onCreated( () => {
Template.instance().subscribe( 'train' );
});
Template.dashboard.helpers({
getTargetspeed: function() {
let query = Train.findOne({ targetspeed: {$ne: "" } }, { fields: {'targetspeed': 1 }} );
if(query) {
return query.targetspeed;
} else {
return 0;
}
},
getCurrentspeed: function() {
let query = Train.findOne({ currentspeed: {$ne: "" } }, { fields: {'currentspeed': 1 }} );
if(query) {
return query.currentspeed;
} else {
return 0;
}
},
/*
top: function() {
dep.depend();
var serverTime = (new Date).getTime() + Session.get("serverDiff");
var totalTime = (this.finishAt - this.createdAt);
var elapsedTime = (serverTime - this.createdAt);
var percentage = Math.min(1, elapsedTime / totalTime);
return this.source_top + (this.target_top - this.source_top) * percentage;
},*/
});
Template.dashboard.events({
"change #targetspeed": function (event) {
// current value: $(event.currentTarget).val()
Meteor.call("setTargetspeed", $(event.currentTarget).val());
},
});
|
Add detailed routes for Rooms
|
//= require "lib/moment.min"
//= require "lib/jquery-2.0.3"
//= require "lib/handlebars-v1.1.2"
//= require "lib/ember"
//= require "lib/ember-data"
//= require_self
//= require "models"
//= require "views"
//= require "helpers"
//= require "./routes/authenticated_route"
//= require_tree "./controllers"
//= require_tree "./routes"
window.App = Em.Application.create({LOG_TRANSITIONS: true})
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({})
App.ApplicationAdapter = DS.RESTAdapter.reopen({namespace: "api"})
App.ApplicationView = Em.View.extend({classNames: ["container"]})
App.Router.map(function() {
// login
this.route("login");
// rooms
this.resource("rooms", function() {
this.route("new");
this.resource("room", {path: "/:room_id"}, function() {
this.route("edit");
});
});
// users
// users/new
// users/:user_id
this.resource("users", function() {
this.route("new");
this.resource("user", {path: "/:user_id"}, function() {
this.route("edit");
});
});
});
|
//= require "lib/moment.min"
//= require "lib/jquery-2.0.3"
//= require "lib/handlebars-v1.1.2"
//= require "lib/ember"
//= require "lib/ember-data"
//= require_self
//= require "models"
//= require "views"
//= require "helpers"
//= require "./routes/authenticated_route"
//= require_tree "./controllers"
//= require_tree "./routes"
window.App = Em.Application.create({LOG_TRANSITIONS: true})
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({})
App.ApplicationAdapter = DS.RESTAdapter.reopen({namespace: "api"})
App.ApplicationView = Em.View.extend({classNames: ["container"]})
App.Router.map(function() {
// login
this.route("login");
// rooms
this.resource("rooms");
// users
// users/new
// users/:user_id
this.resource("users", function() {
this.route("new");
this.resource("user", {path: "/:user_id"}, function() {
this.route("edit");
});
});
});
|
:wrench: Fix export in right place
|
import Arrow from './arrow'
import Atm from './atm'
import Attributes from './attributes'
import Bag from './bag'
import Bubbles from './bubbles'
import Cart from './cart'
import Checkmark from './checkmark'
import Error from './error'
import Headset from './headset'
import Magnifier from './magnifier'
import MagnifierAlt from './magnifier-alt'
import Notebook from './notebook'
import Payout from './payout'
import ProductBox from './product-box'
import Pencil from './pencil'
import Regret from './regret'
import Shop from './shop'
import ShopAlt from './shop-alt'
import Star from './star'
import Stock from './stock'
import Tags from './tags'
import Truck from './truck'
import TableSetting from './table-setting'
import Warning from './warning'
import X from './x'
export {
Arrow,
Atm,
Attributes,
Bag,
Bubbles,
Cart,
Checkmark,
Error,
Headset,
Magnifier,
MagnifierAlt,
Notebook,
Payout,
ProductBox,
Pencil,
Regret,
Shop,
ShopAlt,
Star,
Stock,
Tags,
Truck,
TableSetting,
Warning,
X,
}
|
import Arrow from './arrow'
import Atm from './atm'
import Attributes from './attributes'
import Bag from './bag'
import Bubbles from './bubbles'
import Cart from './cart'
import Checkmark from './checkmark'
import Error from './error'
import Headset from './headset'
import Magnifier from './magnifier'
import MagnifierAlt from './magnifier-alt'
import Notebook from './notebook'
import Payout from './payout'
import ProductBox from './product-box'
import Pencil from './pencil'
import Regret from './regret'
import TableSetting from './table-setting'
import Shop from './shop'
import ShopAlt from './shop-alt'
import Star from './star'
import Stock from './stock'
import Tags from './tags'
import Truck from './truck'
import Warning from './warning'
import X from './x'
export {
Arrow,
Atm,
Attributes,
Bag,
Bubbles,
Cart,
Checkmark,
Error,
Headset,
Magnifier,
MagnifierAlt,
Notebook,
Payout,
ProductBox,
Pencil,
Regret,
TableSetting,
Shop,
ShopAlt,
Star,
Stock,
Tags,
Truck,
Warning,
X,
}
|
Make $METEOR_NPM_REBUILD_FLAGS override default flags.
|
// Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args = ["rebuild"];
flags.split(/\s+/g).forEach(function (flag) {
if (flag) {
args.push(flag);
}
});
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
|
// Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args.push.apply(args, flags.split(/\s+/g));
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
|
Include the new note order template
|
<?php include 'templates/header.php'; ?>
<div class="col-sm-12 row">
<div class="col-sm-12">
<h2>
User Options
</h2>
<p>
<form action="includes/logout.php">
<button class="btn btn-default pull-right">
Logout
</button>
</form>
</p>
<p>
Modify your options to your preferences.
</p>
<p>
<b>
Email:
</b>
<?php echo $_SESSION['user']; ?>
</p>
<?php include 'templates/color-select.html'; ?>
<?php include 'templates/note-order.html'; ?>
<?php include 'templates/password.php'; ?>
</div>
</div>
<?php echo '<script>var userId = "' . $_SESSION['userId'] . '"; </script>'; // use this to echo the session user ID for the JS to use ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/user-script.js"></script>
<?php include 'templates/footer.html'; ?>
|
<?php include 'templates/header.php'; ?>
<div class="col-sm-12 row">
<div class="col-sm-12">
<h2>
User Options
</h2>
<p>
<form action="includes/logout.php">
<button class="btn btn-default pull-right">
Logout
</button>
</form>
</p>
<p>
Modify your options to your preferences.
</p>
<p>
<b>
Email:
</b>
<?php echo $_SESSION['user']; ?>
</p>
<?php include 'templates/color-select.html'; ?>
<?php include 'templates/password.php'; ?>
</div>
</div>
<?php echo '<script>var userId = "' . $_SESSION['userId'] . '"; </script>'; // use this to echo the session user ID for the JS to use ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/user-script.js"></script>
<?php include 'templates/footer.html'; ?>
|
Update to work on full view
|
// ==UserScript==
// @name FA Cleanup
// @author Erra Boothale <erra@boothale.net>
// @namespace http://boothale.net/
// @description Fixes various annoyances with FA's user interface
// @include http://www.furaffinity.net/view/*
// @include https://www.furaffinity.net/view/*
// @include http://www.furaffinity.net/full/*
// @include https://www.furaffinity.net/full/*
// ==/UserScript==
var tables = document.querySelectorAll('.maintable'),
descTable = tables[2],
descHead = descTable.querySelectorAll('td')[0],
description = descTable.querySelectorAll('tr')[1],
sideTable = tables[3],
sideRow = sideTable.parentNode,
sideContent = sideTable.querySelectorAll('td')[1];
description.appendChild(sideContent);
sideRow.parentNode.removeChild(sideRow);
descHead.setAttribute('colspan', '2');
|
// ==UserScript==
// @name FA Cleanup
// @author Erra Boothale <erra@boothale.net>
// @namespace http://boothale.net/
// @description Fixes various annoyances with FA's user interface
// @include http://www.furaffinity.net/view/*
// @include https://www.furaffinity.net/view/*
// ==/UserScript==
var tables = document.querySelectorAll('.maintable'),
descTable = tables[2],
descHead = descTable.querySelectorAll('td')[0],
description = descTable.querySelectorAll('tr')[1],
sideTable = tables[3],
sideRow = sideTable.parentNode,
sideContent = sideTable.querySelectorAll('td')[1];
description.appendChild(sideContent);
sideRow.parentNode.removeChild(sideRow);
descHead.setAttribute('colspan', '2');
|
Switch user type check to acl
|
<?php
/**
* Outputs the admin toolbar if the user is an admin,
* otherwise simply loads jQuery for other scripts that
* may rely on it.
*/
if ($appconf['Scripts']['jquery_source'] === 'local') {
$page->add_script ('/js/jquery-1.8.3.min.js');
} elseif ($appconf['Scripts']['jquery_source'] === 'google') {
$page->add_script ('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>');
} else {
$page->add_script ('<script src="' . $appconf['Scripts']['jquery_source'] . '"></script>');
}
if (User::require_admin () && $page->preview == false) {
$page->add_style ('/apps/admin/css/jquery.jgrowl.css');
$page->add_style ('/apps/admin/css/top-bar.css');
$page->add_script ("<script>$(function(){\$.elefant_version='" . ELEFANT_VERSION . "';});</script>");
$page->add_script ('/apps/admin/js/jquery.jgrowl.min.js');
$page->add_script ('/js/jquery.cookie.js');
$page->add_script ('/apps/admin/js/top-bar.js');
}
?>
|
<?php
/**
* Outputs the admin toolbar if the user is an admin,
* otherwise simply loads jQuery for other scripts that
* may rely on it.
*/
if ($appconf['Scripts']['jquery_source'] === 'local') {
$page->add_script ('/js/jquery-1.8.3.min.js');
} elseif ($appconf['Scripts']['jquery_source'] === 'google') {
$page->add_script ('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>');
} else {
$page->add_script ('<script src="' . $appconf['Scripts']['jquery_source'] . '"></script>');
}
if (User::is_valid () && User::is ('admin') && $page->preview == false) {
$page->add_style ('/apps/admin/css/jquery.jgrowl.css');
$page->add_style ('/apps/admin/css/top-bar.css');
$page->add_script ("<script>$(function(){\$.elefant_version='" . ELEFANT_VERSION . "';});</script>");
$page->add_script ('/apps/admin/js/jquery.jgrowl.min.js');
$page->add_script ('/js/jquery.cookie.js');
$page->add_script ('/apps/admin/js/top-bar.js');
}
?>
|
Use pathlib to read ext.conf
|
import pathlib
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution("Mopidy-NAD").version
class Extension(ext.Extension):
dist_name = "Mopidy-NAD"
ext_name = "nad"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["port"] = config.String()
schema["source"] = config.String(optional=True)
schema["speakers-a"] = config.Boolean(optional=True)
schema["speakers-b"] = config.Boolean(optional=True)
return schema
def setup(self, registry):
from mopidy_nad.mixer import NadMixer
registry.add("mixer", NadMixer)
|
import os
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution("Mopidy-NAD").version
class Extension(ext.Extension):
dist_name = "Mopidy-NAD"
ext_name = "nad"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["port"] = config.String()
schema["source"] = config.String(optional=True)
schema["speakers-a"] = config.Boolean(optional=True)
schema["speakers-b"] = config.Boolean(optional=True)
return schema
def setup(self, registry):
from mopidy_nad.mixer import NadMixer
registry.add("mixer", NadMixer)
|
Add JDK 1.8 version support
Signed-off-by: Pekka Enberg <add4fcd06328a394f0ad91feda7ee057316dc5ed@iki.fi>
|
/**
* Copyright 2012 Douglas Campos <qmx@qmx.me>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.qmx.jitescript;
import org.objectweb.asm.Opcodes;
public enum JDKVersion implements Opcodes {
V1_6(Opcodes.V1_6),
V1_7(Opcodes.V1_7),
V1_8(Opcodes.V1_8);
private final int ver;
JDKVersion(int ver) {
this.ver = ver;
}
public int getVer() {
return ver;
}
}
|
/**
* Copyright 2012 Douglas Campos <qmx@qmx.me>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.qmx.jitescript;
import org.objectweb.asm.Opcodes;
public enum JDKVersion implements Opcodes {
V1_6(Opcodes.V1_6),
V1_7(Opcodes.V1_7);
private final int ver;
JDKVersion(int ver) {
this.ver = ver;
}
public int getVer() {
return ver;
}
}
|
Remove an argument of Productor.FindProduct
|
package main
type Productor struct {
items [][]string
indexes []int
ch chan []int
}
func NewProductor(items [][]string, ch chan []int) *Productor {
return &Productor{
items: items,
indexes: make([]int, len(items)),
ch: ch,
}
}
func (p *Productor) findProduct(index_i int) {
if index_i == len(p.items) {
indexes := make([]int, len(p.indexes))
copy(indexes, p.indexes)
p.ch <- indexes
return
}
for i := 0; i < len(p.items[index_i]); i++ {
p.indexes[index_i] = i
p.findProduct(index_i + 1)
}
}
func (p *Productor) FindProduct() {
p.findProduct(0)
}
func Product(items [][]string) chan []int {
ch := make(chan []int, 16)
go func() {
p := NewProductor(items, ch)
p.FindProduct()
close(p.ch)
}()
return ch
}
|
package main
type Productor struct {
items [][]string
indexes []int
ch chan []int
}
func NewProductor(items [][]string, ch chan []int) *Productor {
return &Productor{
items: items,
indexes: make([]int, len(items)),
ch: ch,
}
}
func (p *Productor) FindProduct(index_i int) {
if index_i == len(p.items) {
indexes := make([]int, len(p.indexes))
copy(indexes, p.indexes)
p.ch <- indexes
return
}
for i := 0; i < len(p.items[index_i]); i++ {
p.indexes[index_i] = i
p.FindProduct(index_i + 1)
}
}
func Product(items [][]string) chan []int {
ch := make(chan []int, 16)
go func() {
p := NewProductor(items, ch)
p.FindProduct(0)
close(p.ch)
}()
return ch
}
|
Add hashCode and equals methods.
|
package ca.corefacility.bioinformatics.irida.model;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* A password reset object.
*
* @author Josh Adam <josh.adam@phac-aspc.gc.ca>
*/
@Entity
@Table(name = "password_reset")
public class PasswordReset implements Comparable<PasswordReset> {
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
@OneToOne
@NotNull
private User user;
@Id
@NotNull
private String id;
protected PasswordReset() {
}
public PasswordReset(User user) {
this.createdDate = new Date();
this.user = user;
this.id = UUID.randomUUID().toString();
}
public Date getCreatedDate() {
return createdDate;
}
public User getUser() {
return user;
}
public String getId() {
return this.id;
}
@Override
public int compareTo(PasswordReset passwordReset) {
return createdDate.compareTo(passwordReset.createdDate);
}
@Override
public int hashCode() {
return Objects.hash(createdDate, user, id);
}
@Override
public boolean equals(Object other) {
if (other instanceof Project) {
PasswordReset p = (PasswordReset) other;
return Objects.equals(createdDate, p.createdDate) && Objects.equals(user, p.user)
&& Objects.equals(id, p.id);
}
return false;
}
}
|
package ca.corefacility.bioinformatics.irida.model;
import java.util.Date;
import java.util.UUID;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* A password reset object.
*
* @author Josh Adam <josh.adam@phac-aspc.gc.ca>
*/
@Entity
@Table(name = "password_reset")
public class PasswordReset implements Comparable<PasswordReset> {
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
@OneToOne
@NotNull
private User user;
@Id
@NotNull
private String id;
protected PasswordReset() {}
public PasswordReset(User user) {
this.createdDate = new Date();
this.user = user;
this.id = UUID.randomUUID().toString();
}
public Date getCreatedDate() {
return createdDate;
}
public User getUser() {
return user;
}
public String getId() {
return this.id;
}
@Override
public int compareTo(PasswordReset passwordReset) {
return createdDate.compareTo(passwordReset.createdDate);
}
}
|
Allow instantiating a Metadata Factory if one is not passed in the constructor to simplify instantiating the metadata registry
|
<?php
namespace Tystr\RestOrm\Metadata;
/**
* @author Tyler Stroud <tyler@tylerstroud.com>
*/
class Registry
{
/**
* @var array
*/
private $metadata = [];
/**
* @param Factory $factory
*/
public function __construct(Factory $factory = null)
{
$this->factory = $factory ?: new Factory();
}
/**
* @param Metadata $metadata
*/
public function addMetadata(Metadata $metadata)
{
$this->metadata[$metadata->getClass()] = $metadata;
}
/**
* @param string $class
*
* @return Metadata
*/
public function getMetadataForClass($class)
{
if (!isset($this->metadata[$class])) {
$this->metadata[$class] = $this->factory->create($class);
}
return $this->metadata[$class];
}
}
|
<?php
namespace Tystr\RestOrm\Metadata;
/**
* @author Tyler Stroud <tyler@tylerstroud.com>
*/
class Registry
{
/**
* @var array
*/
private $metadata = [];
/**
* @param Factory $factory
*/
public function __construct(Factory $factory)
{
$this->factory = $factory;
}
/**
* @param Metadata $metadata
*/
public function addMetadata(Metadata $metadata)
{
$this->metadata[$metadata->getClass()] = $metadata;
}
/**
* @param string $class
*
* @return Metadata
*/
public function getMetadataForClass($class)
{
if (!isset($this->metadata[$class])) {
$this->metadata[$class] = $this->factory->create($class);
}
return $this->metadata[$class];
}
}
|
Upgrade release number to 0.6.0 (oq-engine 1.3.0)
|
# coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
from openquake.risklib.scientific import (
VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
__version__ = '0.6.0'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general')
if path:
sys.exit('Found an obsolete version of commonlib; '
'please remove %s and/or fix your PYTHONPATH'
% os.path.dirname(path))
|
# coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
from openquake.risklib.scientific import (
VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
__version__ = '0.5.1'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general')
if path:
sys.exit('Found an obsolete version of commonlib; '
'please remove %s and/or fix your PYTHONPATH'
% os.path.dirname(path))
|
Include tiddlywebplugins.utils as a dependency
|
AUTHOR = 'Chris Dent'
AUTHOR_EMAIL = 'cdent@peermore.com'
MAINTAINER = 'Ben Paddock'
MAINTAINER_EMAIL = 'pads@thisispads.me.uk'
NAME = 'tiddlywebplugins.jsondispatcher'
DESCRIPTION = 'A TiddlyWeb plugin to allow the dispatching of tiddlers to non-Python handlers by serialising tiddler data to JSON'
VERSION = '0.1.0'
import os
from setuptools import setup, find_packages
setup(
namespace_packages = ['tiddlywebplugins'],
name = NAME,
version = VERSION,
description = DESCRIPTION,
long_description = file(os.path.join(os.path.dirname(__file__), 'README')).read(),
author = AUTHOR,
author_email = AUTHOR_EMAIL,
maintainer = MAINTAINER,
maintainer_email = MAINTAINER_EMAIL,
url = 'http://pypi.python.org/pypi/%s' % NAME,
packages = find_packages(exclude=['test']),
platforms = 'Posix; MacOS X; Windows',
install_requires = [
'tiddlyweb',
'tiddlywebplugins.dispatcher',
'tiddlywebplugins.utils',
'beanstalkc'
],
zip_safe = False,
)
|
AUTHOR = 'Chris Dent'
AUTHOR_EMAIL = 'cdent@peermore.com'
MAINTAINER = 'Ben Paddock'
MAINTAINER_EMAIL = 'pads@thisispads.me.uk'
NAME = 'tiddlywebplugins.jsondispatcher'
DESCRIPTION = 'A TiddlyWeb plugin to allow the dispatching of tiddlers to non-Python handlers by serialising tiddler data to JSON'
VERSION = '0.1.0'
import os
from setuptools import setup, find_packages
setup(
namespace_packages = ['tiddlywebplugins'],
name = NAME,
version = VERSION,
description = DESCRIPTION,
long_description = file(os.path.join(os.path.dirname(__file__), 'README')).read(),
author = AUTHOR,
author_email = AUTHOR_EMAIL,
maintainer = MAINTAINER,
maintainer_email = MAINTAINER_EMAIL,
url = 'http://pypi.python.org/pypi/%s' % NAME,
packages = find_packages(exclude=['test']),
platforms = 'Posix; MacOS X; Windows',
install_requires = ['tiddlyweb', 'tiddlywebplugins.dispatcher', 'beanstalkc'],
zip_safe = False,
)
|
Add `computationInputs` property to `Project` model.
|
'use strict';
const PouchDocument = require('./pouch-document');
const joi = require('joi');
/**
* @class Project
* @extends PouchDocument
* @constructor
* @property {string} name
* @property {string=} consortiumId
* @property {(File[])=} files
* @property {string=} metaFile Full path to the project's metadata CSV
*/
class Project extends PouchDocument {}
Project.schema = Object.assign({
name: joi.string().min(1).regex(/[a-zA-Z]+/, 'at least one character')
.required(),
/**
* A project's consortium's `activeComputationInputs` are stashed on the
* `computationInputs` property to ensure the user properly configures the
* project for the computation run. coinstac-client-core compares the
* consortium's computation inputs to the project's prior to run and throws
* when they don't match.
*
* @todo Find better method for guaranteeing project-to-computation input
* alignment.
*
* {@link https://github.com/MRN-Code/coinstac/issues/151}
*/
computationInputs: joi.array().default([]),
consortiumId: joi.string().optional(),
files: joi.alternatives().try(joi.array()).default([]),
metaFile: joi.array(),
metaFilePath: joi.string().min(2).optional(),
metaCovariateMapping: joi.object().default({}),
}, PouchDocument.schema);
module.exports = Project;
|
'use strict';
const PouchDocument = require('./pouch-document');
const joi = require('joi');
/**
* @class Project
* @extends PouchDocument
* @constructor
* @property {string} name
* @property {string=} consortiumId
* @property {(File[])=} files
* @property {string=} metaFile Full path to the project's metadata CSV
*/
class Project extends PouchDocument {}
Project.schema = Object.assign({
name: joi.string().min(1).regex(/[a-zA-Z]+/, 'at least one character')
.required(),
consortiumId: joi.string().optional(),
files: joi.alternatives().try(joi.array()).default([]),
metaFile: joi.array(),
metaFilePath: joi.string().min(2).optional(),
metaCovariateMapping: joi.object().default({}),
}, PouchDocument.schema);
module.exports = Project;
|
Add viewbox, fill, and fill-rule in draw command
|
var express = require('express');
var gm = require('gm');
var hashblot = require('hashblot');
function encode(str) {
return encodeURIComponent(str).replace(/%20/g,'+')}
function decode(str) {
return decodeURIComponent(str.replace(/\+/g,' '))}
module.exports = function appctor(opts) {
var gmopts = opts.gm || {};
var app = express();
app.get('/sha1q/:size/:input.png', function sha1qpPng(req, res, next) {
var str = req.params.input;
var size = req.params.size;
gm(size, size, '#fff').options(gmopts)
.draw([
'viewbox 0 0 255 255',
'fill #000',
'fill-rule nonzero',
'path', hashblot.sha1qpd(str)].join(' '))
.toBuffer('PNG',function (err, buffer) {
if (err) return next(err);
res.type('png');
res.send(buffer);
});
});
return app;
};
|
var express = require('express');
var gm = require('gm');
var hashblot = require('hashblot');
function encode(str) {
return encodeURIComponent(str).replace(/%20/g,'+')}
function decode(str) {
return decodeURIComponent(str.replace(/\+/g,' '))}
module.exports = function appctor(opts) {
var gmopts = opts.gm || {};
var app = express();
app.get('/sha1q/:size/:input.png', function sha1qpPng(req, res, next) {
var str = req.params.input;
gm(req.params.size, req.params.size, '#fff')
.options(gmopts)
.fill('#000').draw('path ' + hashblot.sha1qpd(str))
.toBuffer('PNG',function (err, buffer) {
if (err) return next(err);
res.type('png');
res.send(buffer);
});
});
return app;
};
|
Change log level to info
|
angular.module('app.task')
.controller('TaskListContentController', TaskListContentController);
/*@ngInject*/
function TaskListContentController($state, taskService) {
var vm = this;
vm.tasks = undefined;
vm.edit = edit;
activate();
function activate() {
return getTasks().then(function () {
console.info('TaskListContentController activated.');
});
}
function edit(task) {
$state.go('task.edit', { id: task.id });
}
function getTasks() {
return taskService.getTasks()
.then(function (tasks) {
vm.tasks = tasks;
});
}
}
|
angular.module('app.task')
.controller('TaskListContentController', TaskListContentController);
/*@ngInject*/
function TaskListContentController($state, taskService) {
var vm = this;
vm.tasks = undefined;
vm.edit = edit;
activate();
function activate() {
return getTasks().then(function () {
console.log('TaskListContentController activated.');
});
}
function edit(task) {
$state.go('task.edit', { id: task.id });
}
function getTasks() {
return taskService.getTasks()
.then(function (tasks) {
vm.tasks = tasks;
});
}
}
|
Include confirmation key in context object.
This way our templates can reference the confirmation key later.
(imported from commit 4d57e1309386f2236829b6fdf4e4ad43c5b125c8)
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2008, Jarek Zgoda <jarek.zgoda@gmail.com>
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
'key': confirmation_key,
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2008, Jarek Zgoda <jarek.zgoda@gmail.com>
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
|
Add a cached ballot fetcher to the DevsDC helper
If we happen to run out of RAM in Lambda (we won't), Lambda will just
kill the function and invoke a new one next time.
|
import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
self.ballot_cache = {}
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
def ballot_request(self, ballot_paper_id):
if ballot_paper_id not in self.ballot_cache:
r = self.make_request("elections/{}".format(ballot_paper_id))
if r.status_code == 200:
self.ballot_cache[ballot_paper_id] = r
else:
return r
return self.ballot_cache[ballot_paper_id]
|
import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
|
Include typeof check in JSONP callback response.
This is more robust, and helps against attacks such as Rosetta Flash:
https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
|
import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If the response is a redirect, the callback will be dealt
# on the next request:
if response.status_code == 302:
return response
else:
cb = request.GET.get('callback')
if cb and re.match('[a-zA-Z0-9_$.]+$', cb):
cb = cb.encode('utf-8')
response.content = b'typeof ' + cb + b" === 'function' && " + cb + b'(' + response.content + b')'
response.status_code = 200 # Must return OK for JSONP to be processed
return response
|
import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If the response is a redirect, the callback will be dealt
# on the next request:
if response.status_code == 302:
return response
else:
if request.GET.get('callback') and re.match('[a-zA-Z0-9_$.]+$', request.GET.get('callback')):
response.content = request.GET.get('callback').encode('utf-8') + b'(' + response.content + b')'
response.status_code = 200 # Must return OK for JSONP to be processed
return response
|
Use a better regex to avoid transforming all modules
|
module.exports = {
roots: ['<rootDir>/src/', '<rootDir>/test/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
'\\.m?jsx?$': 'jest-esm-transformer',
},
testMatch: ['**/unit/**/*-test.ts{,x}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
setupFiles: ['<rootDir>/test/globals.ts', '<rootDir>/test/unit-test-env.ts'],
setupFilesAfterEnv: ['<rootDir>/test/setup-test-framework.ts'],
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!**/node_modules/**',
'!**/vendor/**',
'!**/*.d.*',
// not focused on testing these areas currently
'!src/cli/**/*',
'!src/crash/**/*',
'!src/highlighter/**/*',
// ignore index files
'!**/index.ts',
],
reporters: ['default', '<rootDir>../script/jest-actions-reporter.js'],
coverageReporters: ['text-summary', 'json', 'html', 'cobertura'],
// For now, @github Node modules required to be transformed by jest-esm-transformer
transformIgnorePatterns: ['node_modules/(?!(@github))'],
}
|
module.exports = {
roots: ['<rootDir>/src/', '<rootDir>/test/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
'\\.m?jsx?$': 'jest-esm-transformer',
},
testMatch: ['**/unit/**/*-test.ts{,x}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
setupFiles: ['<rootDir>/test/globals.ts', '<rootDir>/test/unit-test-env.ts'],
setupFilesAfterEnv: ['<rootDir>/test/setup-test-framework.ts'],
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!**/node_modules/**',
'!**/vendor/**',
'!**/*.d.*',
// not focused on testing these areas currently
'!src/cli/**/*',
'!src/crash/**/*',
'!src/highlighter/**/*',
// ignore index files
'!**/index.ts',
],
reporters: ['default', '<rootDir>../script/jest-actions-reporter.js'],
coverageReporters: ['text-summary', 'json', 'html', 'cobertura'],
transformIgnorePatterns: ['node_modules/temp'],
}
|
Fix linking new device to user.
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Device extends Model
{
static $rules = [
'template_id' => 'required|integer',
'udid' => 'required|regex:/^[a-z0-9]{16}$/',
'name' => 'required|max:255'
];
protected $fillable = ['user_id', 'template_id', 'udid', 'name'];
public $timestamps = true;
public $relationships = ['users', 'template'];
public $setCurrentUserIdOnCreate = true;
// Used by App\Http\Controllers\Api\DeviceController
public $user_id = 0;
function users ()
{
return $this->belongsToMany(User::class, 'user_devices')->withTimestamps();
}
function template ()
{
return $this->belongsTo(Template::class);
}
function setUserIdAttribute ($val)
{
$this->user_id = $val;
}
function getUserIdsAttribute ()
{
return $this->users->pluck('id')->toArray() + [(int) $this->user_id];
}
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Device extends Model
{
static $rules = [
'template_id' => 'required|integer',
'udid' => 'required|regex:/^[a-z0-9]{16}$/',
'name' => 'required|max:255'
];
protected $fillable = ['user_id', 'template_id', 'udid', 'name'];
public $timestamps = true;
public $relationships = ['users', 'template'];
public $setCurrentUserIdOnCreate = true;
// Used by App\Http\Controllers\Api\DeviceController
protected $userId = 0;
function users ()
{
return $this->belongsToMany(User::class, 'user_devices')->withTimestamps();
}
function template ()
{
return $this->belongsTo(Template::class);
}
function setUserIdAttribute ($val)
{
$this->userId = $val;
}
function getUserIdsAttribute ()
{
return $this->users->pluck('id')->toArray() + [(int) $this->userId];
}
}
|
Remove name field. It already exists
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0013_make_rendition_upload_callable'),
('catalogue', '0010_auto_20160616_1048'),
]
operations = [
migrations.AddField(
model_name='category',
name='description',
field=models.TextField(verbose_name='Description', blank=True),
),
migrations.AddField(
model_name='category',
name='image',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True),
)
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0013_make_rendition_upload_callable'),
('catalogue', '0010_auto_20160616_1048'),
]
operations = [
migrations.AddField(
model_name='category',
name='description',
field=models.TextField(verbose_name='Description', blank=True),
),
migrations.AddField(
model_name='category',
name='image',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True),
),
migrations.AddField(
model_name='category',
name='name',
field=models.CharField(max_length=255, verbose_name='Name', db_index=True),
),
]
|
Print one name at a time.
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
print(generate_name())
|
from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn.cursor()
adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()
conn.close()
r = random.random()
if r < 0.001 or r >= 0.999:
return rare
elif r < 0.3 and uncommon_anim is not None:
return ' '.join((adj, uncommon_anim[0]))
elif r >= 0.7 and uncommon_adj is not None:
return ' '.join((uncommon_adj[0], anim))
return ' '.join((adj, anim))
if __name__ == '__main__':
for _ in range(20):
print(generate_name())
|
Use https for git dependency
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
setup(
name="atsy",
version="0.0.1",
description="AreTheySlimYet",
long_description="A set of tools for measuring cross-browser, cross-platform memory usage.",
url="https://github.com/EricRahm/atsy",
author="Eric Rahm",
author_email="erahm@mozilla.com",
license="MPL 2.0",
classifiers=[
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"
],
packages=["atsy"],
install_requires=[
"selenium",
"marionette-client",
"psutil==3.5.0",
],
dependency_links=[
# We need to use a fork of psutil until USS calculations get integrated.
"git+https://github.com/ericrahm/psutil@release-3.5.0#egg=psutil-3.5.0"
],
)
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
setup(
name="atsy",
version="0.0.1",
description="AreTheySlimYet",
long_description="A set of tools for measuring cross-browser, cross-platform memory usage.",
url="https://github.com/EricRahm/atsy",
author="Eric Rahm",
author_email="erahm@mozilla.com",
license="MPL 2.0",
classifiers=[
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"
],
packages=["atsy"],
install_requires=[
"selenium",
"marionette-client",
"psutil==3.5.0",
],
dependency_links=[
# We need to use a fork of psutil until USS calculations get integrated.
"git+ssh://git@github.com/ericrahm/psutil@release-3.5.0#egg=psutil-3.5.0"
],
)
|
Add test for MotorAsyncIOReference await support
|
from umongo import Document
from umongo.dal.motor_asyncio import MotorAsyncIOReference
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
|
from umongo import Document
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
|
Use a smaller set of users in fake game two gameplay
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from ...models import (
Transcript, TranscriptPhraseVote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()[:5]
transcript = Transcript.objects.random_transcript(
in_progress=False
).first()
phrases = transcript.phrases.all()[:5]
for phrase in phrases:
for user in users:
TranscriptPhraseVote.objects.create(
transcript_phrase=phrase,
user=user,
upvote=random.choice([True, False])
)
update_transcript_stats(transcript)
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from ...models import (
Transcript, TranscriptPhraseVote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for phrase in phrases:
for user in users:
TranscriptPhraseVote.objects.create(
transcript_phrase=phrase,
user=user,
upvote=random.choice([True, False])
)
update_transcript_stats(transcript)
|
Enable disk cache for PhJS
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.ikravets.com/#!" + unquote(qs[19:])
response = check_output([
"phantomjs", "--disk-cache=true", "--load-images=false",
"crawler.js", url
])
if "404 Not Found" in response:
status = "404 Not Found"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
status = "500 Internal Server Error"
else:
url = "http://platformio.ikravets.com/#!" + unquote(qs[19:])
response = check_output(["phantomjs",
"--load-images=false", "crawler.js", url])
if "404 Not Found" in response:
status = "404 Not Found"
start_response(status, [("Content-Type", "text/html"),
("Content-Length", str(len(response)))])
return response
|
Remove holder item as not used anymore
|
package flickr.demo.qvdev.com.flickrdemo;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import flickr.demo.qvdev.com.flickrdemo.dummy.DummyContent;
class FlickrItemRecyclerViewAdapter
extends RecyclerView.Adapter<FlickrViewHolder> {
private final List<DummyContent.DummyItem> mItems;
FlickrItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mItems = items;
}
@Override
public FlickrViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.flickritem_list_content, parent, false);
return new FlickrViewHolder(view);
}
@Override
public void onBindViewHolder(final FlickrViewHolder holder, int position) {
holder.mIdView.setText(mItems.get(position).id);
holder.mContentView.setText(mItems.get(position).content);
}
@Override
public int getItemCount() {
return mItems.size();
}
}
|
package flickr.demo.qvdev.com.flickrdemo;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import flickr.demo.qvdev.com.flickrdemo.dummy.DummyContent;
class FlickrItemRecyclerViewAdapter
extends RecyclerView.Adapter<FlickrViewHolder> {
private final List<DummyContent.DummyItem> mItems;
FlickrItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mItems = items;
}
@Override
public FlickrViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.flickritem_list_content, parent, false);
return new FlickrViewHolder(view);
}
@Override
public void onBindViewHolder(final FlickrViewHolder holder, int position) {
holder.mItem = mItems.get(position);
holder.mIdView.setText(mItems.get(position).id);
holder.mContentView.setText(mItems.get(position).content);
}
@Override
public int getItemCount() {
return mItems.size();
}
}
|
Add a todo comment for forms test case
|
package com.ushahidi.android.data.api.model;
import com.ushahidi.android.BuildConfig;
import com.ushahidi.android.data.api.BaseApiTestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static com.google.common.truth.Truth.assertThat;
import static com.ushahidi.android.data.TestHelper.getResource;
/**
* @author Ushahidi Team <team@ushahidi.com>
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormsTest extends BaseApiTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void shouldSuccessfullyDeserializeForms() throws IOException {
final String formJson = getResource("forms.json");
final Forms forms = gson.fromJson(formJson, Forms.class);
assertThat(forms).isNotNull();
// TODO: Test the remanining fields
}
}
|
package com.ushahidi.android.data.api.model;
import com.ushahidi.android.BuildConfig;
import com.ushahidi.android.data.api.BaseApiTestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static com.google.common.truth.Truth.assertThat;
import static com.ushahidi.android.data.TestHelper.getResource;
/**
* @author Ushahidi Team <team@ushahidi.com>
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormsTest extends BaseApiTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void shouldSuccessfullyDeserializeForms() throws IOException {
final String formJson = getResource("forms.json");
final Forms forms = gson.fromJson(formJson, Forms.class);
assertThat(forms).isNotNull();
}
}
|
Stop pylint complaining about bare-except
|
"""
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (if available),
* hostname
* uname
* environment variables
Returns:
dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ``
"""
env = {}
try:
env['python_packages'] = [str(p) for p in pip.get_installed_distributions()]
except: # pylint: disable=bare-except
pass
env['hostname'] = socket.gethostname()
env['uname'] = os.uname()
env['environ'] = dict(os.environ)
return env
|
"""
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (if available),
* hostname
* uname
* environment variables
Returns:
dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ``
"""
env = {}
try:
env['python_packages'] = [str(p) for p in pip.get_installed_distributions()]
except:
pass
env['hostname'] = socket.gethostname()
env['uname'] = os.uname()
env['environ'] = dict(os.environ)
return env
|
Fix "element.getAttribute is not a function" Selenium errors when filling in fields
The root cause was the locator strategy was naively returning an element that was not a form field, causing Selenium's internals to blow up
|
// Credit to: http://simonwillison.net/2006/Jan/20/escape/
RegExp.escape = function(text) {
if (!arguments.callee.sRE) {
var specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
arguments.callee.sRE = new RegExp(
'(\\' + specials.join('|\\') + ')', 'g'
);
}
return text.replace(arguments.callee.sRE, '\\$1');
}
var allLabels = inDocument.getElementsByTagName("label");
var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i');
var candidateLabels = $A(allLabels).select(function(candidateLabel){
var labelText = getText(candidateLabel).strip();
return (labelText.search(regExp) >= 0);
});
if (candidateLabels.length == 0) {
return null;
}
//reverse length sort
candidateLabels = candidateLabels.sortBy(function(s) {
return s.length * -1;
});
var locatedLabel = candidateLabels.first();
var labelFor = locatedLabel.getAttribute('for');
if ((labelFor == null) && (locatedLabel.hasChildNodes())) {
return locatedLabel.getElementsByTagName('button')[0]
|| locatedLabel.getElementsByTagName('input')[0]
|| locatedLabel.getElementsByTagName('textarea')[0]
|| locatedLabel.getElementsByTagName('select')[0];
}
return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);
|
RegExp.escape = function(text) {
if (!arguments.callee.sRE) {
var specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
arguments.callee.sRE = new RegExp(
'(\\' + specials.join('|\\') + ')', 'g'
);
}
return text.replace(arguments.callee.sRE, '\\$1');
}
var allLabels = inDocument.getElementsByTagName("label");
var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i');
var candidateLabels = $A(allLabels).select(function(candidateLabel){
var labelText = getText(candidateLabel).strip();
return (labelText.search(regExp) >= 0);
});
if (candidateLabels.length == 0) {
return null;
}
//reverse length sort
candidateLabels = candidateLabels.sortBy(function(s) {
return s.length * -1;
});
var locatedLabel = candidateLabels.first();
var labelFor = locatedLabel.getAttribute('for');
if ((labelFor == null) && (locatedLabel.hasChildNodes())) {
// TODO: should find the first form field, not just any node
return locatedLabel.firstChild;
}
return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);
|
Load package version from flake8_coding.py
|
# -*- coding: utf-8 -*-
from setuptools import setup
from flake8_coding import __version__
setup(
name='flake8-coding',
version=__version__,
description='Adds coding magic comment checks to flake8',
long_description=open("README.rst").read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
author='Takeshi KOMIYA',
author_email='i.tkomiya at gmail.com',
url='https://github.com/tk0miya/flake8-coding',
license='Apache License 2.0',
keywords='pep8 flake8 coding',
py_modules=['flake8_coding'],
install_requires=[
'flake8',
],
entry_points={
'flake8.extension': ['C10 = flake8_coding:CodingChecker'],
},
)
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='flake8-coding',
version='0.1.0',
description='Adds coding magic comment checks to flake8',
long_description=open("README.rst").read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
author='Takeshi KOMIYA',
author_email='i.tkomiya at gmail.com',
url='https://github.com/tk0miya/flake8-coding',
license='Apache License 2.0',
keywords='pep8 flake8 coding',
py_modules=['flake8_coding'],
install_requires=[
'flake8',
],
entry_points={
'flake8.extension': ['C10 = flake8_coding:CodingChecker'],
},
)
|
Correct variables, and have it add to number given in get request.
|
<html>
<head>
<title>Number Counter</title>
</head>
<body>
<?php
$date = $_GET['date'];
if (!isset($num)) die("Give me a number boo");
if ($num < 0) die ("Yo, digits are not valid, bro...");
$num = $numend;
echo "<h2>Counting towards ".$date.":"."</h2>";
for ($num=$numend; $numend>=0; $numend++)
{
echo $numend."<br>";
}
print "<br><br>";
echo "<h2>Counting backwards from ".$numend.":"."</h2>";
print "<br>";
for ($num=$numend; $num>=$numstart; $num--)
{
echo $num."<br>";
}
?>
<br>
</body>
</html>
|
<html>
<head>
<title>Number Counter</title>
</head>
<body>
<?php
$date = $_GET['date'];
if (!isset($date)) die("Give me a number boo");
if ($date < 0) die ("Yo, digits are not valid, bro...");
$date = $numend;
$numstart=0;
echo "<h2>Counting towards ".$date.":"."</h2>";
for ($date>=$numstart; $date=$numend; $numend++)
{
echo $numend."<br>";
}
print "<br><br>";
echo "<h2>Counting backwards from ".$numend.":"."</h2>";
print "<br>";
for ($num=$numend; $num>=$numstart; $num--)
{
echo $num."<br>";
}
?>
<br>
</body>
</html>
|
Change pin LED is connected to.
|
from apiclient import errors
import threading
import time
import RPi.GPIO as GPIO
import GmailAuthorization
PIN = 35
CHECK_INTERVAL = 30
service = None
unread_count = 0
def refresh():
global unread_count
try:
messages = service.users().messages().list(userId='me', q='is:inbox + is:unread').execute()
unread_count = messages['resultSizeEstimate']
except errors.HttpError as error:
print('An error occurred: {0}'.format(error))
def indicator():
while True:
if unread_count > 0:
GPIO.output(PIN, not GPIO.input(PIN))
else:
GPIO.output(PIN, GPIO.LOW)
time.sleep(0.5)
def monitor():
while True:
refresh()
time.sleep(CHECK_INTERVAL)
def start_indicator():
t = threading.Thread(target=indicator)
t.daemon = True
t.start()
def start_monitor():
t = threading.Thread(target=monitor)
t.daemon = True
t.start()
def load_service():
global service
service = GmailAuthorization.get_service()
def start():
load_service()
start_indicator()
start_monitor()
|
from apiclient import errors
import threading
import time
import RPi.GPIO as GPIO
import GmailAuthorization
PIN = 22
CHECK_INTERVAL = 30
service = None
unread_count = 0
def refresh():
global unread_count
try:
messages = service.users().messages().list(userId='me', q='is:inbox + is:unread').execute()
unread_count = messages['resultSizeEstimate']
except errors.HttpError as error:
print('An error occurred: {0}'.format(error))
def indicator():
while True:
if unread_count > 0:
GPIO.output(PIN, not GPIO.input(PIN))
else:
GPIO.output(PIN, GPIO.LOW)
time.sleep(0.5)
def monitor():
while True:
refresh()
time.sleep(CHECK_INTERVAL)
def start_indicator():
t = threading.Thread(target=indicator)
t.daemon = True
t.start()
def start_monitor():
t = threading.Thread(target=monitor)
t.daemon = True
t.start()
def load_service():
global service
service = GmailAuthorization.get_service()
def start():
load_service()
start_indicator()
start_monitor()
|
Add docstrings for sigproc benchmarks
|
""" Test the sigproc read function """
from timeit import default_timer as timer
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class SigprocBenchmarker(PipelineBenchmarker):
""" Test the sigproc read function """
def run_benchmark(self):
with bf.Pipeline() as pipeline:
fil_file = "../../../data/1chan8bitNoDM.fil"
data = blocks.read_sigproc([fil_file], gulp_nframe=4096)
data.on_data = self.timeit(data.on_data)
start = timer()
pipeline.run()
end = timer()
self.total_clock_time = end-start
sigproc_benchmarker = SigprocBenchmarker()
print sigproc_benchmarker.average_benchmark(10)
|
from timeit import default_timer as timer
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class SigprocBenchmarker(PipelineBenchmarker):
def run_benchmark(self):
with bf.Pipeline() as pipeline:
fil_file = "../../../data/1chan8bitNoDM.fil"
data = blocks.read_sigproc([fil_file], gulp_nframe=4096)
data.on_data = self.timeit(data.on_data)
start = timer()
pipeline.run()
end = timer()
self.total_clock_time = end-start
sigproc_benchmarker = SigprocBenchmarker()
print sigproc_benchmarker.average_benchmark(10)
|
Fix autoformat issue on new file
|
/*global atom*/
module.exports = {
formatter: function () {
if (!this.standardFormat) {
this.standardFormat = require('standard-format')
}
return this.standardFormat
},
activate: function () {
this.commands = atom.commands.add('atom-workspace', 'standard-formatter:format', this.format.bind(this))
this.editorObserver = atom.workspace.observeTextEditors(this.handleEvents.bind(this))
},
deactivate: function () {
this.commands.dispose()
this.editorObserver.dispose()
},
format: function () {
var editor = atom.workspace.getActivePaneItem()
var text = editor.getText()
var transformed = this.formatter().transform(text)
editor.setText(transformed)
},
handleEvents: function (editor) {
editor.getBuffer().onWillSave(function () {
var path = editor.getPath()
if (!path) return
var ext = path.substring(path.length - 3)
var formatOnSave = atom.config.get('standard-formatter.formatOnSave', {scope: editor.getRootScopeDescriptor()})
if (ext === '.js' && formatOnSave) {
this.format()
}
}.bind(this))
},
config: {
formatOnSave: {
type: 'boolean',
default: false
}
}
}
|
/*global atom*/
module.exports = {
formatter: function () {
if (!this.standardFormat) {
this.standardFormat = require('standard-format')
}
return this.standardFormat
},
activate: function () {
this.commands = atom.commands.add('atom-workspace', 'standard-formatter:format', this.format.bind(this))
this.editorObserver = atom.workspace.observeTextEditors(this.handleEvents.bind(this))
},
deactivate: function () {
this.commands.dispose()
this.editorObserver.dispose()
},
format: function () {
var editor = atom.workspace.getActivePaneItem()
var text = editor.getText()
var transformed = this.formatter().transform(text)
editor.setText(transformed)
},
handleEvents: function (editor) {
editor.getBuffer().onWillSave(function () {
var path = editor.getPath()
var ext = path.substring(path.length - 3)
var formatOnSave = atom.config.get('standard-formatter.formatOnSave', {scope: editor.getRootScopeDescriptor()})
if (ext === '.js' && formatOnSave) {
this.format()
}
}.bind(this))
},
config: {
formatOnSave: {
type: 'boolean',
default: false
}
}
}
|
Fix for environments without process var
|
var parser = require('js-yaml')
var optionalByteOrderMark = '\\ufeff?'
var platform = typeof process !== 'undefined' ? process.platform : ''
var pattern = '^(' +
optionalByteOrderMark +
'(= yaml =|---)' +
'$([\\s\\S]*?)' +
'^(?:\\2|\\.\\.\\.)\\s*' +
'$' +
(platform === 'win32' ? '\\r?' : '') +
'(?:\\n)?)'
// NOTE: If this pattern uses the 'g' flag the `regex` variable definition will
// need to be moved down into the functions that use it.
var regex = new RegExp(pattern, 'm')
module.exports = extractor
module.exports.test = test
function extractor (string) {
string = string || ''
var lines = string.split(/(\r?\n)/)
if (lines[0] && /= yaml =|---/.test(lines[0])) {
return parse(string)
} else {
return { attributes: {}, body: string }
}
}
function parse (string) {
var match = regex.exec(string)
if (!match) {
return {
attributes: {},
body: string
}
}
var yaml = match[match.length - 1].replace(/^\s+|\s+$/g, '')
var attributes = parser.load(yaml) || {}
var body = string.replace(match[0], '')
return { attributes: attributes, body: body, frontmatter: yaml }
}
function test (string) {
string = string || ''
return regex.test(string)
}
|
var parser = require('js-yaml')
var optionalByteOrderMark = '\\ufeff?'
var pattern = '^(' +
optionalByteOrderMark +
'(= yaml =|---)' +
'$([\\s\\S]*?)' +
'^(?:\\2|\\.\\.\\.)\\s*' +
'$' +
(process.platform === 'win32' ? '\\r?' : '') +
'(?:\\n)?)'
// NOTE: If this pattern uses the 'g' flag the `regex` variable definition will
// need to be moved down into the functions that use it.
var regex = new RegExp(pattern, 'm')
module.exports = extractor
module.exports.test = test
function extractor (string) {
string = string || ''
var lines = string.split(/(\r?\n)/)
if (lines[0] && /= yaml =|---/.test(lines[0])) {
return parse(string)
} else {
return { attributes: {}, body: string }
}
}
function parse (string) {
var match = regex.exec(string)
if (!match) {
return {
attributes: {},
body: string
}
}
var yaml = match[match.length - 1].replace(/^\s+|\s+$/g, '')
var attributes = parser.load(yaml) || {}
var body = string.replace(match[0], '')
return { attributes: attributes, body: body, frontmatter: yaml }
}
function test (string) {
string = string || ''
return regex.test(string)
}
|
Update repository endpoint location for BI server
|
/**
* Repository query
*/
var SavedQuery = Backbone.Model.extend({
parse: function(response, XHR) {
this.xml = response.xml;
},
url: function() {
var segment = Settings.BIPLUGIN ?
"/pentahorepository/" : "/repository/";
return encodeURI(Saiku.session.username + segment + this.get('name'));
},
move_query_to_workspace: function(model, response) {
var query = new Query({
xml: model.xml
}, {
name: model.get('name')
});
var tab = Saiku.tabs.add(new Workspace({ query: query }));
}
});
/**
* Repository adapter
*/
var Repository = Backbone.Collection.extend({
model: SavedQuery,
initialize: function(args, options) {
this.dialog = options.dialog;
},
parse: function(response) {
this.dialog.populate(response);
},
url: function() {
var segment = Settings.BIPLUGIN ?
"/pentahorepository" : "/repository";
return encodeURI(Saiku.session.username + segment);
}
});
|
/**
* Repository query
*/
var SavedQuery = Backbone.Model.extend({
parse: function(response, XHR) {
this.xml = response.xml;
},
url: function() {
return encodeURI(Saiku.session.username + "/repository/" + this.get('name'));
},
move_query_to_workspace: function(model, response) {
var query = new Query({
xml: model.xml
}, {
name: model.get('name')
});
var tab = Saiku.tabs.add(new Workspace({ query: query }));
}
});
/**
* Repository adapter
*/
var Repository = Backbone.Collection.extend({
model: SavedQuery,
initialize: function(args, options) {
this.dialog = options.dialog;
},
parse: function(response) {
this.dialog.populate(response);
},
url: function() {
return encodeURI(Saiku.session.username + "/repository");
}
});
|
Add an implicit wait of 1 second
|
import os
import pytest
from pyvirtualdisplay import Display
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
REPORTS_DIR = "reports"
@pytest.fixture(scope='function')
def webdriver(request):
display = Display(visible=0, size=(800, 600), use_xauth=True)
display.start()
options = Options()
options.add_argument("--no-sandbox")
driver = Chrome(chrome_options=options)
driver.implicitly_wait(1)
prev_failed_tests = request.session.testsfailed
yield driver
if prev_failed_tests != request.session.testsfailed:
try:
os.makedirs(REPORTS_DIR)
except os.error:
pass
test_name = request.function.__module__ + "." + request.function.__name__
driver.save_screenshot(f"reports/{test_name}.png")
with open(f"reports/{test_name}.html", "w") as f:
f.write(driver.page_source)
driver.quit()
display.stop()
|
import os
import pytest
from pyvirtualdisplay import Display
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
REPORTS_DIR = "reports"
@pytest.fixture(scope='function')
def webdriver(request):
display = Display(visible=0, size=(800, 600), use_xauth=True)
display.start()
options = Options()
options.add_argument("--no-sandbox")
driver = Chrome(chrome_options=options)
prev_failed_tests = request.session.testsfailed
yield driver
if prev_failed_tests != request.session.testsfailed:
try:
os.makedirs(REPORTS_DIR)
except os.error:
pass
test_name = request.function.__module__ + "." + request.function.__name__
driver.save_screenshot(f"reports/{test_name}.png")
with open(f"reports/{test_name}.html", "w") as f:
f.write(driver.page_source)
driver.quit()
display.stop()
|
Fix for enzyme and react 15
|
"use strict";
/**
* Webpack frontend test configuration.
*/
var path = require("path");
var prodCfg = require("./webpack.config");
// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();
var _ = require("lodash"); // devDependency
module.exports = {
cache: true,
context: path.join(ROOT, "test/client"),
entry: "./main",
output: {
filename: "main.js",
publicPath: "/assets/"
},
resolve: _.merge({}, prodCfg.resolve, {
alias: {
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
sinon: "node_modules/sinon/pkg/sinon.js",
// Allow root import of `src/FOO` from ROOT/src.
src: path.join(ROOT, "src")
}
}),
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
externals: {
"cheerio": "window",
"react/lib/ExecutionEnvironment": true,
"react/lib/ReactContext": true,
"react/addons": true
},
module: _.assign({}, prodCfg.module, {
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
noParse: [
/\/sinon\.js/
]
}),
devtool: "source-map"
};
|
"use strict";
/**
* Webpack frontend test configuration.
*/
var path = require("path");
var prodCfg = require("./webpack.config");
// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();
var _ = require("lodash"); // devDependency
module.exports = {
cache: true,
context: path.join(ROOT, "test/client"),
entry: "./main",
output: {
filename: "main.js",
publicPath: "/assets/"
},
resolve: _.merge({}, prodCfg.resolve, {
alias: {
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
sinon: "node_modules/sinon/pkg/sinon.js",
// Allow root import of `src/FOO` from ROOT/src.
src: path.join(ROOT, "src")
}
}),
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
externals: {
"cheerio": "window",
"react/lib/ExecutionEnvironment": true,
"react/lib/ReactContext": true
},
module: _.assign({}, prodCfg.module, {
// enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
noParse: [
/\/sinon\.js/
]
}),
devtool: "source-map"
};
|
Upgrade menu widget to use yiistrap
|
<?php
Yii::import('bootstrap.widgets.TbNav');
class MlLanguageMenu extends TbNav
{
/**
* Initializes the widget.
*/
public function init()
{
$languages = Yii::app()->getLanguages();
$activeLocale = Yii::app()->language;
$items = array(array('label'=>'Language'));
foreach ($languages as $locale => $language)
{
if ($locale === $activeLocale)
$activeLanguage = $language;
$items[] = array(
'label' => $language,
'url' => array('/site/changeLanguage', 'locale'=>$locale),
'active' => $locale === $activeLocale,
);
}
$label = isset($activeLanguage) ? $activeLanguage : 'Unknown';
$this->items = array_merge(array(array('label'=> $label, 'items'=>$items)), $this->items);
parent::init();
}
}
|
<?php
Yii::import('bootstrap.widgets.TbMenu');
class MlLanguageMenu extends TbMenu
{
/**
* Initializes the widget.
*/
public function init()
{
$languages = Yii::app()->getLanguages();
$activeLocale = Yii::app()->language;
$items = array(array('label'=>'Language'));
foreach ($languages as $locale => $language)
{
if ($locale === $activeLocale)
$activeLanguage = $language;
$items[] = array(
'label' => $language,
'url' => array('/site/changeLanguage', 'locale'=>$locale),
'active' => $locale === $activeLocale,
);
}
$label = isset($activeLanguage) ? $activeLanguage : 'Unknown';
$this->items = array_merge(array(array('label'=> $label, 'items'=>$items)), $this->items);
parent::init();
}
}
|
Add support for css Keyframes properties
|
<?php
namespace Neilime\AssetsBundle\Service\Filter;
class CssFilter implements \Neilime\AssetsBundle\Service\Filter\FilterInterface{
/**
* @param string $sContent
* @see \Neilime\AssetsBundle\Service\Filter\FilterInterface::run()
* @throws \Exception
* @return string
*/
public function run($sContent){
if(!is_string($sContent))throw new \Exception('Content is not a string : '.gettype($sContent));
return \CssMin::minify(
$sContent,
array(
'ConvertLevel3AtKeyframes' => array('RemoveSource' => false),
'ConvertLevel3Properties' => true
),
array(
'ConvertFontWeight' => true,
'ConvertHslColors' => true,
'ConvertRgbColors' => true,
'ConvertNamedColors' => true,
'CompressColorValues' => true,
'CompressUnitValues' => true,
'CompressExpressionValues' => true
)
);
}
}
|
<?php
namespace Neilime\AssetsBundle\Service\Filter;
class CssFilter implements \Neilime\AssetsBundle\Service\Filter\FilterInterface{
/**
* @param string $sContent
* @see \Neilime\AssetsBundle\Service\Filter\FilterInterface::run()
* @throws \Exception
* @return string
*/
public function run($sContent){
if(!is_string($sContent))throw new \Exception('Content is not a string : '.gettype($sContent));
return \CssMin::minify(
$sContent,
null,
array(
'ConvertHslColors' => true,
'ConvertRgbColors' => true,
'ConvertNamedColors' => true,
'CompressColorValues' => true,
'CompressUnitValues' => true,
'CompressExpressionValues' => true
)
);
}
}
|
Fix test failures after method renames
|
import unittest
import re
import importlib
import importlib_metadata
class BasicTests(unittest.TestCase):
version_pattern = r'\d+\.\d+(\.\d)?'
def test_retrieves_version_of_self(self):
dist = importlib_metadata.Distribution.from_module(importlib_metadata)
assert isinstance(dist.version, str)
assert re.match(self.version_pattern, dist.version)
def test_retrieves_version_of_pip(self):
"""
Assume pip is installed and retrieve the version of pip.
"""
pip = importlib.import_module('pip')
dist = importlib_metadata.Distribution.from_module(pip)
assert isinstance(dist.version, str)
assert re.match(self.version_pattern, dist.version)
def test_for_name_does_not_exist(self):
with self.assertRaises(importlib_metadata.PackageNotFound):
importlib_metadata.Distribution.from_name('does-not-exist')
|
import unittest
import re
import importlib
import importlib_metadata
class BasicTests(unittest.TestCase):
version_pattern = r'\d+\.\d+(\.\d)?'
def test_retrieves_version_of_self(self):
dist = importlib_metadata.Distribution.for_module(importlib_metadata)
assert isinstance(dist.version, str)
assert re.match(self.version_pattern, dist.version)
def test_retrieves_version_of_pip(self):
"""
Assume pip is installed and retrieve the version of pip.
"""
pip = importlib.import_module('pip')
dist = importlib_metadata.Distribution.for_module(pip)
assert isinstance(dist.version, str)
assert re.match(self.version_pattern, dist.version)
def test_for_name_does_not_exist(self):
with self.assertRaises(importlib_metadata.PackageNotFound):
importlib_metadata.Distribution.for_name('does-not-exist')
|
Add different prefixes for the experiments
|
#!/usr/bin/env python
template = """#!/bin/bash
#PBS -l walltime=72:00:00
#PBS -l nodes=1:ppn=1
cd /RQusagers/vanmerb/rnnencdec
export PYTHONPATH=/RQusagers/vanmerb/rnnencdec/groundhog-private/:$PYTHONPATH
python /RQusagers/vanmerb/rnnencdec/groundhog-private/scripts/RNN_Enc_Dec_Phrase.py \"{options}\" >{log} 2>&1"""
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
#!/usr/bin/env python
template = """#!/bin/bash
#PBS -l walltime=72:00:00
#PBS -l nodes=1:ppn=1
cd /RQusagers/vanmerb/rnnencdec
export PYTHONPATH=/RQusagers/vanmerb/rnnencdec/groundhog-private/:$PYTHONPATH
python /RQusagers/vanmerb/rnnencdec/groundhog-private/scripts/RNN_Enc_Dec_Phrase.py \"{options}\" >{log} 2>&1"""
params = [
("dict(dim=250, dim_mlp=250)", "run1"),
("dict(dim=500, dim_mlp=500)", "run2"),
("dict(rank_n_approx=200)", "run3"),
("dict(rank_n_approx=500)", "run4"),
("dict(avg_word=False)", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
Make Pholio description behave as a remarkup field (e.g., subscribe mentioned users)
Summary: Ref T12732. This is pre-existing but fix it since I caught it while banging around.
Test Plan: {F4967442}
Reviewers: chad, amckinley
Reviewed By: chad
Maniphest Tasks: T12732
Differential Revision: https://secure.phabricator.com/D17970
|
<?php
final class PholioMockDescriptionTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'description';
public function generateOldValue($object) {
return $object->getDescription();
}
public function applyInternalEffects($object, $value) {
$object->setDescription($value);
}
public function getTitle() {
return pht(
"%s updated the mock's description.",
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the description for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function shouldHide() {
$old = $this->getOldValue();
return ($old === null);
}
public function hasChangeDetailView() {
return true;
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
return $changes;
}
}
|
<?php
final class PholioMockDescriptionTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'description';
public function generateOldValue($object) {
return $object->getDescription();
}
public function applyInternalEffects($object, $value) {
$object->setDescription($value);
}
public function getTitle() {
return pht(
"%s updated the mock's description.",
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the description for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function shouldHide() {
$old = $this->getOldValue();
return ($old === null);
}
public function hasChangeDetailView() {
return true;
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
}
|
Migrate away from componentWillMount in declarative bootstrap container
|
/* eslint-disable no-underscore-dangle */
import PropTypes from 'prop-types';
import { Component } from 'react';
import bootstrap from 'bootstrap';
/**
* Component that declaratively wraps logic for idempotently bootstrapping the library. Client code
* can be contained within the children of this component at the highest level of the application.
*/
export default class Elemental extends Component {
static propTypes = {
fontOpts: PropTypes.shape({
primary: PropTypes.shape({
regular: PropTypes.string,
bold: PropTypes.string,
}),
secondary: PropTypes.shape({
regular: PropTypes.string,
bold: PropTypes.string,
}),
}),
colorOpts: PropTypes.shape({
primary: PropTypes.string,
primaryLight: PropTypes.string,
primaryDark: PropTypes.string,
}),
children: PropTypes.node.isRequired,
};
static defaultProps = {
fontOpts: {},
colorOpts: {},
};
componentDidMount() {
const { fontOpts, colorOpts } = this.props;
// Idempotent bootstrapping by caching initialization state in a global key
if (!window.__REACT_ELEMENTAL_BOOTSTRAPPED__) {
bootstrap(fontOpts, colorOpts);
window.__REACT_ELEMENTAL_BOOTSTRAPPED__ = true;
}
}
render() {
return this.props.children;
}
}
|
/* eslint-disable no-underscore-dangle */
import PropTypes from 'prop-types';
import { Component } from 'react';
import bootstrap from 'bootstrap';
/**
* Component that declaratively wraps logic for idempotently bootstrapping the library. Client code
* can be contained within the children of this component at the highest level of the application.
*/
export default class Elemental extends Component {
static propTypes = {
fontOpts: PropTypes.shape({
primary: PropTypes.shape({
regular: PropTypes.string,
bold: PropTypes.string,
}),
secondary: PropTypes.shape({
regular: PropTypes.string,
bold: PropTypes.string,
}),
}),
colorOpts: PropTypes.shape({
primary: PropTypes.string,
primaryLight: PropTypes.string,
primaryDark: PropTypes.string,
}),
children: PropTypes.node.isRequired,
};
static defaultProps = {
fontOpts: {},
colorOpts: {},
};
componentWillMount() {
const { fontOpts, colorOpts } = this.props;
// Idempotent bootstrapping by caching initialization state in a global key
if (!window.__REACT_ELEMENTAL_BOOTSTRAPPED__) {
bootstrap(fontOpts, colorOpts);
window.__REACT_ELEMENTAL_BOOTSTRAPPED__ = true;
}
}
render() {
return this.props.children;
}
}
|
Correct input type for password in Login
|
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
class LoginForm extends Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label htmlFor="email">Email: </label>
<Field name="email" component="input" type="text" />
</div>
<div>
<label htmlFor="password">Password: </label>
<Field name="password" component="input" type="password" />
</div>
<button type="submit">Login</button>
</form>
)
}
}
export default reduxForm({
form: 'signup'
})(LoginForm)
|
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
class LoginForm extends Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label htmlFor="email">Email: </label>
<Field name="email" component="input" type="text" />
</div>
<div>
<label htmlFor="password">Password: </label>
<Field name="password" component="input" type="text" />
</div>
<button type="submit">Login</button>
</form>
)
}
}
export default reduxForm({
form: 'signup'
})(LoginForm)
|
Piwik: Mark sidemenu entry as active
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.plugins import WPJinjaMixinPlugin
from MaKaC.webinterface.pages.conferences import WPConferenceModifBase
class WPStatistics(WPJinjaMixinPlugin, WPConferenceModifBase):
sidemenu_option = 'statistics'
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.plugins import WPJinjaMixinPlugin
from MaKaC.webinterface.pages.conferences import WPConferenceModifBase
class WPStatistics(WPJinjaMixinPlugin, WPConferenceModifBase):
active_menu_item = 'statistics'
|
Remove the default tab if there aren't any fields in it
|
<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
* @package PyroCMS
* @subpackage Streams Tabs Helper
* @author Chris Harvey <chris@chrisnharvey.com>
* @license MIT
*/
/**
* Build a tabs array for streams
*
* @param array $tabs Your associative tab array
* @param string $stream Stream slug
* @param string $namespace Stream namesapce
* @param string $default The default tab where other fields will go if they have not been assigned to a tab
* @return array The tabs array ready to be passed into $this->streams->cp->entry_form()
*/
function build_tabs($tabs, $stream, $namespace = null, $default = 'general')
{
$fields = ci()->streams->streams->get_assignments($stream, $namespace);
foreach ($fields as $field) $tabs[$default]['fields'][$field->field_slug] = $field->field_slug;
foreach ($tabs as $key => $tab) {
if ($key == $default) continue;
foreach ($fields as $field) {
if (in_array($field->field_slug, $tab['fields'])) {
unset($tabs[$default]['fields'][$field->field_slug]);
}
}
}
if (empty($tabs[$default]['fields'])) unset($tabs[$default]);
return $tabs;
}
|
<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
* @package PyroCMS
* @subpackage Streams Tabs Helper
* @author Chris Harvey <chris@chrisnharvey.com>
* @license MIT
*/
/**
* Build a tabs array for streams
*
* @param array $tabs Your associative tab array
* @param string $stream Stream slug
* @param string $namespace Stream namesapce
* @param string $default The default tab where other fields will go if they have not been assigned to a tab
* @return array The tabs array ready to be passed into $this->streams->cp->entry_form()
*/
function build_tabs($tabs, $stream, $namespace = null, $default = 'general')
{
$fields = ci()->streams->streams->get_assignments($stream, $namespace);
foreach ($fields as $field) $tabs[$default]['fields'][$field->field_slug] = $field->field_slug;
foreach ($tabs as $key => $tab) {
if ($key == $default) continue;
foreach ($fields as $field) {
if (in_array($field->field_slug, $tab['fields'])) {
unset($tabs[$default]['fields'][$field->field_slug]);
}
}
}
return $tabs;
}
|
Change click number to user polls
|
'use strict';
(function () {
// var addButton = document.querySelector('.btn-add');
// var deleteButton = document.querySelector('.btn-delete');
var userPolls = document.querySelector('#user-polls');
// var loginButton = document.querySelector('.')
var apiUrl = appUrl + '/api/:id/polls';
function updateUserPolls (data) {
var pollsObject = JSON.parse(data);
// polls should be an array so fix this
userPolls.innerHTML = pollsObject.polls;
}
// ajaxFunctions.ready(ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls));
addButton.addEventListener('click', function () {
ajaxFunctions.ajaxRequest('POST', apiUrl, function () {
ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls);
});
}, false);
// deleteButton.addEventListener('click', function () {
// ajaxFunctions.ajaxRequest('DELETE', apiUrl, function () {
// ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls);
// });
// }, false);
})();
|
'use strict';
(function () {
// var addButton = document.querySelector('.btn-add');
// var deleteButton = document.querySelector('.btn-delete');
var clickNbr = document.querySelector('#click-nbr');
// var loginButton = document.querySelector('.')
var apiUrl = appUrl + '/api/:id/polls';
function updateUserPolls (data) {
var clicksObject = JSON.parse(data);
clickNbr.innerHTML = clicksObject.clicks;
}
// ajaxFunctions.ready(ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls));
addButton.addEventListener('click', function () {
ajaxFunctions.ajaxRequest('POST', apiUrl, function () {
ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls);
});
}, false);
// deleteButton.addEventListener('click', function () {
// ajaxFunctions.ajaxRequest('DELETE', apiUrl, function () {
// ajaxFunctions.ajaxRequest('GET', apiUrl, updateUserPolls);
// });
// }, false);
})();
|
Fix codemirror include for built version of examples.
|
yepnope([
{
test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
// Load for IE < 9
yep : [
'../flotr2.ie.min.js'
]
},
'../flotr2.js',
'lib/codemirror/lib/codemirror.js',
'lib/codemirror/mode/javascript/javascript.js',
'lib/beautify.js',
'lib/randomseed.js',
'lib/jquery-1.7.1.min.js',
// Examples
'../flotr2.examples.min.js',
'../flotr2.examples.types.js',
{ complete : function () {
if (Flotr.ExamplesCallback) {
Flotr.ExamplesCallback();
} else {
Examples = new Flotr.Examples({
node : document.getElementById('examples')
});
}
}
}
]);
|
yepnope([
{
test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
// Load for IE < 9
yep : [
'../flotr2.ie.min.js'
]
},
'../flotr2.js',
'lib/google-code-prettify/prettify.js',
'lib/beautify.js',
'lib/randomseed.js',
'lib/jquery-1.7.1.min.js',
// Examples
'../flotr2.examples.min.js',
'../flotr2.examples.types.js',
{ complete : function () {
if (Flotr.ExamplesCallback) {
Flotr.ExamplesCallback();
} else {
Examples = new Flotr.Examples({
node : document.getElementById('examples')
});
}
}
}
]);
|
Make command block do something
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.my_first_block = function() {
console.log("Hello world!");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.my_first_block = function() {
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
Adjust audio button position, size
|
function AudioButton() {
var that = this;
this.position = {
x: 15.5,
y: 0.4
};
if (typeof localStorage.soundActivated === 'undefined') {
localStorage.soundActivated = "1";
}
this.on = !!localStorage.soundActivated;
setTimeout(function() {
createjs.Sound.setMute(!that.on);
mm.music.volume = !!that.on * 0.4;
}, 10);
}
AudioButton.prototype.render = function() {
var sprite = this.on ? this.sprite_on : this.sprite_off;
ctx.save();
var scaler = sprite.width * GU * 0.00015;
ctx.translate(this.position.x * GU, this.position.y * GU);
ctx.scale(scaler, scaler);
ctx.drawImage(sprite, -sprite.width / 2, -sprite.height / 2);
ctx.restore();
};
AudioButton.prototype.pause = function() {
this.musicElement.pause && this.musicElement.pause();
localStorage.soundActivated = "";
};
AudioButton.prototype.toggleActivated = function() {
this.on = !this.on;
createjs.Sound.setMute(!this.on);
mm.music.volume = !!this.on * 0.4;
localStorage.soundActivated = this.on ? "1" : "";
};
|
function AudioButton() {
var that = this;
this.position = {
x: 15.5,
y: 0.5
};
if (typeof localStorage.soundActivated === 'undefined') {
localStorage.soundActivated = "1";
}
this.on = !!localStorage.soundActivated;
setTimeout(function() {
createjs.Sound.setMute(!that.on);
mm.music.volume = !!that.on * 0.4;
}, 10);
}
AudioButton.prototype.render = function() {
var sprite = this.on ? this.sprite_on : this.sprite_off;
ctx.save();
var scaler = sprite.width * GU * 0.00025;
ctx.translate(this.position.x * GU, this.position.y * GU);
ctx.scale(scaler, scaler);
ctx.drawImage(sprite, -sprite.width / 2, -sprite.height / 2);
ctx.restore();
};
AudioButton.prototype.pause = function() {
this.musicElement.pause && this.musicElement.pause();
localStorage.soundActivated = "";
};
AudioButton.prototype.toggleActivated = function() {
this.on = !this.on;
createjs.Sound.setMute(!this.on);
mm.music.volume = !!this.on * 0.4;
localStorage.soundActivated = this.on ? "1" : "";
};
|
Remove unsupported python 3.4 from trove classifiers
|
from setuptools import find_packages, setup
version = '0.1.0'
setup(
author='Charlie Denton',
author_email='charlie@meshy.co.uk',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Communications :: Chat :: Internet Relay Chat',
],
description='An asynchronous IRC framework/library based upon asyncio',
include_package_data=True,
install_requires=[
'cchardet>=0.3.5,<2',
],
name='framewirc',
packages=find_packages(exclude=['tests']),
url='https://github.com/meshy/framewirc/',
version=version,
)
|
from setuptools import find_packages, setup
version = '0.1.0'
setup(
author='Charlie Denton',
author_email='charlie@meshy.co.uk',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Communications :: Chat :: Internet Relay Chat',
],
description='An asynchronous IRC framework/library based upon asyncio',
include_package_data=True,
install_requires=[
'cchardet>=0.3.5,<2',
],
name='framewirc',
packages=find_packages(exclude=['tests']),
url='https://github.com/meshy/framewirc/',
version=version,
)
|
[Client] Use %q to generate quoted values in airtable query
|
package redirect
import (
"fmt"
"github.com/fabioberger/airtable-go"
)
const (
// DefaultRedirectKey should be fetched if the requested key is not found.
DefaultRedirectKey = "default"
redirectTableName = "Redirects"
)
// Client uses Airtable to implement Redirector.
type Client struct {
airtableGo *airtable.Client
}
type airtableRecord struct {
AirtableID string
Fields Redirect
}
// NewClient builds an instance of client.
func NewClient(apiKey string, baseID string) (*Client, error) {
airtableGo, err := airtable.New(apiKey, baseID)
return &Client{airtableGo: airtableGo}, err
}
// Get implements Redirector.
func (c *Client) Get(key string) (*Redirect, error) {
var records []airtableRecord
err := c.airtableGo.ListRecords(
redirectTableName,
&records,
airtable.ListParameters{FilterByFormula: fmt.Sprintf("{Key} = %q", key), MaxRecords: 1},
)
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, fmt.Errorf("redirect %q not found", key)
}
return &records[0].Fields, nil
}
|
package redirect
import (
"fmt"
"github.com/fabioberger/airtable-go"
)
const (
// DefaultRedirectKey should be fetched if the requested key is not found.
DefaultRedirectKey = "default"
redirectTableName = "Redirects"
)
// Client uses Airtable to implement Redirector.
type Client struct {
airtableGo *airtable.Client
}
type airtableRecord struct {
AirtableID string
Fields Redirect
}
// NewClient builds an instance of client.
func NewClient(apiKey string, baseID string) (*Client, error) {
airtableGo, err := airtable.New(apiKey, baseID)
return &Client{airtableGo: airtableGo}, err
}
// Get implements Redirector.
func (c *Client) Get(key string) (*Redirect, error) {
var records []airtableRecord
err := c.airtableGo.ListRecords(
redirectTableName,
&records,
airtable.ListParameters{FilterByFormula: fmt.Sprintf("{Key} = '%s'", key), MaxRecords: 1},
)
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, fmt.Errorf("redirect %s not found", key)
}
return &records[0].Fields, nil
}
|
Use Github's cache, but store for offline access
|
import Rx from 'rx';
import request from 'axios';
import moment from 'moment';
const INDEX_URL = "http://tldr-pages.github.io/assets/index.json";
let search = (name) => {
return getIndex()
.filter( cmd => {
return cmd.name === name
})
.last( { platform: ["client"], name: "not-found" } );
};
let requestIndex = function *() {
let requestOptions = {
method: 'GET',
url: INDEX_URL,
withCredentials: false
};
let modifiedSince = localStorage.getItem("tldr/index.cache");
// Yes, that's right, it's the string "undefined"...gee.
if(modifiedSince !== "undefined" && modifiedSince !== undefined) {
requestOptions.headers = {
'If-Modified-Since': modifiedSince
};
}
let response = yield request(requestOptions);
return response;
};
let getIndex = () => {
return Rx.Observable.spawn(requestIndex).tap( (response) => {
let ifModifiedSince = response.headers["last-modified"];
localStorage.setItem("tldr/index.cache", ifModifiedSince);
let commands = response.data.commands;
localStorage.setItem("tldr/index", JSON.stringify(commands));
}).flatMap( res => res.data.commands )
}
let Command = {
search,
getIndex
};
export { Command };
|
import Rx from 'rx';
import request from 'axios';
import moment from 'moment';
const INDEX_URL = "http://tldr-pages.github.io/assets/index.json";
let search = (name) => {
return getIndex()
.filter( cmd => {
return cmd.name === name
})
.last( { platform: ["client"], name: "not-found" } );
};
let requestIndex = function *() {
let requestOptions = {
method: 'GET',
url: INDEX_URL,
withCredentials: false
};
let index = yield request(requestOptions);
let commands = index.data.commands || [];
return commands;
};
let getIndex = () => {
let _commands = JSON.parse(localStorage.getItem("tldr_index"));
if(_commands && _commands.length > 0) {
return Rx.Observable.fromArray(_commands);
} else {
return Rx.Observable.spawn(requestIndex).tap( (commands) => {
localStorage.setItem("tldr_index", JSON.stringify(commands));
}).flatMap( list => list )
}
}
let Command = {
search,
getIndex
};
export { Command };
|
Change name to pyqtool (available on PyPI)
|
from setuptools import setup
VERSION = '0.0.1'
setup(
name='pyqtool',
version=VERSION,
description="Search Python code with jQuery-like selectors",
author="Caio Ariede",
author_email="caio.ariede@gmail.com",
url="http://github.com/caioariede/pyq",
license="MIT",
zip_safe=False,
platforms=["any"],
packages=['pyq', 'sizzle'],
entry_points={
'console_scripts': ['pyq = pyq.pyq:main'],
},
classifiers=[
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
],
include_package_data=True,
install_requires=[
'click==6.2',
'Pygments==2.1',
'regex==2016.1.10',
'astor==0.5',
]
)
|
from setuptools import setup
VERSION = '0.0.1'
setup(
name='pyq',
version=VERSION,
description="Search Python code with jQuery-like selectors",
author="Caio Ariede",
author_email="caio.ariede@gmail.com",
url="http://github.com/caioariede/pyq",
license="MIT",
zip_safe=False,
platforms=["any"],
packages=['pyq', 'sizzle'],
entry_points={
'console_scripts': ['pyq = pyq.pyq:main'],
},
classifiers=[
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
],
include_package_data=True,
install_requires=[
'click==6.2',
'Pygments==2.1',
'regex==2016.1.10',
'astor==0.5',
]
)
|
Fix gulp script (run metascript after clean).
|
var gulp = require('gulp');
var metascriptPipe = require('gulp-metascript');
var headerPipe = require('gulp-header');
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');
gulp.task('metascript', ['clean'], function () {
return gulp.src('Sources/**/*.js')
.pipe(metascriptPipe())
.pipe(headerPipe("/* It is auto-generated file. Do not modify it. */\n"))
.pipe(chmod({ write: false }))
.on('error', logError)
.pipe(gulp.dest('../Libraries/'));
});
gulp.task('clean', function () {
return gulp.src('../Libraries', { read: false })
.pipe(clean({ force: true }));
});
gulp.task('build-Debug', ['metascript']);
gulp.task('build-Release', ['metascript']);
/*Helpers*/
function logError(error) {
console.error(error.message);
process.exit(1);
}
|
var gulp = require('gulp');
var metascriptPipe = require('gulp-metascript');
var headerPipe = require('gulp-header');
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');
gulp.task('metascript', function () {
return gulp.src('Sources/**/*.js')
.pipe(metascriptPipe())
.pipe(headerPipe("/* It is auto-generated file. Do not modify it. */\n"))
.pipe(chmod({ write: false }))
.on('error', logError)
.pipe(gulp.dest('../Libraries/'));
});
gulp.task('clean', function () {
return gulp.src('../Libraries/', { read: false })
.pipe(clean({ force: true }));
});
gulp.task('build-Debug', ['clean', 'metascript']);
gulp.task('build-Release', ['clean', 'metascript']);
/*Helpers*/
function logError(error) {
console.error(error.message);
process.exit(1);
}
|
Use an empty write instead of drain event. Closes gh-5, gh-4.
|
/*
* exit
* https://github.com/cowboy/node-exit
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exit(exitCode, streams) {
if (!streams) { streams = [process.stdout, process.stderr]; }
var drainCount = 0;
// Actually exit if all streams are drained.
function tryToExit() {
if (drainCount === streams.length) {
process.exit(exitCode);
}
}
streams.forEach(function(stream) {
// Count drained streams now, but monitor non-drained streams.
if (stream.bufferSize === 0) {
drainCount++;
} else {
stream.write('', 'utf-8', function() {
drainCount++;
tryToExit();
});
}
// Prevent further writing.
stream.write = function() {};
});
// If all streams were already drained, exit now.
tryToExit();
// In Windows, when run as a Node.js child process, a script utilizing
// this library might just exit with a 0 exit code, regardless. This code,
// despite the fact that it looks a bit crazy, appears to fix that.
process.on('exit', function() {
process.exit(exitCode);
});
};
|
/*
* exit
* https://github.com/cowboy/node-exit
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exit(exitCode, streams) {
if (!streams) { streams = [process.stdout, process.stderr]; }
var drainCount = 0;
// Actually exit if all streams are drained.
function tryToExit() {
if (drainCount === streams.length) {
process.exit(exitCode);
}
}
streams.forEach(function(stream) {
// Prevent further writing.
stream.write = function() {};
// Count drained streams now, but monitor non-drained streams.
if (stream.bufferSize === 0) {
drainCount++;
} else {
stream.once('drain', function() {
drainCount++;
tryToExit();
});
}
});
// If all streams were already drained, exit now.
tryToExit();
// In Windows, when run as a Node.js child process, a script utilizing
// this library might just exit with a 0 exit code, regardless. This code,
// despite the fact that it looks a bit crazy, appears to fix that.
process.on('exit', function() {
process.exit(exitCode);
});
};
|
Remove related model data attribute not included
|
'use strict';
var _ = require('lodash');
var debug = require('ghost-ignition').debug('format');
var Mapper = require('./vendor/jsonapi-mapper');
var defaultSerializerOptions = {};
var defaultMapperOptions = {enableLinks: true};
module.exports = function format(api, apiReq, apiRes) {
if (!apiRes || _.isEmpty(apiRes.model)) {
debug('Nothing to format :(');
// We don't throw an error, but return empty
// This allows us to support, empty delete responses etc
return;
}
debug('mapping to JSONAPI');
// Apply any defaults that weren't overridden
_.defaults(apiRes.serializerOptions, defaultSerializerOptions);
_.defaults(apiRes.mapperOptions, defaultMapperOptions);
var mapper = Mapper(api.baseUrl, apiRes.serializerOptions);
var json = mapper.map(apiRes.model, apiRes.type, apiRes.mapperOptions);
var includes = apiReq.query.options.include;
// Omit data attribute from related models that have not been included
// This is a workaround for jsonapi-mapper bug - https://github.com/scoutforpets/jsonapi-mapper/issues/69
_.each(json.data.relationships, function (v, k) {
json.data.relationships[k] = !_.includes(includes, k) ? _.omit(v, 'data') : v;
});
debug('returning');
return json;
};
|
'use strict';
var _ = require('lodash');
var debug = require('ghost-ignition').debug('format');
var Mapper = require('./vendor/jsonapi-mapper');
var defaultSerializerOptions = {};
var defaultMapperOptions = {enableLinks: true};
module.exports = function format(api, apiReq, apiRes) {
if (!apiRes || _.isEmpty(apiRes.model)) {
debug('Nothing to format :(');
// We don't throw an error, but return empty
// This allows us to support, empty delete responses etc
return;
}
debug('mapping to JSONAPI');
// Apply any defaults that weren't overridden
_.defaults(apiRes.serializerOptions, defaultSerializerOptions);
_.defaults(apiRes.mapperOptions, defaultMapperOptions);
var mapper = Mapper(api.baseUrl, apiRes.serializerOptions);
var json = mapper.map(apiRes.model, apiRes.type, apiRes.mapperOptions);
debug('returning');
return json;
};
|
Check that command is not null before saving.
|
/*
* Copyright 2015, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.server.storage.filesystem;
import org.spine3.server.storage.CommandStorage;
import org.spine3.server.storage.CommandStoreRecord;
import static com.google.common.base.Preconditions.checkNotNull;
public class FileSystemCommandStorage extends CommandStorage {
@Override
protected void write(CommandStoreRecord record) {
checkNotNull(record, "CommandRecord shouldn't be null.");
Helper.write(record);
}
}
|
/*
* Copyright 2015, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.server.storage.filesystem;
import org.spine3.server.storage.CommandStorage;
import org.spine3.server.storage.CommandStoreRecord;
public class FileSystemCommandStorage extends CommandStorage {
@Override
protected void write(CommandStoreRecord record) {
Helper.write(record);
}
}
|
Check only the files that are staged for commit
|
<?php
namespace GrumPHP\Locator;
use Gitonomy\Git\Diff\File;
use Gitonomy\Git\Repository;
use GrumPHP\Collection\FilesCollection;
use SplFileInfo;
/**
* Class Git
*
* @package GrumPHP\Locator
*/
class ChangedFiles implements LocatorInterface
{
/**
* @var Repository
*/
protected $repository;
/**
* @param Repository $repository
*/
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
/**
* @return FilesCollection
*/
public function locate()
{
$diff = $this->repository->getWorkingCopy()->getDiffStaged();
$files = array();
/** @var File $file */
foreach ($diff->getFiles() as $file) {
if ($file->isDeletion()) {
continue;
}
$fileName = $file->isRename() ? $file->getNewName() : $file->getName();
$files[] = new SplFileInfo($fileName);
}
return new FilesCollection($files);
}
}
|
<?php
namespace GrumPHP\Locator;
use Gitonomy\Git\Diff\File;
use Gitonomy\Git\Repository;
use GrumPHP\Collection\FilesCollection;
use SplFileInfo;
/**
* Class Git
*
* @package GrumPHP\Locator
*/
class ChangedFiles implements LocatorInterface
{
/**
* @var Repository
*/
protected $repository;
/**
* @param Repository $repository
*/
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
/**
* @return FilesCollection
*/
public function locate()
{
$diff = $this->repository->getDiff('HEAD');
$files = array();
/** @var File $file */
foreach ($diff->getFiles() as $file) {
if ($file->isDeletion()) {
continue;
}
$fileName = $file->isRename() ? $file->getNewName() : $file->getName();
$files[] = new SplFileInfo($fileName);
}
return new FilesCollection($files);
}
}
|
Use new extension setup() API
|
from __future__ import unicode_literals
import os
from mopidy import ext, config
__version__ = '0.2'
class SubsonicExtension(ext.Extension):
dist_name = 'Mopidy-Subsonic'
ext_name = 'subsonic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf')
return config.read(conf_file)
def get_config_schema(self):
schema = super(SubsonicExtension, self).get_config_schema()
schema['hostname'] = config.Hostname()
schema['port'] = config.Port()
schema['username'] = config.String()
schema['password'] = config.Secret()
schema['ssl'] = config.Boolean()
return schema
def setup(self, registry):
from .actor import SubsonicBackend
registry.add('backend', SubsonicBackend)
|
from __future__ import unicode_literals
import os
from mopidy import ext, config
__version__ = '0.2'
class SubsonicExtension(ext.Extension):
dist_name = 'Mopidy-Subsonic'
ext_name = 'subsonic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf')
return config.read(conf_file)
def get_config_schema(self):
schema = super(SubsonicExtension, self).get_config_schema()
schema['hostname'] = config.Hostname()
schema['port'] = config.Port()
schema['username'] = config.String()
schema['password'] = config.Secret()
schema['ssl'] = config.Boolean()
return schema
def get_backend_classes(self):
from .actor import SubsonicBackend
return [SubsonicBackend]
|
Add logger to events.persons module
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from flask import session
from indico.core import signals
from indico.core.logger import Logger
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem
logger = Logger.get('events.persons')
@signals.menu.items.connect_via('event-management-sidemenu')
def _sidemenu_items(sender, event, **kwargs):
if event.type == 'lecture' or not event.can_manage(session.user):
return
return SideMenuItem('lists', _('Roles'), url_for('persons.person_list', event), section='reports')
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from flask import session
from indico.core import signals
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem
@signals.menu.items.connect_via('event-management-sidemenu')
def _sidemenu_items(sender, event, **kwargs):
if event.type == 'lecture' or not event.can_manage(session.user):
return
return SideMenuItem('lists', _('Roles'), url_for('persons.person_list', event), section='reports')
|
Remove .only on socket game controller tests
|
const CONSTANTS = require('../../../data/constants');
const gameController = require('../../../../app/socket/controllers/game');
const knex = require('../../../../app/lib/db');
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const should = chai.should();
describe('Game Socket Functions: ', () => {
before((done) => {
// Run initial migrations and seed db
knex.migrate.rollback()
.then(() => {
knex.migrate.latest()
.then(() => {
knex.seed.run()
.then(() => done());
});
});
});
it('Should pass socket next_round', (done) => {
gameController.nextRound(1, () => {
setTimeout(() => {
gameController.getGameById(1, (game) => {
game.round_phase.should.equal(0);
game.current_round.should.equal(1);
done();
});
}, CONSTANTS.TIMEOUT);
});
});
});
|
const CONSTANTS = require('../../../data/constants');
const gameController = require('../../../../app/socket/controllers/game');
const knex = require('../../../../app/lib/db');
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const should = chai.should();
describe.only('Game Socket Functions: ', () => {
before((done) => {
// Run initial migrations and seed db
knex.migrate.rollback()
.then(() => {
knex.migrate.latest()
.then(() => {
knex.seed.run()
.then(() => done());
});
});
});
it('Should pass socket next_round', (done) => {
gameController.nextRound(1, () => {
setTimeout(() => {
gameController.getGameById(1, (game) => {
game.round_phase.should.equal(0);
game.current_round.should.equal(1);
done();
});
}, CONSTANTS.TIMEOUT);
});
});
});
|
Update failing metadata settings acceptance test.
|
# disable missing docstring
#pylint: disable=C0111
from lettuce import world, step
@step('I see the correct settings and default values$')
def i_see_the_correct_settings_and_values(step):
world.verify_all_setting_entries([['Default Speed', '', False],
['Display Name', 'default', True],
['Download Track', '', False],
['Download Video', '', False],
['Show Captions', 'True', False],
['Speed: .75x', '', False],
['Speed: 1.25x', '', False],
['Speed: 1.5x', '', False]])
|
# disable missing docstring
#pylint: disable=C0111
from lettuce import world, step
@step('I see the correct settings and default values$')
def i_see_the_correct_settings_and_values(step):
world.verify_all_setting_entries([['.75x', '', False],
['1.25x', '', False],
['1.5x', '', False],
['Display Name', 'default', True],
['Normal Speed', '', False],
['Show Captions', 'True', False],
['Source', '', False],
['Track', '', False]])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.