text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add a random param to the S3 URL so that Slack will always expand the image
|
var connect = require('connect');
var PORT = process.env.PORT || 5000;
var diffy = require('./diffy');
var http = require('http');
var postMessage = require('./lib/post_message');
var app = connect()
.use(require('body-parser').urlencoded({ extended: true }))
.use(function(req, res){
if (req.body.token && req.body.token === process.env.AUTH_TOKEN) {
diffy(decodeURIComponent(req.body.url), function (err, s3Url) {
if (err) {
res.statusCode = 500;
res.end('Something went horribly wrong: ' + err.message);
return;
}
// Nothing has changed
if (!s3Url) {
res.statusCode = 204;
res.end();
return;
}
// Post the message to slack
postMessage(s3Url + '?' + Math.round(Math.random() * 1e4), function (err) {
if (err) {
res.statusCode = 500;
res.end('Failed to post message to Slack ' + err.message);
return;
}
res.statusCode = 200;
res.end(s3Url);
});
});
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
http.createServer(app).listen(PORT);
|
var connect = require('connect');
var PORT = process.env.PORT || 5000;
var diffy = require('./diffy');
var http = require('http');
var postMessage = require('./lib/post_message');
var app = connect()
.use(require('body-parser').urlencoded({ extended: true }))
.use(function(req, res){
if (req.body.token && req.body.token === process.env.AUTH_TOKEN) {
diffy(decodeURIComponent(req.body.url), function (err, s3Url) {
if (err) {
res.statusCode = 500;
res.end('Something went horribly wrong: ' + err.message);
return;
}
// Nothing has changed
if (!s3Url) {
res.statusCode = 204;
res.end();
return;
}
// Post the message to slack
postMessage(s3Url, function (err) {
if (err) {
res.statusCode = 500;
res.end('Failed to post message to Slack ' + err.message);
return;
}
res.statusCode = 200;
res.end(s3Url);
});
});
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
http.createServer(app).listen(PORT);
|
Allow for local run of example and demos installed with tool.
|
from __future__ import division
import os
import numpy as np
import scipy.io
import scipy.ndimage.interpolation
def load_head_phantom(number_of_voxels=None):
if number_of_voxels is None:
number_of_voxels = np.array((128, 128, 128))
dirname = os.path.dirname(__file__)
dirname = os.path.join(dirname,'../../../Common/data/head.mat')
if not os.path.isfile(dirname):
dirname = os.path.dirname(__file__)
dirname = os.path.join(dirname,'./../../data/head.mat')
test_data = scipy.io.loadmat(dirname)
# Loads data in F_CONTIGUOUS MODE (column major), convert to Row major
image = test_data['img'].transpose(2,1,0).copy()
image_dimensions = image.shape
zoom_x = number_of_voxels[0] / image_dimensions[0]
zoom_y = number_of_voxels[1] / image_dimensions[1]
zoom_z = number_of_voxels[2] / image_dimensions[2]
# TODO: add test for this is resizing and not simply zooming
resized_image = scipy.ndimage.interpolation.zoom(image, (zoom_x, zoom_y, zoom_z), order=3, prefilter=False)
return resized_image
|
from __future__ import division
import os
import numpy as np
import scipy.io
import scipy.ndimage.interpolation
def load_head_phantom(number_of_voxels=None):
if number_of_voxels is None:
number_of_voxels = np.array((128, 128, 128))
dirname = os.path.dirname(__file__)
dirname = os.path.join(dirname,'../../../Common/data/head.mat')
test_data = scipy.io.loadmat(dirname)
# Loads data in F_CONTIGUOUS MODE (column major), convert to Row major
image = test_data['img'].transpose(2,1,0).copy()
image_dimensions = image.shape
zoom_x = number_of_voxels[0] / image_dimensions[0]
zoom_y = number_of_voxels[1] / image_dimensions[1]
zoom_z = number_of_voxels[2] / image_dimensions[2]
# TODO: add test for this is resizing and not simply zooming
resized_image = scipy.ndimage.interpolation.zoom(image, (zoom_x, zoom_y, zoom_z), order=3, prefilter=False)
return resized_image
|
Add test for POST request
|
var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;
var fs = require('fs');
var server = require(__dirname + '/../index.js');
describe('our NLP sever', function() {
before(function(done) {
fs.readFile(__dirname + '/../public/index.html', function(err, data) {
if(err) throw err;
this.html = data.toString();
done();
}.bind(this));
});
it('should respond to a GET request with our index page', function(done) {
chai.request('localhost:3000')
.get('/')
.end(function(err, res) {
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(res.text).to.eql(this.html);
done();
}.bind(this));
});
it('should respond to a POST request to the process URL', function(done){
chai.request('localhost:3000')
.post('/process')
.type('form')
.send('text=You talking to me?')
.end(function(err, res){
expect(err).to.eql(null);
expect(res.text).to.eql('{"you":1,"talking":1,"to":1,"me":1}')
done();
})
})
});
|
var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;
var fs = require('fs');
var server = require(__dirname + '/../index.js');
describe('our NLP sever', function() {
before(function(done) {
fs.readFile(__dirname + '/../public/index.html', function(err, data) {
if(err) throw err;
this.html = data.toString();
done();
}.bind(this));
});
it('should respond to a get request with our index page', function(done) {
chai.request('localhost:3000')
.get('/')
.end(function(err, res) {
expect(err).to.eql(null);
expect(res.status).to.eql(200);
expect(res.text).to.eql(this.html);
done();
}.bind(this));
});
});
|
Remove eslint disable, and add flow
|
//@flow
import React from 'react';
import cx from 'classnames';
import styles from './index.css';
type Props = {
children?: any,
className?: string,
justifyContent?: string,
alignItems?: string,
flexWrap?: string,
style?: any,
container?: boolean,
flex?: any
};
export const FlexRow = ({
children,
className,
justifyContent,
alignItems,
flexWrap,
style,
...rest
}: Props) => (
<div
className={cx(styles.row, className)}
style={{
justifyContent,
alignItems,
flexWrap,
...style
}}
{...rest}
>
{children}
</div>
);
export const FlexColumn = ({
children,
className,
justifyContent,
alignItems,
flexWrap,
style,
...rest
}: Props) => (
<div
className={cx(styles.column, className)}
style={{
justifyContent,
alignItems,
flexWrap,
...style
}}
{...rest}
>
{children}
</div>
);
export const FlexItem = ({
children,
className,
flex,
container = false, // Add display: flex;
...rest
}: Props) => (
<div
className={className}
style={{
flex,
display: container ? 'flex' : 'block'
}}
{...rest}
>
{children}
</div>
);
|
/* eslint-disable */
/* DEPRECATED DO NOT USE */
import React from 'react';
import cx from 'classnames';
import styles from './index.css';
export const FlexRow = ({
children,
className,
justifyContent,
alignItems,
flexWrap,
style,
...rest
}) => (
<div
className={cx(styles.row, className)}
style={{
justifyContent,
alignItems,
flexWrap,
...style
}}
{...rest}
>
{children}
</div>
);
export const FlexColumn = ({
children,
className,
justifyContent,
alignItems,
flexWrap,
style,
...rest
}) => (
<div
className={cx(styles.column, className)}
style={{
justifyContent,
alignItems,
flexWrap,
...style
}}
{...rest}
>
{children}
</div>
);
export const FlexItem = ({
children,
className,
flex,
container = false, // Add display: flex;
...rest
}) => (
<div
className={className}
style={{
flex,
display: container ? 'flex' : 'block'
}}
{...rest}
>
{children}
</div>
);
|
Add update to usermodel upon login with login controller
|
(function(){
'use strict';
angular
.module('secondLead')
.controller('LoginCtrl', [
'Restangular',
'$state',
'store',
'UserModel',
function (Restangular, $state, store, UserModel) {
var login = this;
login.user = {};
login.onSubmit = function() {
UserModel.login(login.user)
.then(function (response) {
var user = response.data.user;
UserModel.setLoggedIn(true);
$state.go('user.lists', {userID: user.id});
login.reset();
}, function(error){
login.error = "Invalid username/password";
}
);
}
login.reset = function () {
login.user = {};
};
}])
})();
|
(function(){
'use strict';
angular
.module('secondLead')
.controller('LoginCtrl', [
'Restangular',
'$state',
'store',
'UserModel',
function (Restangular, $state, store, UserModel) {
var login = this;
login.user = {};
login.onSubmit = function() {
UserModel.login(login.user)
.then(function (response) {
var user = response.data.user;
$state.go('user.lists', {userID: user.id});
login.reset();
}, function(error){
login.error = "Invalid username/password";
}
);
}
login.reset = function () {
login.user = {};
};
}])
})();
|
Fix formatTime function:
- avoid AM/PM from being removed of the returning string.
|
import React from 'react'
import styles from './event-heading.module.styl'
export default class EventHeading extends React.Component {
constructor (props) {
super(props)
const date = new Date(props.event.date * 1000)
this.state = {
dateDate: formatDate(date),
dateTime: formatTime(date),
eventName: `${props.event.home} X ${props.event.away}`
}
}
render () {
const event = this.props.event
return (
<h4>
<span className={styles.red}>{event.code}</span>
{
` - ${this.state.dateDate}, ${this.state.dateTime}
- ${this.state.eventName}
- ${event.sport}
- ${event.country}
- ${event.competition}`
}
</h4>
)
}
}
function formatDate (date) {
const now = new Date()
return date.getDate() === now.getDate() ? 'Hoje'
: date.getDate() === (now.getDate() + 1) ? 'Amanhã'
: date.toLocaleDateString()
}
function formatTime (date) {
const time = date.toLocaleTimeString()
// Remove seconds from return string
return time.replace(/:00/, '')
}
|
import React from 'react'
import styles from './event-heading.module.styl'
export default class EventHeading extends React.Component {
constructor (props) {
super(props)
const date = new Date(props.event.date * 1000)
this.state = {
dateDate: formatDate(date),
dateTime: formatTime(date),
eventName: `${props.event.home} X ${props.event.away}`
}
}
render () {
const event = this.props.event
return (
<h4>
<span className={styles.red}>{event.code}</span>
{
` - ${this.state.dateDate}, ${this.state.dateTime}
- ${this.state.eventName}
- ${event.sport}
- ${event.country}
- ${event.competition}`
}
</h4>
)
}
}
function formatDate (date) {
const now = new Date()
return date.getDate() === now.getDate() ? 'Hoje'
: date.getDate() === (now.getDate() + 1) ? 'Amanhã'
: date.toLocaleDateString()
}
function formatTime (date) {
const time = date.toLocaleTimeString()
// Remove seconds from return string
return time.slice(0, time.lastIndexOf(':'))
}
|
Add missing parser argument to BeautifulSoup instance
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, value=None, key='id'):
if isinstance(markup, BeautifulSoup):
self._soup = markup
else:
self._soup = BeautifulSoup(markup, 'html.parser')
if value:
self._soup = self._soup.find(**{key: value})
self._cals = self._soup.findAll(attrs='vcalendar')
if self._cals:
self._cals = list(map(vCalendar, self._cals))
else:
self._cals = [vCalendar(self._soup)]
def __len__(self):
return len(self._cals)
def __iter__(self):
return iter(self._cals)
def __getitem__(self, key):
return self._cals[key]
def getCalendar(self):
return self._cals
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, value=None, key='id'):
if isinstance(markup, BeautifulSoup):
self._soup = markup
else:
self._soup = BeautifulSoup(markup)
if value:
self._soup = self._soup.find(**{key: value})
self._cals = self._soup.findAll(attrs='vcalendar')
if self._cals:
self._cals = list(map(vCalendar, self._cals))
else:
self._cals = [vCalendar(self._soup)]
def __len__(self):
return len(self._cals)
def __iter__(self):
return iter(self._cals)
def __getitem__(self, key):
return self._cals[key]
def getCalendar(self):
return self._cals
|
Change the way of creating database's connection pool
|
# -*- coding:utf-8 -*-
import os,time,asyncio,json
import logging
logging.basicConfig(level=logging.ERROR)
try:
from aiohttp import web
except ImportError:
logging.error("Can't import module aiohttp")
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from tools.config import Config
from tools.database import create_pool,DB
logging.basicConfig(level=logging.INFO)
class Application(web.Application):
def __init__(self):
self._loop=asyncio.get_event_loop()
super(Application,self).__init__(loop=self._loop,middlewares=Middleware.allmiddlewares())
def run(self,addr='127.0.0.1',port='8000'):
self._loop.run_until_complete(self.get_server(addr,port))
self._loop.run_forever()
@asyncio.coroutine
def get_server(self,addr,port):
Template.init(self)
Route.register_route(self)
yield from DB.createpool(self._loop)
#pool=yield from create_pool(self._loop)
srv=yield from self._loop.create_server(self.make_handler(),addr,port)
logging.info("server start at http://%s:%s"%(addr,port))
Log.info("server start at http://%s:%s"%(addr,port))
print("server start at http://%s:%s"%(addr,port))
return srv
|
# -*- coding:utf-8 -*-
import os,time,asyncio,json
import logging
logging.basicConfig(level=logging.ERROR)
try:
from aiohttp import web
except ImportError:
logging.error("Can't import module aiohttp")
from tools.log import Log
from tools.httptools import Middleware,Route
from tools.template import Template
from tools.config import Config
from tools.database import create_pool
logging.basicConfig(level=logging.INFO)
class Application(web.Application):
def __init__(self):
self._loop=asyncio.get_event_loop()
super(Application,self).__init__(loop=self._loop,middlewares=Middleware.allmiddlewares())
def run(self,addr='127.0.0.1',port='8000'):
self._loop.run_until_complete(self.get_server(addr,port))
self._loop.run_forever()
@asyncio.coroutine
def get_server(self,addr,port):
Template.init(self)
Route.register_route(self)
pool=yield from create_pool(self._loop)
srv=yield from self._loop.create_server(self.make_handler(),addr,port)
logging.info("server start at http://%s:%s"%(addr,port))
Log.info("server start at http://%s:%s"%(addr,port))
print("server start at http://%s:%s"%(addr,port))
return srv
|
Add ability to print out studies view from command line.
|
import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
|
import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in TerminalView(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.set_defaults(lower_bound=0, spins=False, references=True)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
|
Handle both strings and arrays, as the parent does
|
<?php
/**
* This file is part of Ibuildings QA-Tools.
*
* (c) Ibuildings
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ibuildings\QA\Tools\Common\Console\Helper;
use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class DialogHelper
*
* @package Ibuildings\QA\Tools\Common\Console\Helper
*/
class DialogHelper extends BaseDialogHelper
{
/**
* Asks a confirmation to the user.
*
* The question will be asked until the user answers by nothing, yes, or no.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param Boolean $default The default answer if the user enters nothing
*
* @return Boolean true if the user has confirmed, false otherwise
*/
public function askConfirmation(OutputInterface $output, $question, $default = true)
{
$hint = ($default) ? ' [Y/n] ' : ' [y/N] ';
if (is_string($question)) {
$question = $question . $hint;
} else {
array_push($question, array_pop($question) . $hint);
}
return parent::askConfirmation($output, $question, $default);
}
}
|
<?php
/**
* This file is part of Ibuildings QA-Tools.
*
* (c) Ibuildings
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ibuildings\QA\Tools\Common\Console\Helper;
use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class DialogHelper
*
* @package Ibuildings\QA\Tools\Common\Console\Helper
*/
class DialogHelper extends BaseDialogHelper
{
/**
* Asks a confirmation to the user.
*
* The question will be asked until the user answers by nothing, yes, or no.
*
* @param OutputInterface $output An Output instance
* @param string|array $question The question to ask
* @param Boolean $default The default answer if the user enters nothing
*
* @return Boolean true if the user has confirmed, false otherwise
*/
public function askConfirmation(OutputInterface $output, $question, $default = true)
{
$hint = ($default) ? '[Y/n] ' : '[y/N] ';
$question = $question . ' ' . $hint;
return parent::askConfirmation($output, $question, $default);
}
}
|
Fix SQL connection in blank route
|
package nuclibook.routes;
import com.j256.ormlite.support.ConnectionSource;
import nuclibook.server.SqlServerConnection;
import spark.Request;
import spark.Response;
import spark.Route;
import java.sql.Connection;
public class BlankRoute implements Route {
/**
* This route provides a simple "debugging" page for development use.
* It will display whatever message is passed in the constructor, and
* some diagnostic information.
*/
private String label = null;
public BlankRoute() {
}
public BlankRoute(String label) {
this.label = label;
}
@Override
public Object handle(Request request, Response response) throws Exception {
// carry out connection test
ConnectionSource connection = SqlServerConnection.acquireConnection();
// return HTML
return "<html>" +
"<head>" +
"<link type=\"text/css\" href=\"/css/blank-route-style.css\" rel=\"stylesheet\" />" +
"</head>" +
"<body>" +
"<h1>Blank route" + (label == null ? "" : ": " + label) + "</h1>" +
"<p>Connection test: " + (connection == null ? "nope =/" : "awesome! :D") + "</p>" +
"</body>" +
"</html>";
}
}
|
package nuclibook.routes;
import nuclibook.server.SqlServerConnection;
import spark.Request;
import spark.Response;
import spark.Route;
import java.sql.Connection;
public class BlankRoute implements Route {
/**
* This route provides a simple "debugging" page for development use.
* It will display whatever message is passed in the constructor, and
* some diagnostic information.
*/
private String label = null;
public BlankRoute() {
}
public BlankRoute(String label) {
this.label = label;
}
@Override
public Object handle(Request request, Response response) throws Exception {
// carry out connection test
Connection connection = SqlServerConnection.acquireConnection();
// return HTML
return "<html>" +
"<head>" +
"<link type=\"text/css\" href=\"/css/blank-route-style.css\" rel=\"stylesheet\" />" +
"</head>" +
"<body>" +
"<h1>Blank route" + (label == null ? "" : ": " + label) + "</h1>" +
"<p>Connection test: " + (connection == null ? "nope =/" : "awesome! :D") + "</p>" +
"</body>" +
"</html>";
}
}
|
Mark assets as `noProcess` to keep it from screwing up the PNG
|
var exec = require("child_process").exec;
var path = require("path");
exports.description = "A standard starting-point for news app development at the Seattle Times."
exports.template = function(grunt, init, done) {
//prelims
var here = path.basename(process.cwd());
//process
init.process(init.defaults, [
init.prompt("author_name"),
init.prompt("app_name", here),
init.prompt("app_description"),
init.prompt("github_repo", "seattletimes/" + here)
], function(err, props) {
//add environment variables, dynamic properties
var root = init.filesToCopy(props);
init.copyAndProcess(root, props, { noProcess: "src/assets/**" });
grunt.file.mkdir("data");
//install node modules
console.log("Installing Node modules...");
exec("npm install --cache-min 999999", done);
});
};
|
var exec = require("child_process").exec;
var path = require("path");
exports.description = "A standard starting-point for news app development at the Seattle Times."
exports.template = function(grunt, init, done) {
//prelims
var here = path.basename(process.cwd());
//process
init.process(init.defaults, [
init.prompt("author_name"),
init.prompt("app_name", here),
init.prompt("app_description"),
init.prompt("github_repo", "seattletimes/" + here)
], function(err, props) {
//add environment variables, dynamic properties
var root = init.filesToCopy(props);
init.copyAndProcess(root, props);
grunt.file.mkdir("data");
//install node modules
console.log("Installing Node modules...");
exec("npm install --cache-min 999999", done);
});
};
|
Update dependencies to be more loose (and match Channels)
|
from os.path import dirname, join
from setuptools import find_packages, setup
from channels_redis import __version__
# We use the README as the long_description
readme = open(join(dirname(__file__), "README.rst")).read()
crypto_requires = ["cryptography>=1.3.0"]
test_requires = crypto_requires + [
"pytest>=3.0",
"pytest-asyncio~=0.8",
"async_generator~=1.8",
"async-timeout~=2.0",
]
setup(
name="channels_redis",
version=__version__,
url="http://github.com/django/channels_redis/",
author="Django Software Foundation",
author_email="foundation@djangoproject.com",
description="Redis-backed ASGI channel layer implementation",
long_description=readme,
license="BSD",
zip_safe=False,
packages=find_packages(exclude=["tests"]),
include_package_data=True,
install_requires=[
"aioredis~=1.0.0",
"msgpack~=0.5.0",
"asgiref~=2.1",
"channels~=2.0",
],
extras_require={
"cryptography": crypto_requires,
"tests": test_requires,
},
)
|
from os.path import dirname, join
from setuptools import find_packages, setup
from channels_redis import __version__
# We use the README as the long_description
readme = open(join(dirname(__file__), "README.rst")).read()
crypto_requires = ["cryptography>=1.3.0"]
test_requires = crypto_requires + [
"pytest>=3.0",
"pytest-asyncio~=0.8",
"async_generator~=1.8",
"async-timeout~=2.0",
]
setup(
name="channels_redis",
version=__version__,
url="http://github.com/django/channels_redis/",
author="Django Software Foundation",
author_email="foundation@djangoproject.com",
description="Redis-backed ASGI channel layer implementation",
long_description=readme,
license="BSD",
zip_safe=False,
packages=find_packages(exclude=["tests"]),
include_package_data=True,
install_requires=[
"aioredis~=1.0.0",
"msgpack~=0.5.0",
"asgiref~=2.0.1",
"channels~=2.0.0",
],
extras_require={
"cryptography": crypto_requires,
"tests": test_requires,
},
)
|
Fix so it doesn't create new connection if one has already been created.
|
package classpackage;
import java.sql.*;
/**
* Created by axelkvistad on 3/18/16.
*/
public class DBConnector {
private String username = "thomjos"; //DataLeser2.lesTekst("Brukernavn: "); // DataLeser2, se nedenfor
private String password = "cinPn2AK";
private String databaseName = "jdbc:mysql://mysql.stud.iie.ntnu.no:3306/" + username + "?user=" + username + "&password=" + password;
private String databaseDriver = "com.mysql.jdbc.Driver";
protected static Connection con = null;
public DBConnector() {
if(con == null) {
try {
Class.forName(databaseDriver);
con = DriverManager.getConnection(databaseName);
} catch (ClassNotFoundException exc) {
System.out.println(exc);
} catch (SQLException exc) {
System.out.println(exc);
}
}
}
public void closeConnection() {
try {
con.close();
} catch (SQLException exc) {
System.out.println(exc);
}
}
}
|
package classpackage;
import java.sql.*;
/**
* Created by axelkvistad on 3/18/16.
*/
public class DBConnector {
private String username = "thomjos"; //DataLeser2.lesTekst("Brukernavn: "); // DataLeser2, se nedenfor
private String password = "cinPn2AK";
private String databaseName = "jdbc:mysql://mysql.stud.iie.ntnu.no:3306/" + username + "?user=" + username + "&password=" + password;
private String databaseDriver = "com.mysql.jdbc.Driver";
protected static Connection con = null;
public DBConnector() {
try {
Class.forName(databaseDriver);
con = DriverManager.getConnection(databaseName);
} catch (ClassNotFoundException exc) {
System.out.println(exc);
} catch (SQLException exc) {
System.out.println(exc);
}
}
public void closeConnection() {
try {
con.close();
} catch (SQLException exc) {
System.out.println(exc);
}
}
}
|
Tweak a migration to run on non-transactional DBs
A single migration failed to run on databases with no support for
transactions because those require explicit ordering of commands that's
generally implicit on modern relational DBs.
Switch the order of those queries to prevent that crash.
Fixes #27
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-02 23:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('afip', '0020_backfill_receiptvalidation__processed_date'),
]
operations = [
migrations.RemoveField(
model_name='receipt',
name='batch',
),
migrations.RemoveField(
model_name='receiptvalidation',
name='validation',
),
migrations.AlterField(
model_name='receiptvalidation',
name='processed_date',
field=models.DateTimeField(verbose_name='processed date'),
),
migrations.DeleteModel(
name='Validation',
),
migrations.DeleteModel(
name='ReceiptBatch',
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-02 23:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('afip', '0020_backfill_receiptvalidation__processed_date'),
]
operations = [
migrations.RemoveField(
model_name='receipt',
name='batch',
),
migrations.RemoveField(
model_name='receiptvalidation',
name='validation',
),
migrations.AlterField(
model_name='receiptvalidation',
name='processed_date',
field=models.DateTimeField(verbose_name='processed date'),
),
migrations.DeleteModel(
name='ReceiptBatch',
),
migrations.DeleteModel(
name='Validation',
),
]
|
Change language key to something more appropriate
|
/*
* © 2013 by Intellectual Reserve, Inc. All rights reserved.
*/
package org.sonar.plugins.xquery.api;
public interface XQueryConstants {
static String XQUERY_LANGUAGE_KEY = "xquery";
static String FILE_EXTENSIONS_KEY = "sonar.marklogic.fileExtensions";
static String SOURCE_DIRECTORY_KEY = "sonar.marklogic.sourceDirectory";
static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath";
static String XQUERY_LANGUAGE_NAME = "XQuery";
static String[] DEFAULT_FILE_EXTENSIONS = { "xqy", "xquery", "xq" , "xqi", "xql", "xqm", "xqws"};
static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws";
static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery";
static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports";
}
|
/*
* © 2013 by Intellectual Reserve, Inc. All rights reserved.
*/
package org.sonar.plugins.xquery.api;
public interface XQueryConstants {
static String XQUERY_LANGUAGE_KEY = "xqy";
static String FILE_EXTENSIONS_KEY = "sonar.marklogic.fileExtensions";
static String SOURCE_DIRECTORY_KEY = "sonar.marklogic.sourceDirectory";
static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath";
static String XQUERY_LANGUAGE_NAME = "XQuery";
static String[] DEFAULT_FILE_EXTENSIONS = { "xqy", "xquery", "xq" };
static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq";
static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery";
static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports";
}
|
Write idea for rest app
|
<?php
/**
* @author Patsura Dmitry @ovr <talk@dmtry.me>
*/
/**
* Class IndexController
* @Path("/api/")
*/
class IndexController extends \Owl\Rest\Controller
{
/**
* @Get
* @Url("/user/{id:int}/")
*/
public function indexAction($id)
{
return array(
'user' => array(
'id' => $id
)
);
}
/**
* @Get
* @Url("/users")
*/
public function listAction()
{
//Get users from db
return true;
}
/**x
* @Post
* @Url("/user")
*/
public function createAction()
{
//Create new user in db
return true;
}
/**
* @Delete
* @Url("/user/{id:int}/")
*/
public function deleteAction()
{
//Remove user from db
return true;
}
}
|
<?php
/**
* @author Patsura Dmitry @ovr <talk@dmtry.me>
*/
/**
* Class IndexController
* @Path("/api/")
*/
class IndexController extends \Owl\Rest\Controller
{
/**
* @Get
* @Url("/user/{id:int}/")
*/
public function indexAction($id)
{
return array(
'user' => array(
'id' => $id
)
);
}
/**x
* @Post
* @Url("/user")
*/
public function createAction()
{
//Create new user in db
return true;
}
/**
* @Delete
* @Url("/user/{id:int}/")
*/
public function deleteAction()
{
//Remove user from db
return true;
}
}
|
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
|
from django_auth_ldap.backend import LDAPBackend
class LDAPBackendWrapper(LDAPBackend):
# def authenticate(self, identification, password, **kwargs):
# return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs)
def authenticate(self, **kwargs):
if "username" in kwargs:
username = kwargs["username"]
del kwargs["username"]
elif "identification" in kwargs:
username = kwargs["identification"]
del kwargs["identification"]
password = kwargs["password"]
del kwargs["password"]
return super(LDAPBackendWrapper, self).authenticate(username=username, password=password, **kwargs)
# return None
|
from django_auth_ldap.backend import LDAPBackend
class LDAPBackendWrapper(LDAPBackend):
# def authenticate(self, identification, password, **kwargs):
# return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs)
def authenticate(self, **kwargs):
if "username" in kwargs:
username = kwargs["username"]
del kwargs["username"]
elif "identification" in kwargs:
username = kwargs["identification"]
del kwargs["identification"]
password = kwargs["password"]
del kwargs["password"]
return super(LDAPBackendWrapper, self).authenticate(username, password, **kwargs)
# return None
|
Modify Code add log !
|
package com.homeinns.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoAction extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String msg = "您上传了:<br/>";
String[] fileUrls = request.getParameterValues("fileUrl");
String[] fileNames = request.getParameterValues("fileName");
for (int i = 0; i < fileUrls.length; i++) {
msg += "文件路径:" + fileUrls[i] + " 文件名称:" + fileNames[i] + "<br/>";
System.out.println(fileUrls[i] + " " + fileNames[i]);
}
String name = request.getParameter("name");
msg += "用户名:" + name + "<br/>";
String pwd = request.getParameter("pwd");
msg += "密码:" + pwd + "<br/>";
request.setAttribute("msg", msg);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}
}
|
package com.homeinns.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoAction extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String msg = "您上传了:<br/>";
String[] fileUrls = request.getParameterValues("fileUrl");
String[] fileNames = request.getParameterValues("fileName");
for (int i = 0; i < fileUrls.length; i++) {
msg += "文件路径:" + fileUrls[i] + " 文件名称:" + fileNames[i] + "<br/>";
// System.out.println(fileUrls[i] + " " + fileNames[i]);
}
String name = request.getParameter("name");
msg += "用户名:" + name + "<br/>";
String pwd = request.getParameter("pwd");
msg += "密码:" + pwd + "<br/>";
request.setAttribute("msg", msg);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}
}
|
Add ovp_core_0011 migration as dependency for ovp_organizations_0023
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
('ovp_core', '0011_simpleaddress'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='address',
field=models.OneToOneField(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='ovp_core.SimpleAddress', verbose_name='address'),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='address',
field=models.OneToOneField(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='ovp_core.SimpleAddress', verbose_name='address'),
),
]
|
Add debug string representation of integer concrete type
|
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
@Override
public String toString() {
return "$Integer";
}
}
|
package org.hummingbirdlang.types.concrete;
import org.hummingbirdlang.nodes.builtins.BuiltinNodes;
import org.hummingbirdlang.types.MethodProperty;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.UnknownType;
import org.hummingbirdlang.types.realize.Index.Module;
public final class IntegerType extends BootstrappableConcreteType {
public static String BUILTIN_NAME = "Integer";
private MethodType toString;
@Override
public String getBootstrapName() {
return IntegerType.BUILTIN_NAME;
}
@Override
public void bootstrapBuiltins(BuiltinNodes builtins) {
this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString"));
}
@Override
public void bootstrapTypes(Module indexModule) {
this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME));
}
@Override
public Property getProperty(String name) throws PropertyNotFoundException {
switch (name) {
case "toString":
return MethodProperty.fromType(this.toString);
default:
throw new PropertyNotFoundException(this, name);
}
}
}
|
Add empty lines for readability
|
'use strict';
/**
* Fréchet distributed pseudorandom numbers.
*
* @module @stdlib/math/base/random/frechet
*
* @example
* var frechet = require( '@stdlib/math/base/random/frechet' );
*
* var v = frechet( 10.0, 10.0, 7.0 );
* // returns <number>
*
* @example
* var factory = require( '@stdlib/math/base/random/frechet' ).factory;
*
* var frechet = factory( 5.0, 5.0, 3.0, {
* 'seed': 643361677
* });
*
* var v = frechet();
* // returns ~8.733
*
* @example
* var factory = require( '@stdlib/math/base/random/frechet' ).factory;
*
* var frechet = factory({
* 'seed': 643361677
* });
*
* var v = frechet( 5.0, 5.0, 3.0 );
* // returns ~8.733
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var frechet = require( './frechet.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( frechet, 'factory', factory );
// EXPORTS //
module.exports = frechet;
|
'use strict';
/**
* Fréchet distributed pseudorandom numbers.
*
* @module @stdlib/math/base/random/frechet
*
* @example
* var frechet = require( '@stdlib/math/base/random/frechet' );
*
* var v = frechet( 10.0, 10.0, 7.0 );
* // returns <number>
*
* @example
* var factory = require( '@stdlib/math/base/random/frechet' ).factory;
* var frechet = factory( 5.0, 5.0, 3.0, {
* 'seed': 643361677
* });
*
* var v = frechet();
* // returns ~8.733
*
* @example
* var factory = require( '@stdlib/math/base/random/frechet' ).factory;
* var frechet = factory({
* 'seed': 643361677
* });
*
* var v = frechet( 5.0, 5.0, 3.0 );
* // returns ~8.733
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var frechet = require( './frechet.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( frechet, 'factory', factory );
// EXPORTS //
module.exports = frechet;
|
Fix generation error for array generators.
|
<?php
namespace JSON_Loader {
/**
* Class Array_Generator
*/
class Array_Generator {
var $generator_class;
var $values;
var $parent;
var $args;
/**
* @param string $generator_class
* @param array $values
* @param Generator $parent
* @param array $args
*/
function __construct( $generator_class, $values, $parent, $args ) {
$this->generator_class = $generator_class;
$this->values = $values;
$this->parent = $parent;
$this->args = $args;
}
function execute() {
$generator_class = $this->generator_class;
foreach( $this->values as $index => $value ) {
if ( 0 < $index ) {
/**
* @todo Yes, this is really screwy. We'd need to rearchitect to fix it eventually.
*/
$s = Util::get_state( $value );
Util::get_state( $s->owner )->set_values( $s->values() );
}
Generator::generate( $value, new $generator_class( $value, $this->parent, $this->args ) );
}
}
}
}
|
<?php
namespace JSON_Loader {
/**
* Class Array_Generator
*/
class Array_Generator {
var $generator_class;
var $values;
var $parent;
var $args;
/**
* @param string $generator_class
* @param array $values
* @param Generator $parent
* @param array $args
*/
function __construct( $generator_class, $values, $parent, $args ) {
$this->generator_class = $generator_class;
$this->values = $values;
$this->parent = $parent;
$this->args = $args;
}
function execute() {
$generator_class = $this->generator_class;
foreach( $this->values as $index => $value ) {
/**
* @var Generator $generator
*/
$generator = new $generator_class( $value, $this->parent, $this->args );
$generator->generate( $value, $generator );
}
}
}
}
|
Make page content show on posts page with page ID
|
<?php
if ( is_category() || is_home() ) :
$queried_object = get_queried_object();
if ( get_field( 'header_image', $queried_object ) ) :
get_template_part('templates/archive', 'hero');
endif;
else : ?>
<header >
<div class="container">
<div class="row">
<div class="col-md-12">
<?php get_template_part('templates/page', 'header'); ?>
</div>
</div>
</div>
</header>
<?php endif; ?>
<section class="page-section">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php echo(get_post_field('post_content',10)); ?>
</div>
</div>
</div>
</section>
<section class="page-section">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php if (!have_posts()) : ?>
<div class="alert alert-warning">
<?php _e('Sorry, no results were found.', 'sage'); ?>
</div>
<?php get_search_form(); ?>
<?php endif; ?>
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
</div><!-- /.col-sm-8 -->
|
<?php
if ( is_category() || is_home() ) :
$queried_object = get_queried_object();
if ( get_field( 'header_image', $queried_object ) ) :
get_template_part('templates/archive', 'hero');
endif;
else : ?>
<header >
<div class="container">
<div class="row">
<div class="col-md-12">
<?php get_template_part('templates/page', 'header'); ?>
</div>
</div>
</div>
</header>
<?php endif; ?>
<section class="page-section">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php if (!have_posts()) : ?>
<div class="alert alert-warning">
<?php _e('Sorry, no results were found.', 'sage'); ?>
</div>
<?php get_search_form(); ?>
<?php endif; ?>
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
</div><!-- /.col-sm-8 -->
|
Use setTimeout(fn, 0) instead of setImmediate
|
import get from 'lodash/get'
import {useCallback, useEffect, useRef, useState} from 'react'
const alwaysValid = () => true
export default function useControlledInput(
propValue,
propOnChange,
testValid = alwaysValid
) {
const [inputValue, setInputValue] = useState(propValue)
const ref = useRef()
// Update the value from the external source on change unless the input is
// currently the active element.
useEffect(() => {
if (ref.current !== document.activeElement) setInputValue(propValue)
}, [propValue, ref, setInputValue])
const onChange = useCallback(
input => {
// Is this the value itself or an event?
const isEvent =
input instanceof Event || get(input, 'nativeEvent') instanceof Event
const value = isEvent ? input.target.value : input
const isValid = testValid(value)
// Ensure the displayed value syncs fast, even if it's not valid
setInputValue(value)
// Don't pass invalid changes through to the onChange function
if (!isValid) return
// Allow the sync to occur before propogating the change
setTimeout(() => propOnChange(value), 0)
},
[propOnChange, setInputValue, testValid]
)
return [inputValue, onChange, ref, testValid(inputValue)]
}
|
import get from 'lodash/get'
import {useCallback, useEffect, useRef, useState} from 'react'
const noop = () => true
export default function useControlledInput(
propValue,
propOnChange,
testValid = noop
) {
const [inputValue, setInputValue] = useState(propValue)
const ref = useRef()
// Update the value from the external source on change unless the input is
// currently the active element.
useEffect(() => {
if (ref.current !== document.activeElement) setInputValue(propValue)
}, [propValue, ref, setInputValue])
const onChange = useCallback(
input => {
// Is this the value itself or an event?
const isEvent =
input instanceof Event || get(input, 'nativeEvent') instanceof Event
const value = isEvent ? input.target.value : input
const isValid = testValid(value)
// Ensure the displayed value syncs fast, even if it's not valid
setInputValue(value)
// Don't pass invalid changes through to the onChange function
if (!isValid) return
// Allow the sync to occur before propogating the change
setImmediate(() => propOnChange(value))
},
[propOnChange, setInputValue, testValid]
)
return [inputValue, onChange, ref, testValid(inputValue)]
}
|
Set this.data as an empty object instead of null
|
import {Data} from 'Framework/Data';
const dataData = new Data();
export class Locale
{
constructor()
{
this.isInitialized = false;
this.data = {};
}
initialize()
{
$.ajax(
'/' + dataData.get('request.locale') + '/locale.json',
{
type: 'GET',
dataType: 'json',
async: false,
success: (data) => {
this.data = data;
this.isInitialized = true;
},
error: (jqXHR, textStatus, errorThrown) => {
throw Error('Regenerate your locale-files.');
}
}
);
}
exists(key)
{
return (this.get(key) !== null);
}
get(key)
{
if (!this.isInitialized) {
this.initialize();
}
if (this.data[key] !== null) {
return this.data[key];
}
}
act(key)
{
return this.get(key);
}
err(key)
{
return this.get(key);
}
lbl(key)
{
return this.get(key);
}
msg(key)
{
return this.get(key);
}
}
|
import {Data} from 'Framework/Data';
const dataData = new Data();
export class Locale
{
constructor()
{
this.isInitialized = false;
this.data = null;
}
initialize()
{
$.ajax(
'/' + dataData.get('request.locale') + '/locale.json',
{
type: 'GET',
dataType: 'json',
async: false,
success: (data) => {
this.data = data;
this.isInitialized = true;
},
error: (jqXHR, textStatus, errorThrown) => {
throw Error('Regenerate your locale-files.');
}
}
);
}
exists(key)
{
return (this.get(key) !== null);
}
get(key)
{
if (!this.isInitialized) {
this.initialize();
}
if (this.data[key] !== null) {
return this.data[key];
}
}
act(key)
{
return this.get(key);
}
err(key)
{
return this.get(key);
}
lbl(key)
{
return this.get(key);
}
msg(key)
{
return this.get(key);
}
}
|
Use protoc for file output
|
#!/usr/bin/env python
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
response = plugin_pb2.CodeGeneratorResponse()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
# Write the C file.
t = Template(resource_string(__name__, 'template/module.jinja.c'))
cFile = response.file.add()
cFile.name = name + '.c'
cFile.content = t.render(context)
# Write setup.py.
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
setupFile = response.file.add()
setupFile.name = 'setup.py'
setupFile.content = t.render({'files': files})
sys.stdout.write(response.SerializeToString())
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import plugin_pb2
from jinja2 import Template
from pkg_resources import resource_string
import os.path
import sys
import tempfile
def main():
log = sys.stderr
request = plugin_pb2.CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
path = tempfile.mkdtemp()
generateFiles = set(request.file_to_generate)
files = []
for file in request.proto_file:
if file.name not in generateFiles:
continue
name = file.name.split('.')[0]
files.append(name)
context = {
'moduleName': name,
'messages': file.message_type
}
cFilePath = os.path.join(path, name + '.c')
with open(cFilePath, 'w') as f:
t = Template(resource_string(__name__, 'template/module.jinja.c'))
f.write(t.render(context))
setupPyPath = os.path.join(path, 'setup.py')
with open(setupPyPath, 'w') as f:
t = Template(resource_string(__name__, 'template/setup.jinja.py'))
f.write(t.render({'files': files}))
print >> log, path
if __name__ == '__main__':
main()
|
Change suggested_company_name factory var to pystr
|
# -*- coding: utf-8 -*-
import factory
import random
from django.conf import settings
from TWLight.resources.models import Partner, Stream, Video, Suggestion
class PartnerFactory(factory.django.DjangoModelFactory):
class Meta:
model = Partner
strategy = factory.CREATE_STRATEGY
company_name = factory.Faker(
"company", locale=random.choice(settings.FAKER_LOCALES)
)
terms_of_use = factory.Faker("uri", locale=random.choice(settings.FAKER_LOCALES))
status = Partner.AVAILABLE # not the default, but usually wanted in tests
class StreamFactory(factory.django.DjangoModelFactory):
class Meta:
model = Stream
strategy = factory.CREATE_STRATEGY
partner = factory.SubFactory(PartnerFactory)
name = factory.Faker("bs", locale=random.choice(settings.FAKER_LOCALES))
class SuggestionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Suggestion
strategy = factory.CREATE_STRATEGY
suggested_company_name = factory.Faker("pystr", max_chars=40)
company_url = factory.Faker("url", locale=random.choice(settings.FAKER_LOCALES))
class VideoFactory(factory.django.DjangoModelFactory):
class Meta:
model = Video
strategy = factory.CREATE_STRATEGY
partner = factory.SubFactory(PartnerFactory)
|
# -*- coding: utf-8 -*-
import factory
import random
from django.conf import settings
from TWLight.resources.models import Partner, Stream, Video, Suggestion
class PartnerFactory(factory.django.DjangoModelFactory):
class Meta:
model = Partner
strategy = factory.CREATE_STRATEGY
company_name = factory.Faker(
"company", locale=random.choice(settings.FAKER_LOCALES)
)
terms_of_use = factory.Faker("uri", locale=random.choice(settings.FAKER_LOCALES))
status = Partner.AVAILABLE # not the default, but usually wanted in tests
class StreamFactory(factory.django.DjangoModelFactory):
class Meta:
model = Stream
strategy = factory.CREATE_STRATEGY
partner = factory.SubFactory(PartnerFactory)
name = factory.Faker("bs", locale=random.choice(settings.FAKER_LOCALES))
class SuggestionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Suggestion
strategy = factory.CREATE_STRATEGY
suggested_company_name = factory.Faker(
"company", locale=random.choice(settings.FAKER_LOCALES)
)
company_url = factory.Faker("url", locale=random.choice(settings.FAKER_LOCALES))
class VideoFactory(factory.django.DjangoModelFactory):
class Meta:
model = Video
strategy = factory.CREATE_STRATEGY
partner = factory.SubFactory(PartnerFactory)
|
Use !== instead of != (so not type conversion is performed).
|
'use strict';
/* Controllers */
var demoControllers = angular.module('demoControllers', []);
demoControllers.controller('NodeCtrl', ['$scope', '$routeParams', 'DemoSession',
function ($scope, $routeParams, DemoSession) {
var id = $routeParams.nodeId;
if (id && id !== 'root') {
DemoSession.getById(id).then(function (node) {
$scope.node = node;
});
} else {
DemoSession.getRoot().then(function (node) {
$scope.node = node;
});
}
}
]);
demoControllers.controller('PathCtrl', ['$scope', '$routeParams', 'DemoSession',
function ($scope, $routeParams, DemoSession) {
var path = $routeParams.path;
DemoSession.getByPath(path).then(function (node) {
$scope.node = node;
});
}
]);
demoControllers.controller('SessionCtrl', ['$scope', 'DemoSession',
function ($scope, DemoSession) {
DemoSession.getSessions().then(function (sessions) {
$scope.sessions = sessions;
});
}
]);
|
'use strict';
/* Controllers */
var demoControllers = angular.module('demoControllers', []);
demoControllers.controller('NodeCtrl', ['$scope', '$routeParams', 'DemoSession',
function ($scope, $routeParams, DemoSession) {
var id = $routeParams.nodeId;
if (id && id != 'root') {
DemoSession.getById(id).then(function (node) {
$scope.node = node;
});
} else {
DemoSession.getRoot().then(function (node) {
$scope.node = node;
});
}
}
]);
demoControllers.controller('PathCtrl', ['$scope', '$routeParams', 'DemoSession',
function ($scope, $routeParams, DemoSession) {
var path = $routeParams.path;
DemoSession.getByPath(path).then(function (node) {
$scope.node = node;
});
}
]);
demoControllers.controller('SessionCtrl', ['$scope', 'DemoSession',
function ($scope, DemoSession) {
DemoSession.getSessions().then(function (sessions) {
$scope.sessions = sessions;
});
}
]);
|
Update to use 'app.env' for environment
|
<?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Bootstrap;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;
/**
* @internal
*/
final class LoadConfiguration implements BoostrapperContract
{
/**
* {@inheritdoc}
*/
public function bootstrap(Application $app): void
{
$app->make(BaseLoadConfiguration::class)
->bootstrap($app);
$app->detectEnvironment(
function () use ($app) {
return $app['config']->get('app.env', 'production');
}
);
/*
* When artisan starts, sets the application name and the application version.
*/
Artisan::starting(
function ($artisan) use ($app) {
$artisan->setName($app['config']->get('app.name', 'Laravel Zero'));
$artisan->setVersion($app->version());
}
);
}
}
|
<?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Bootstrap;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;
/**
* @internal
*/
final class LoadConfiguration implements BoostrapperContract
{
/**
* {@inheritdoc}
*/
public function bootstrap(Application $app): void
{
$app->make(BaseLoadConfiguration::class)
->bootstrap($app);
$app->detectEnvironment(
function () use ($app) {
return $app['config']->get('app.production', true) ? 'production' : 'development';
}
);
/*
* When artisan starts, sets the application name and the application version.
*/
Artisan::starting(
function ($artisan) use ($app) {
$artisan->setName($app['config']->get('app.name', 'Laravel Zero'));
$artisan->setVersion($app->version());
}
);
}
}
|
Add allowed headers to preflight response.
|
from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[
('Access-Control-Allow-Origin','*'),
('Access-Control-Allow-Methods', 'POST'),
('Access-Control-Allow-Headers', 'Content-Type')])
yield b''
else:
start_response('405 Method Not Allowed',[('Content-Type','text/plain')])
yield b'405 Method Not Allowed'
else:
j=JSONRPCResponseManager.handle(environ['wsgi.input'].read().decode(), d)
if j:
start_response('200 OK',[('Content-Type','application/json'), ('Access-Control-Allow-Origin','*')])
yield j.json.encode()
else:
start_response('204 No Content',[('Access-Control-Allow-Origin','*')])
yield b''
|
from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[('Access-Control-Allow-Origin','*'), ('Access-Control-Allow-Methods', 'POST')])
yield b''
else:
start_response('405 Method Not Allowed',[('Content-Type','text/plain')])
yield b'405 Method Not Allowed'
else:
j=JSONRPCResponseManager.handle(environ['wsgi.input'].read().decode(), d)
if j:
start_response('200 OK',[('Content-Type','application/json'), ('Access-Control-Allow-Origin','*')])
yield j.json.encode()
else:
start_response('204 No Content',[('Access-Control-Allow-Origin','*')])
yield b''
|
Add additional sample gpx files and a means to select the file and the track via request parameter.
|
requirejs.config({
paths: {
jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min",
async: "lib/async",
goog: "lib/goog",
propertyParser: "lib/propertyParser"
}
});
define("gmaps", ["async!http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"], function() {
return window.google.maps;
});
define("gvis", ["goog!visualization,1,packages:[corechart,controls]"], function() {
return window.google.visualization;
});
require(["jquery", "gpx", "map", "elevation_profile"], function($, gpx, map, elevationProfile) {
function getURLParameter(name) {
return decodeURIComponent(
(new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20')) || null;
}
var fileName = getURLParameter("gpx") || "blue_hills";
var trackNo = parseInt(getURLParameter("track") || "1");
gpx.load("gpx/" + fileName + ".gpx", function(gpx) {
var track = gpx.tracks[trackNo - 1];
if (track) {
var m = map.create("#map");
m.drawTrack(track);
elevationProfile.build(track, "#elevationProfile");
}
});
});
|
requirejs.config({
paths: {
jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min",
async: "lib/async",
goog: "lib/goog",
propertyParser: "lib/propertyParser"
}
});
define("gmaps", ["async!http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"], function() {
return window.google.maps;
});
define("gvis", ["goog!visualization,1,packages:[corechart,controls]"], function() {
return window.google.visualization;
});
require(["jquery", "gpx", "map", "elevation_profile"], function($, gpx, map, elevationProfile) {
gpx.load(
"gpx/blue_hills.gpx",
function(gpx) {
var m = map.create("#map");
m.drawTrack(gpx.tracks[0]);
elevationProfile.build(gpx.tracks[0], "#elevationProfile");
});
});
|
Return unlabeled data for the autoencoder as a straight array.
|
#!/usr/bin/env python
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Autoencoder
def get_datasets(self):
return [x for x, _ in cPickle.load(gzip.open(DATASET))]
path = os.path.join(tempfile.gettempdir(), 'mnist-autoencoder.pkl.gz')
Main().train().save(path)
print 'saved network to', path
|
#!/usr/bin/env python
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Autoencoder
def get_datasets(self):
return [(x, ) for x, _ in cPickle.load(gzip.open(DATASET))]
path = os.path.join(tempfile.gettempdir(), 'mnist-autoencoder.pkl.gz')
Main().train().save(path)
print 'saved network to', path
|
Add bounds to the package name regex
|
<?php
namespace Packagist\WebBundle\Twig;
use Symfony\Bridge\Doctrine\RegistryInterface;
class PackagistExtension extends \Twig_Extension
{
/**
* @var \Symfony\Bridge\Doctrine\RegistryInterface
*/
private $doctrine;
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
public function getTests()
{
return array(
'existing_package' => new \Twig_Test_Method($this, 'packageExistsTest')
);
}
public function getName()
{
return 'packagist';
}
public function packageExistsTest($package)
{
if (!preg_match('/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/', $package)) {
return false;
}
return $this->doctrine->getRepository('PackagistWebBundle:Package')
->packageExists($package);
}
}
|
<?php
namespace Packagist\WebBundle\Twig;
use Symfony\Bridge\Doctrine\RegistryInterface;
class PackagistExtension extends \Twig_Extension
{
/**
* @var \Symfony\Bridge\Doctrine\RegistryInterface
*/
private $doctrine;
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
public function getTests()
{
return array(
'existing_package' => new \Twig_Test_Method($this, 'packageExistsTest')
);
}
public function getName()
{
return 'packagist';
}
public function packageExistsTest($package)
{
if (!preg_match('/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/', $package)) {
return false;
}
return $this->doctrine->getRepository('PackagistWebBundle:Package')
->packageExists($package);
}
}
|
Print better logs for Dylos
|
import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if not ser.isOpen():
ser.open()
def read():
line = ser.readline()
LOGGER.debug("Read from serial port: %s", line)
small, large = [int(x.strip()) for x in line.split(b',')]
LOGGER.debug("Small: %s, Large: %s", small, large)
return {"small": small, "large": large}
return read
|
import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if not ser.isOpen():
ser.open()
def read():
line = ser.readline()
small, large = [int(x) for x in line.split(b',')]
LOGGER.debug("Read from serial port: %s %s", small, large)
return {"small": small, "large": large}
return read
|
refactor: Add proper default handling for uninitialized err.messages
|
"use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.statusCode = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.statusCode);
res.send(err.message || HTTPStatus.getStatusText(err.statusCode));
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
|
"use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.status = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.status);
res.send(err.message || '** no unicorns here **');
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
|
Change mocha's reporter type to spec
|
module.exports = function(grunt) {
grunt.registerTask("default", ["test-server", "test-client"]);
grunt.registerTask("test-client", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
});
grunt.registerTask("test-server", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
});
};
|
module.exports = function(grunt) {
grunt.registerTask("default", ["test-server", "test-client"]);
grunt.registerTask("test-client", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js"]}, function(error) {
done(!error);
});
});
grunt.registerTask("test-server", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js"]}, function(error) {
done(!error);
});
});
};
|
Load configuration from current directory
|
var moment = require('moment');
var debug = require('debug')('cli:rank');
var config = require('./config.json');
var talks = require('libtlks').talk;
var rank = require('librank').rank;
/**
* Count the number of hours between two timestamps
* @param start int start timestamp
* @param end int end timestamp
*/
function countHours(start, end) {
var duration = moment.duration(end.diff(start));
var hours = duration.asHours();
return hours;
}
/**
* Calculates score of a talk
* @param talk object talk object
*/
function calculateRank(talk) {
var now = moment();
var points = talk.voteCount;
var hours = countHours(talk.created, now);
var gravity = 1.8;
var ranking = rank.rank(points, hours, gravity);
return ranking;
}
/**
* Updates talk new score to the database
* @param talk object talk object
*/
function updateRank(talk) {
var score = calculateRank(talk);
talks.rank(config.dburl, talk.id, score, function(err) {
if (err) {
throw new Error(err);
}
debug('Ranked talk %s with score: %s', talk.title, score);
});
}
exports.rank = function() {
talks.all(config.dburl, function(err, docs) {
if (err) {
throw new Error(err);
}
docs.forEach(updateRank);
});
};
|
var moment = require('moment');
var debug = require('debug')('cli:rank');
var config = require('../../config.json');
var talks = require('libtlks').talk;
var rank = require('librank').rank;
/**
* Count the number of hours between two timestamps
* @param start int start timestamp
* @param end int end timestamp
*/
function countHours(start, end) {
var duration = moment.duration(end.diff(start));
var hours = duration.asHours();
return hours;
}
/**
* Calculates score of a talk
* @param talk object talk object
*/
function calculateRank(talk) {
var now = moment();
var points = talk.voteCount;
var hours = countHours(talk.created, now);
var gravity = 1.8;
var ranking = rank.rank(points, hours, gravity);
return ranking;
}
/**
* Updates talk new score to the database
* @param talk object talk object
*/
function updateRank(talk) {
var score = calculateRank(talk);
talks.rank(config.dburl, talk.id, score, function(err) {
if (err) {
throw new Error(err);
}
debug('Ranked talk %s with score: %s', talk.title, score);
});
}
exports.rank = function() {
talks.all(config.dburl, function(err, docs) {
if (err) {
throw new Error(err);
}
docs.forEach(updateRank);
});
};
|
Make sure the id is between 1 and 10000
|
package com.example.helloworld.resources;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.example.helloworld.core.World;
import com.example.helloworld.db.WorldDAO;
import com.google.common.base.Optional;
import com.yammer.dropwizard.hibernate.UnitOfWork;
@Path("/db")
@Produces(MediaType.APPLICATION_JSON)
public class WorldResource
{
private WorldDAO worldDAO = null;
public WorldResource(WorldDAO worldDAO)
{
this.worldDAO = worldDAO;
}
@GET
@UnitOfWork
public World[] dbTest(@QueryParam("queries") Optional<Integer> queries)
{
final int totalQueries = queries.or(1);
final World[] worlds = new World[queries.or(1)];
final Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < totalQueries; i++)
{
worlds[i] = this.worldDAO.findById((long)(random.nextInt(10000) + 1)).orNull();
}
return worlds;
}
}
|
package com.example.helloworld.resources;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.example.helloworld.core.World;
import com.example.helloworld.db.WorldDAO;
import com.google.common.base.Optional;
import com.yammer.dropwizard.hibernate.UnitOfWork;
@Path("/db")
@Produces(MediaType.APPLICATION_JSON)
public class WorldResource
{
private WorldDAO worldDAO = null;
public WorldResource(WorldDAO worldDAO)
{
this.worldDAO = worldDAO;
}
@GET
@UnitOfWork
public World[] dbTest(@QueryParam("queries") Optional<Integer> queries)
{
final int totalQueries = queries.or(1);
final World[] worlds = new World[queries.or(1)];
final Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < totalQueries; i++)
{
worlds[i] = this.worldDAO.findById((long)random.nextInt(10000)).orNull();
}
return worlds;
}
}
|
Debug and release folders need to be specified separately.
|
var lint = require('./lint');
var clean = require('./clean');
var copy = require('./copy');
var runSequence = require('run-sequence');
exports.config = function(gulp, packageName, source, debugTarget, releaseTarget, useLint) {
lint.config(gulp, source);
clean.config(gulp, debugTarget, releaseTarget);
compile.config(gulp, packageName, source, debugTarget, releaseTarget);
copy.config(gulp, source, debugTarget, releaseTarget);
gulp.task('build', ['build.debug']);
gulp.task('build.debug', function(done) {
if (useLint) {
runSequence('lint',
'clean.debug',
'compile.debug',
'copy.debug',
done);
} else {
runSequence('clean.debug',
'compile.debug',
'copy.debug',
done);
}
});
gulp.task('build.release', function(done) {
if (useLint) {
runSequence('lint',
'clean.release',
'compile.release',
'copy.release',
done);
} else {
runSequence('clean.release',
'compile.release',
'copy.release',
done);
}
});
};
|
var lint = require('./lint');
var clean = require('./clean');
var copy = require('./copy');
var runSequence = require('run-sequence');
exports.config = function(gulp, packageName, source, target, useLint) {
lint.config(gulp, source);
clean.config(gulp, target);
compile.config(gulp, packageName, source, target);
copy.config(gulp, source, target);
gulp.task('build', ['build.debug']);
gulp.task('build.debug', function(done) {
if (useLint) {
runSequence('lint',
'clean.debug',
'compile.debug',
'copy.debug',
done);
} else {
runSequence('clean.debug',
'compile.debug',
'copy.debug',
done);
}
});
gulp.task('build.release', function(done) {
if (useLint) {
runSequence('lint',
'clean.release',
'compile.release',
'copy.release',
done);
} else {
runSequence('clean.release',
'compile.release',
'copy.release',
done);
}
});
};
|
Switch to pycryptodome rather than pycrypto
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 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.
import re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.10
setup(
name='lakeside',
version="0.10",
author='Matthew Garrett',
author_email='mjg59@google.com',
url='http://github.com/google/python-lakeside',
packages=find_packages(),
scripts=[],
description='Python API for controlling Eufy LED bulbs',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
"protobuf",
"pycryptodome",
"requests",
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 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.
import re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.10
setup(
name='lakeside',
version="0.10",
author='Matthew Garrett',
author_email='mjg59@google.com',
url='http://github.com/google/python-lakeside',
packages=find_packages(),
scripts=[],
description='Python API for controlling Eufy LED bulbs',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
"protobuf",
"pycrypto",
"requests",
]
)
|
Fix file registry module test
|
package org.gbif.checklistbank.registry;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.OrganizationService;
import org.gbif.utils.file.FileUtils;
import java.util.UUID;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Test;
import static org.junit.Assert.assertNull;
/**
*
*/
public class FileRegistryModuleTest {
@Test
public void configure() throws Exception {
FileRegistryModule mod = new FileRegistryModule(FileUtils.getClasspathFile("registry-datasets.txt"));
Injector inj = Guice.createInjector(mod);
DatasetService ds = inj.getInstance(DatasetService.class);
assertNull(ds.get(UUID.randomUUID()));
OrganizationService os = inj.getInstance(OrganizationService.class);
assertNull(os.get(UUID.randomUUID()));
}
}
|
package org.gbif.checklistbank.registry;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.OrganizationService;
import java.util.UUID;
import com.google.common.io.Files;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Test;
import static org.junit.Assert.assertNull;
/**
*
*/
public class FileRegistryModuleTest {
@Test
public void configure() throws Exception {
FileRegistryModule mod = new FileRegistryModule(Files.createTempDir());
Injector inj = Guice.createInjector(mod);
DatasetService ds = inj.getInstance(DatasetService.class);
assertNull(ds.get(UUID.randomUUID()));
OrganizationService os = inj.getInstance(OrganizationService.class);
assertNull(os.get(UUID.randomUUID()));
}
}
|
Fix passing variable down to evaluate context
|
/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
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.
*/
module.exports.range = function(start, amount, step = 1) {
const r = [];
for (let i = 0; i < amount; ++i) {
r.push(start + (i * step));
}
return r;
};
module.exports.delay = function(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
};
module.exports.measureStart = function(session, name) {
return session.page.evaluate(_name => {
window.mxPerformanceMonitor.start(_name);
}, name);
};
module.exports.measureStop = function(session, name) {
return session.page.evaluate(_name => {
window.mxPerformanceMonitor.stop(_name);
}, name);
};
|
/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
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.
*/
module.exports.range = function(start, amount, step = 1) {
const r = [];
for (let i = 0; i < amount; ++i) {
r.push(start + (i * step));
}
return r;
};
module.exports.delay = function(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
};
module.exports.measureStart = function(session, name) {
return session.page.evaluate(() => {
window.mxPerformanceMonitor.start(name);
});
};
module.exports.measureStop = function(session, name) {
return session.page.evaluate(() => {
window.mxPerformanceMonitor.stop(name);
});
};
|
Refactor test to eliminate assertRaises() error with Python 2.6
|
from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
for text, p1 in [('(a)', 'a'),
('(aa)', 'aa'),
('(i)','i')]:
result = lower_p.parseString(text)
self.assertEqual(p1, result.p1)
for text in ['(ii)', '(iv)', '(vi)']:
try:
result = lower_p.parseString(text)
except ParseException:
pass
except e:
self.fail("Unexpected error:", e)
else:
self.fail("Didn't raise ParseException")
|
from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
# Match (aa), (bb), etc.
result = lower_p.parseString('(a)')
self.assertEqual('a', result.p1)
result = lower_p.parseString('(aa)')
self.assertEqual('aa', result.p1)
result = lower_p.parseString('(i)')
self.assertEqual('i', result.p1)
# Except for roman numerals
with self.assertRaises(ParseException):
result = lower_p.parseString('(ii)')
with self.assertRaises(ParseException):
result = lower_p.parseString('(iv)')
|
Fix argparse of caffe model download script
|
#!/usr/bin/env python
from __future__ import print_function
import argparse
import six
parser = argparse.ArgumentParser(
description='Download a Caffe reference model')
parser.add_argument('model_type', choices=('alexnet', 'caffenet', 'googlenet'),
help='Model type (alexnet, caffenet, googlenet)')
args = parser.parse_args()
if args.model_type == 'alexnet':
url = 'http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel'
name = 'bvlc_alexnet.caffemodel'
elif args.model_type == 'caffenet':
url = 'http://dl.caffe.berkeleyvision.org/' \
'bvlc_reference_caffenet.caffemodel'
name = 'bvlc_reference_caffenet.caffemodel'
elif args.model_type == 'googlenet':
url = 'http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel'
name = 'bvlc_googlenet.caffemodel'
else:
raise RuntimeError('Invalid model type. Choose from '
'alexnet, caffenet, and googlenet.')
print('Downloading model file...')
six.moves.urllib.request.urlretrieve(url, name)
print('Done')
|
#!/usr/bin/env python
from __future__ import print_function
import argparse
import six
parser = argparse.ArgumentParser(
descriptor='Download a Caffe reference model')
parser.add_argument('model_type',
help='Model type (alexnet, caffenet, googlenet)')
args = parser.parse_args()
if args.model_type == 'alexnet':
url = 'http://dl.caffe.berkeleyvision.org/bvlc_alexnet.caffemodel'
name = 'bvlc_alexnet.caffemodel'
elif args.model_type == 'caffenet':
url = 'http://dl.caffe.berkeleyvision.org/' \
'bvlc_reference_caffenet.caffemodel'
name = 'bvlc_reference_caffenet.caffemodel'
elif args.model_type == 'googlenet':
url = 'http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel'
name = 'bvlc_googlenet.caffemodel'
else:
raise RuntimeError('Invalid model type. Choose from '
'alexnet, caffenet, and googlenet.')
print('Downloading model file...')
six.moves.urllib.request.urlretrieve(url, name)
print('Done')
|
Add trimsuffix to remove windows line endings
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/katnegermis/pocketmine-rcon"
)
func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: ./rcon address password")
return
}
addr := os.Args[1]
pass := os.Args[2]
conn, err := rcon.NewConnection(addr, pass)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Successfully logged in at %s!\n", addr)
prompt()
stdin := bufio.NewReader(os.Stdin)
input := ""
for {
if input, err = stdin.ReadString('\n'); err != nil {
fmt.Println(err)
return
}
input = strings.TrimSuffix(input, "\r\n")
input = strings.Trim(input[:len(input)-1], " ")
if input == ".exit" {
break
}
if len(input) == 0 {
prompt()
continue
}
r, err := conn.SendCommand(input)
if err != nil {
fmt.Printf("Error: %s\n", err)
prompt()
continue
}
fmt.Printf("Server:\n%s\n", r)
prompt()
}
}
func prompt() {
fmt.Print("Enter command:\n>")
}
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/katnegermis/pocketmine-rcon"
)
func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: ./rcon address password")
return
}
addr := os.Args[1]
pass := os.Args[2]
conn, err := rcon.NewConnection(addr, pass)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Successfully logged in at %s!\n", addr)
prompt()
stdin := bufio.NewReader(os.Stdin)
input := ""
for {
if input, err = stdin.ReadString('\n'); err != nil {
fmt.Println(err)
return
}
input = strings.Trim(input[:len(input)-1], " ")
if input == ".exit" {
break
}
if len(input) == 0 {
prompt()
continue
}
r, err := conn.SendCommand(input)
if err != nil {
fmt.Printf("Error: %s\n", err)
prompt()
continue
}
fmt.Printf("Server:\n%s\n", r)
prompt()
}
}
func prompt() {
fmt.Print("Enter command:\n>")
}
|
Make collection base instance of hydratable collection
|
<?php declare(strict_types=1);
namespace Onion\Framework\Collection;
use Onion\Framework\Hydrator\Interfaces\HydratableInterface;
class HydratableCollection extends CallbackCollection
{
private $items;
private $entityClass;
public function __construct(iterable $items, string $entity)
{
if (!class_exists($entity)) {
throw new \InvalidArgumentException(
"Provided entity '{$entity}' does not exist"
);
}
$reflection = new \ReflectionClass($this->entityClass);
if (!$reflection->implementsInterface(HydratableInterface::class)) {
throw new \InvalidArgumentException(
"Provided '{$entity}' does not implement: " . HydratableInterface::class
);
}
$prototype = $reflection->newInstance();
parent::__construct($items, function ($item, $key) use ($prototype) {
/** @var HydratableInterface $prototype */
return $prototype->hydrate($item);
});
}
}
|
<?php declare(strict_types=1);
namespace Onion\Framework\Collection;
use Onion\Framework\Hydrator\Interfaces\HydratableInterface;
class HydratableCollection implements \IteratorAggregate
{
private $items;
private $entityClass;
public function __construct(iterable $items, string $entity)
{
$this->items = $items;
if (!in_array(HydratableInterface::class, class_implements($entity), true)) {
throw new \InvalidArgumentException(
"Provided '{$entity}' does not exist or does not implement: " .
HydratableInterface::class
);
}
$this->entityClass = $entity;
}
public function getIterator()
{
$entity = (new \ReflectionClass($this->entityClass))->newInstance();
return new CallbackCollection($this->items, function ($item, $key) use ($entity) {
/** @var HydratableInterface $entity */
return $entity->hydrate($item);
});
}
}
|
Simplify (POSFilter).apply() by replacing if-else by a comparison expression.
|
package filter
import (
"github.com/ikawaha/kagome/v2/tokenizer"
)
type (
POS = []string
)
type POSFilter struct {
filter *FeaturesFilter
}
// NewPOSFilter returns a part of speech filter.
func NewPOSFilter(stops ...POS) *POSFilter {
return &POSFilter{
filter: NewFeaturesFilter(stops...),
}
}
// Match returns true if a filter matches given POS.
func (f POSFilter) Match(p POS) bool {
return f.filter.Match(p)
}
// Drop drops a token if a filter matches token's POS.
func (f POSFilter) Drop(tokens *[]tokenizer.Token) {
f.apply(tokens, true)
}
// PickUp picks up a token if a filter matches token's POS.
func (f POSFilter) PickUp(tokens *[]tokenizer.Token) {
f.apply(tokens, false)
}
func (f POSFilter) apply(tokens *[]tokenizer.Token, drop bool) {
if tokens == nil {
return
}
tail := 0
for i, v := range *tokens {
if f.Match(v.POS()) == drop {
continue
}
if i != tail {
(*tokens)[tail] = v
}
tail++
}
*tokens = (*tokens)[:tail]
}
|
package filter
import (
"github.com/ikawaha/kagome/v2/tokenizer"
)
type (
POS = []string
)
type POSFilter struct {
filter *FeaturesFilter
}
// NewPOSFilter returns a part of speech filter.
func NewPOSFilter(stops ...POS) *POSFilter {
return &POSFilter{
filter: NewFeaturesFilter(stops...),
}
}
// Match returns true if a filter matches given POS.
func (f POSFilter) Match(p POS) bool {
return f.filter.Match(p)
}
// Drop drops a token if a filter matches token's POS.
func (f POSFilter) Drop(tokens *[]tokenizer.Token) {
f.apply(tokens, true)
}
// PickUp picks up a token if a filter matches token's POS.
func (f POSFilter) PickUp(tokens *[]tokenizer.Token) {
f.apply(tokens, false)
}
func (f POSFilter) apply(tokens *[]tokenizer.Token, drop bool) {
if tokens == nil {
return
}
tail := 0
for i, v := range *tokens {
if f.Match(v.POS()) {
if drop {
continue
}
} else if !drop {
continue
}
if i != tail {
(*tokens)[tail] = (*tokens)[i]
}
tail++
}
*tokens = (*tokens)[:tail]
}
|
Update dataSample to index on the ints returned by random_pairs
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
Change authenticate_credentials method to raise an exception if the account is disabled
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
from django.conf import settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
Add filecheck in the scripts
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='kittengroomer',
version='1.0',
author='Raphaël Vinot',
author_email='raphael.vinot@circl.lu',
maintainer='Raphaël Vinot',
url='https://github.com/CIRCL/CIRCLean',
description='Standalone CIRCLean/KittenGroomer code.',
packages=['kittengroomer'],
scripts=['bin/generic.py', 'bin/pier9.py', 'bin/specific.py', 'bin/filecheck.py'],
include_package_data = True,
package_data = {'data': ['PDFA_def.ps','srgb.icc']},
test_suite="tests",
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Communications :: File Sharing',
'Topic :: Security',
],
install_requires=['twiggy'],
)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='kittengroomer',
version='1.0',
author='Raphaël Vinot',
author_email='raphael.vinot@circl.lu',
maintainer='Raphaël Vinot',
url='https://github.com/CIRCL/CIRCLean',
description='Standalone CIRCLean/KittenGroomer code.',
packages=['kittengroomer'],
scripts=['bin/generic.py', 'bin/pier9.py', 'bin/specific.py'],
include_package_data = True,
package_data = {'data': ['PDFA_def.ps','srgb.icc']},
test_suite="tests",
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Communications :: File Sharing',
'Topic :: Security',
],
install_requires=['twiggy'],
)
|
Remove duplicate form new entities
|
<ul class="toolbar toolbar-right">
<?= $this->partial('tools-top') ?>
<?php if ($info->is->duplicateable && !$entity->isNew()) { ?>
<li><a href="<?= $this->url([
'action' => 'duplicate',
]) ?>" class="btn btn-focus btn-out icon-copy confirmable">
Duplicate
</a></li>
<?php } ?>
<?php if (array_intersect(['create'], $actions) && !$entity->isNew()) { ?>
<li><?= $this->inner('new', ['class' => 'btn-out']) ?></li>
<?php } ?>
<?= $this->partial('tools-bottom') ?>
</ul>
|
<ul class="toolbar toolbar-right">
<?= $this->partial('tools-top') ?>
<?php if ($info->is->duplicateable) { ?>
<li><a href="<?= $this->url([
'action' => 'duplicate',
]) ?>" class="btn btn-focus btn-out icon-copy confirmable">
Duplicate
</a></li>
<?php } ?>
<?php if (array_intersect(['create'], $actions) && !$entity->isNew()) { ?>
<li><?= $this->inner('new', ['class' => 'btn-out']) ?></li>
<?php } ?>
<?= $this->partial('tools-bottom') ?>
</ul>
|
Tweak error message, reformat for flake8
|
from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres table/view names.
# Check self.type to exclude test relation identifiers
if (self.identifier is not None and self.type is not None and
len(self.identifier) > self.relation_max_name_length()):
raise RuntimeException(
f"Relation name '{self.identifier}' "
f"is longer than {self.relation_max_name_length()} characters"
)
def relation_max_name_length(self):
return 63
class PostgresColumn(Column):
@property
def data_type(self):
# on postgres, do not convert 'text' to 'varchar()'
if self.dtype.lower() == 'text':
return self.dtype
return super().data_type
|
from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres table/view names.
# Check self.type to exclude test relation identifiers
if (
self.identifier is not None
and self.type is not None
and len(self.identifier) > self.relation_max_name_length()
):
raise RuntimeException(
f"Postgres relation name '{self.identifier}' is longer than "
f"{self.relation_max_name_length()} characters"
)
def relation_max_name_length(self):
return 63
class PostgresColumn(Column):
@property
def data_type(self):
# on postgres, do not convert 'text' to 'varchar()'
if self.dtype.lower() == 'text':
return self.dtype
return super().data_type
|
Fix errors in FastBoot if user-agent is blank
|
import Service from 'ember-service';
import get, { getProperties } from 'ember-metal/get';
import set from 'ember-metal/set';
import computed from 'ember-computed';
import getOwner from 'ember-owner/get';
import isMobile from 'ismobilejs';
export default Service.extend({
fastboot: computed(function() {
return getOwner(this).lookup('service:fastboot');
}),
init() {
this._super(...arguments);
let queries = [];
if (get(this, 'fastboot.isFastBoot')) {
const headers = get(this, 'fastboot.request.headers');
const userAgent = headers.get('user-agent');
if (userAgent) {
queries = getProperties(
isMobile(userAgent),
['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other']
);
}
} else {
queries = isMobile;
}
for (let media in queries) {
set(this, media, queries[media]);
}
}
});
|
import Service from 'ember-service';
import get, { getProperties } from 'ember-metal/get';
import set from 'ember-metal/set';
import computed from 'ember-computed';
import getOwner from 'ember-owner/get';
import isMobile from 'ismobilejs';
export default Service.extend({
fastboot: computed(function() {
return getOwner(this).lookup('service:fastboot');
}),
init() {
this._super(...arguments);
let queries;
if (get(this, 'fastboot.isFastBoot')) {
const headers = get(this, 'fastboot.request.headers');
const userAgent = headers.get('user-agent');
queries = getProperties(isMobile(userAgent), ['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other']);
} else {
queries = isMobile;
}
for (let media in queries) {
set(this, media, queries[media]);
}
}
});
|
Remove unnecessary Hadoop listLocatedStatus shim
|
/*
* 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 com.facebook.presto.hive;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import java.io.IOException;
public class HadoopDirectoryLister
implements DirectoryLister
{
@Override
public RemoteIterator<LocatedFileStatus> list(FileSystem fs, Path path)
throws IOException
{
return fs.listLocatedStatus(path);
}
}
|
/*
* 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 com.facebook.presto.hive;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import java.io.IOException;
import static com.facebook.presto.hadoop.HadoopFileSystem.listLocatedStatus;
public class HadoopDirectoryLister
implements DirectoryLister
{
@Override
public RemoteIterator<LocatedFileStatus> list(FileSystem fs, Path path)
throws IOException
{
return listLocatedStatus(fs, path);
}
}
|
Make songs-list a list of list-items
|
import React from 'react';
import { Avatar, List, ListItem } from 'material-ui';
import { BaseViewComponent } from '../higher-order/index.js';
class RedditPosts extends BaseViewComponent {
constructor(props) {
super(props);
}
render() {
return (
<div className="posts">
<div className="posts-fetch">
<p onClick={this.props.fetchPosts}>Fetch posts</p>
</div>
<div className="posts-list">
<List>
{this.props.posts.map(function renderPosts(post) {
let avatar = (<Avatar src={post.thumbnail} />);
return (
<ListItem leftAvatar={avatar}>
<div key={post.id} className="posts">
{post.title}
</div>
</ListItem>
);
})}
</List>
</div>
</div>
);
}
}
RedditPosts.propTypes = {
posts: React.PropTypes.array.isRequired,
fetchPosts: React.PropTypes.func.isRequired
};
export default RedditPosts;
|
import React from 'react';
import { BaseViewComponent } from '../higher-order/index.js';
class RedditPosts extends BaseViewComponent {
constructor(props) {
super(props);
}
render() {
return (
<div className="posts">
<div className="posts-fetch">
<p onClick={this.props.fetchPosts}>Fetch posts</p>
</div>
<div className="posts-list">
{this.props.posts.map(function renderPosts(post) {
return (
<div key={post.id} className="posts">
<p>{post.title}</p>
</div>
);
})}
</div>
</div>
);
}
}
RedditPosts.propTypes = {
posts: React.PropTypes.array.isRequired,
fetchPosts: React.PropTypes.func.isRequired
};
export default RedditPosts;
|
Change log format (added PID)
|
#!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
pearbot.py
The PearBot IRC bot entry point.
It sets up logging and starts up the IRC client.
Copyright (c) 2014 Twisted Pear <pear at twistedpear dot at>
See the file LICENSE for copying permission.
"""
import asyncio
import command
import config
import logging
import protocol
import signal
LOG_FORMAT = "{asctime} [{process}] {levelname}({name}): {message}"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, style="{")
def main():
logger = logging.getLogger("pearbot")
logger.info("PearBot started.")
loop = asyncio.get_event_loop()
client_config = config.get_config("irc")
client = protocol.Protocol(**client_config)
cmdhdl_config = config.get_config("cmd")
# we don't need to remember this instance
command.CommandHandler(client, **cmdhdl_config)
def shutdown():
logger.info("Shutdown signal received.")
client.shutdown()
loop.add_signal_handler(signal.SIGTERM, shutdown)
logger.info("Running protocol activity.")
task = client.run()
loop.run_until_complete(task)
logger.info("Protocol activity ceased.")
logger.info("Exiting...")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
pearbot.py
The PearBot IRC bot entry point.
It sets up logging and starts up the IRC client.
Copyright (c) 2014 Twisted Pear <pear at twistedpear dot at>
See the file LICENSE for copying permission.
"""
import asyncio
import command
import config
import logging
import protocol
import signal
LOG_FORMAT = "%(asctime)-15s %(name)-10s %(levelname)-8s %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
def main():
logger = logging.getLogger("pearbot")
logger.info("PearBot started.")
loop = asyncio.get_event_loop()
client_config = config.get_config("irc")
client = protocol.Protocol(**client_config)
cmdhdl_config = config.get_config("cmd")
# we don't need to remember this instance
command.CommandHandler(client, **cmdhdl_config)
def shutdown():
logger.info("Shutdown signal received.")
client.shutdown()
loop.add_signal_handler(signal.SIGTERM, shutdown)
logger.info("Running protocol activity.")
task = client.run()
loop.run_until_complete(task)
logger.info("Protocol activity ceased.")
logger.info("Exiting...")
if __name__ == "__main__":
main()
|
Move var err inside if statement
|
package command
import (
"strings"
"os"
"log"
"fmt"
"github.com/wantedly/developers-account-mapper/store"
"github.com/wantedly/developers-account-mapper/models"
)
type RegisterCommand struct {
Meta
}
func (c *RegisterCommand) Run(args []string) int {
var loginName, githubUsername string
if len(args) == 1 {
loginName = os.Getenv("USER")
githubUsername = args[0]
} else if len(args) == 2 {
loginName = args[0]
githubUsername = args[1]
} else {
log.Println(c.Help())
return 1
}
s := store.NewDynamoDB()
user := models.NewUser(loginName, githubUsername)
if err := s.AddUser(user); err != nil {
log.Println(err)
return 1
}
fmt.Printf("user %v added.\n", user)
return 0
}
func (c *RegisterCommand) Synopsis() string {
return "Register LoginName and GitHubUsername mapping"
}
func (c *RegisterCommand) Help() string {
helpText := `
`
return strings.TrimSpace(helpText)
}
|
package command
import (
"strings"
"os"
"log"
"fmt"
"github.com/wantedly/developers-account-mapper/store"
"github.com/wantedly/developers-account-mapper/models"
)
type RegisterCommand struct {
Meta
}
func (c *RegisterCommand) Run(args []string) int {
var loginName, githubUsername string
if len(args) == 1 {
loginName = os.Getenv("USER")
githubUsername = args[0]
} else if len(args) == 2 {
loginName = args[0]
githubUsername = args[1]
} else {
log.Println(c.Help())
return 1
}
s := store.NewDynamoDB()
user := models.NewUser(loginName, githubUsername)
err := s.AddUser(user)
if err != nil {
log.Println(err)
return 1
}
fmt.Printf("user %v added.\n", user)
return 0
}
func (c *RegisterCommand) Synopsis() string {
return "Register LoginName and GitHubUsername mapping"
}
func (c *RegisterCommand) Help() string {
helpText := `
`
return strings.TrimSpace(helpText)
}
|
Update so you can override the transform date function
|
<?php
namespace JDT\Api\Transformers;
use Carbon\Carbon;
use League\Fractal\TransformerAbstract;
/**
* Class AbstractTransformer.
*/
abstract class AbstractTransformer extends TransformerAbstract
{
protected $links = [];
protected static $transformDate;
/**
* @param callable $transformDate
*/
public static function setTransformDate(callable $transformDate)
{
self::$transformDate = $transformDate;
}
/**
* @param $data
* @return array
*/
public function transform($data):array
{
if ($data === null) {
return [];
}
if (method_exists($this, 'transformData') === false) {
throw new \RuntimeException('Your parent class must have the function transformData');
}
$transformed = $this->transformData($data);
return $transformed;
}
/**
* @param \Carbon\Carbon $date
* @return array
*/
protected function transformDate(Carbon $date):array
{
if (self::$transformDate !== null) {
return call_user_func(self::$transformDate, $date);
}
return [
'utc' => $date->toRfc3339String(),
];
}
}
|
<?php
namespace JDT\Api\Transformers;
use Carbon\Carbon;
use League\Fractal\TransformerAbstract;
/**
* Class AbstractTransformer.
*/
abstract class AbstractTransformer extends TransformerAbstract
{
protected $links = [];
/**
* @param $data
* @return array
*/
public function transform($data):array
{
if ($data === null) {
return [];
}
if (method_exists($this, 'transformData') === false) {
throw new \RuntimeException('Your parent class must have the function transformData');
}
$transformed = $this->transformData($data);
return $transformed;
}
/**
* @param \Carbon\Carbon $date
* @return array
*/
protected function transformDate(Carbon $date):array
{
return $date->toRfc3339String();
}
}
|
Check for trailing slash in path
|
""" Utility functions for PhotoScan processing """
import os, sys
import PhotoScan
def align_and_clean_photos(chunk):
ncameras = len(chunk.cameras)
for frame in chunk.frames:
frame.matchPhotos()
chunk.alignCameras()
for camera in chunk.cameras:
if camera.transform is None:
chunk.remove(camera)
naligned = len(chunk.cameras)
print('%d/%d cameras aligned' % (naligned, ncameras))
def export_dems(resolution, formatstring, pathname)
if not os.path.isdir(pathname):
os.mkdir(pathname)
if pathname[-1:] is not '/':
pathname = ''.join(pathname, '/')
nchunks = len(PhotoScan.app.document.chunks)
nexported = nchunks
for chunk in PhotoScan.app.document.chunks:
filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
if not exported:
print('Export failed:', chunk.label)
nexported -= 1
print('%d/%d DEMs exported' % (nexported, nchunks))
|
""" Utility functions for PhotoScan processing """
import os, sys
import PhotoScan
def align_and_clean_photos(chunk):
ncameras = len(chunk.cameras)
for frame in chunk.frames:
frame.matchPhotos()
chunk.alignCameras()
for camera in chunk.cameras:
if camera.transform is None:
chunk.remove(camera)
naligned = len(chunk.cameras)
print('%d/%d cameras aligned' % (naligned, ncameras))
def export_dems(resolution, formatstring, pathname)
if not os.path.isdir(pathname):
os.mkdir(pathname)
nchunks = len(PhotoScan.app.document.chunks)
nexported = nchunks
for chunk in PhotoScan.app.document.chunks:
filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
if not exported:
print('Export failed:', chunk.label)
nexported -= 1
print('%d/%d DEMs exported' % (nexported, nchunks))
|
Change entry for CLI layout
|
import fs from 'fs';
import path from 'path';
import { Reader } from 'fstream';
import { Pack } from 'tar';
/** pose.save
* @desc Save a template.
* @param {Object} opts - Options.
*/
function save(opts = {}) {
const name = opts._[1] || opts.name;
const entry = opts._[2] || opts.entry;
const destPath = path.join(opts._templates, `${name}.tar`);
const dest = fs.createWriteStream(destPath);
const pack = new Pack({ noProprietary: true });
const read = new Reader({ path: entry, type: 'Directory' })
.pipe(pack)
.pipe(dest);
pack.on('end', () => {
console.log(`Saved ${name}.`);
});
pack.on('error', () => {
console.log(`Failed to pack ${destPath}`);
});
read.on('error', () => {
console.log(`Failed to read ${entry}.`);
});
}
export default save;
|
import fs from 'fs';
import path from 'path';
import { Reader } from 'fstream';
import { Pack } from 'tar';
/** pose.save
* @desc Save a template.
* @param {Object} opts - Options.
*/
function save(opts = {}) {
const name = opts._[1] || opts.name;
const destPath = path.join(opts._templates, `${name}.tar`);
const dest = fs.createWriteStream(destPath);
const pack = new Pack({ noProprietary: true });
const read = new Reader({ path: opts.entry, type: 'Directory' })
.pipe(pack)
.pipe(dest);
pack.on('end', () => {
console.log(`Saved ${name}.`);
});
pack.on('error', () => {
console.log(`Failed to pack ${destPath}`);
});
read.on('error', () => {
console.log(`Failed to read ${opts.entry}.`);
});
}
export default save;
|
Change mocking scope to take effect
|
from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch.object(pathutils.os, 'walk')
def test_grep_r(self, mock_walk):
mock_walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@patch.object(pathutils, 'os')
def test_grep_r(self, mock_os):
mock_os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
Remove print statement and change mask to use a fixed length
|
"""
sentry.core.processors
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class Processor(object):
def process(self, data):
resp = self.get_data(data)
if resp:
data['extra'].update(resp)
return data
def get_data(self, data):
return {}
def sanitize_passwords_processor(data):
""" Asterisk out passwords from password fields in frames.
"""
if 'sentry.interfaces.Exception' in data:
if 'frames' in data['sentry.interfaces.Exception']:
for frame in data['sentry.interfaces.Exception']['frames']:
if 'vars' in frame:
for k,v in frame['vars'].iteritems():
if k.startswith('password'):
# store mask as a fixed length for security
frame['vars'][k] = '*'*16
return data
#class SantizePasswordsProcessor(Processor):
|
"""
sentry.core.processors
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class Processor(object):
def process(self, data):
resp = self.get_data(data)
if resp:
data['extra'].update(resp)
return data
def get_data(self, data):
return {}
from pprint import pprint
def sanitize_passwords_processor(data):
""" Asterisk out passwords from password fields in frames.
"""
if 'sentry.interfaces.Exception' in data:
if 'frames' in data['sentry.interfaces.Exception']:
for frame in data['sentry.interfaces.Exception']['frames']:
if 'vars' in frame:
print frame['vars']
for k,v in frame['vars'].iteritems():
if k.startswith('password'):
frame['vars'][k] = '*'*len(v)
return data
#class SantizePasswordsProcessor(Processor):
|
Install pyramid 1.5 or newer which has the new SignedCookieSessionFactory
|
# -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'openstax-accounts',
'psycopg2',
'pyramid>=1.5',
'pyramid_multiauth',
)
tests_require = [
'webtest',
]
extras_require = {
'test': tests_require,
}
description = """\
Application for accepting publication requests to the Connexions Archive."""
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-publishing',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-publishing",
license='LGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
test_suite='cnxpublishing.tests',
packages=find_packages(),
include_package_data=True,
package_data={
'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points="""\
[paste.app_factory]
main = cnxpublishing.main:main
[console_scripts]
cnx-publishing-initdb = cnxpublishing.scripts.initdb:main
""",
)
|
# -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'openstax-accounts',
'psycopg2',
'pyramid',
'pyramid_multiauth',
)
tests_require = [
'webtest',
]
extras_require = {
'test': tests_require,
}
description = """\
Application for accepting publication requests to the Connexions Archive."""
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-publishing',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-publishing",
license='LGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
test_suite='cnxpublishing.tests',
packages=find_packages(),
include_package_data=True,
package_data={
'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points="""\
[paste.app_factory]
main = cnxpublishing.main:main
[console_scripts]
cnx-publishing-initdb = cnxpublishing.scripts.initdb:main
""",
)
|
Rename test check channel home to check create home
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from opps.core.models.channel import Channel
class ChannelModelTest(TestCase):
def setUp(self):
self.site = Site.objects.filter(name=u'example.com').get()
self.channel = Channel.objects.create(name=u'Home', slug=u'home',
description=u'home page', site=self.site)
def test_check_create_home(self):
"""
Check exist channel home, create on setup class
"""
home = Channel.objects.filter(slug=u'home').get()
self.assertTrue(home)
self.assertEqual(home, self.channel)
def test_not_is_published(self):
"""
is_published false on home channel
"""
home = Channel.objects.filter(slug=u'home').get()
self.assertFalse(home.is_published())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from opps.core.models.channel import Channel
class ChannelModelTest(TestCase):
def setUp(self):
self.site = Site.objects.filter(name=u'example.com').get()
self.channel = Channel.objects.create(name=u'Home', slug=u'home',
description=u'home page', site=self.site)
def test_check_home_channel(self):
"""
Check exist channel home, create on setup class
"""
home = Channel.objects.filter(slug=u'home').get()
self.assertTrue(home)
self.assertEqual(home, self.channel)
def test_not_is_published(self):
"""
is_published false on home channel
"""
home = Channel.objects.filter(slug=u'home').get()
self.assertFalse(home.is_published())
|
Make path and description fields text fields instead of string fields
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinephotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machinephotos', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->default(0);
$table->text('machine_photo_path')->nullable();
$table->text('machine_photo_thumb')->nullable();
$table->text('photo_description',)->nullable();
$table->softDeletes();
$table->timestamps();
$table->foreign('machine_id')->references('id')->on('machines');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('machinephotos');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinephotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machinephotos', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->default(0);
$table->string('machine_photo_path', 255)->nullable();
$table->string('machine_photo_thumb', 255)->nullable();
$table->string('photo_description', 255)->nullable();
$table->softDeletes();
$table->timestamps();
$table->foreign('machine_id')->references('id')->on('machines');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('machinephotos');
}
}
|
Fix izip import for python3
|
# -*- coding: utf-8 -*-
"""
molvs.utils
~~~~~~~~~~~
This module contains miscellaneous utility functions.
:copyright: Copyright 2014 by Matt Swain.
:license: MIT, see LICENSE file for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import functools
from itertools import tee
try:
from itertools import izip
except ImportError:
izip = zip
def memoized_property(fget):
"""Decorator to create memoized properties."""
attr_name = '_{}'.format(fget.__name__)
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
return property(fget_memoized)
def pairwise(iterable):
"""Utility function to iterate in a pairwise fashion."""
a, b = tee(iterable)
next(b, None)
return izip(a, b)
|
# -*- coding: utf-8 -*-
"""
molvs.utils
~~~~~~~~~~~
This module contains miscellaneous utility functions.
:copyright: Copyright 2014 by Matt Swain.
:license: MIT, see LICENSE file for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import functools
from itertools import izip, tee
def memoized_property(fget):
"""Decorator to create memoized properties."""
attr_name = '_{}'.format(fget.__name__)
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
return property(fget_memoized)
def pairwise(iterable):
"""Utility function to iterate in a pairwise fashion."""
a, b = tee(iterable)
next(b, None)
return izip(a, b)
|
Add in html5lib as a requirement for Python 2.6
This should fix https://travis-ci.org/Manishearth/ChatExchange/jobs/179059319.
|
import setuptools
setuptools.setup(
name='ChatExchange',
version='0.0.3',
url='https://github.com/Manishearth/ChatExchange',
packages=[
'chatexchange'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage==3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3',
'py>=1.4.29'
# Only for Python 2.6
'html5lib>=0.999999999'
]
)
|
import setuptools
setuptools.setup(
name='ChatExchange',
version='0.0.3',
url='https://github.com/Manishearth/ChatExchange',
packages=[
'chatexchange'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage==3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3',
'py>=1.4.29'
]
)
|
Test does not need to start a user connection
|
package chat_test
import (
"testing"
"github.com/spring1843/chat-server/src/chat"
"github.com/spring1843/chat-server/src/drivers/fake"
)
func TestCanWriteToUser(t *testing.T) {
user1 := chat.NewUser("bar")
msg := "foo"
go user1.SetOutgoing(msg)
outgoing := user1.GetOutgoing()
if outgoing != msg {
t.Errorf("Received message %q which is not equal to %q", outgoing, msg)
}
}
func TestCanReadFromUser(t *testing.T) {
t.Skipf("Racy")
fakeReader := fake.NewFakeConnection()
input := "foo\n"
n, err := fakeReader.WriteString(input)
if err != nil {
t.Fatalf("Failed writing to connection. Error %s", err)
}
if n != len(input) {
t.Fatalf("Wrong length after write. Expected %d, got %d.", len(input), n)
}
user1 := chat.NewConnectedUser(server, fakeReader)
msg := user1.GetIncoming()
if msg != "foo" {
t.Errorf("Message was not read from the user, got %s", msg)
}
}
|
package chat_test
import (
"testing"
"github.com/spring1843/chat-server/src/chat"
"github.com/spring1843/chat-server/src/drivers/fake"
)
func TestCanWriteToUser(t *testing.T) {
fakeWriter := fake.NewFakeConnection()
user1 := chat.NewConnectedUser(server, fakeWriter)
go user1.SetOutgoing(`foo`)
chat.ExpectOutgoing(t, user1, 5, "foo")
}
func TestCanReadFromUser(t *testing.T) {
t.Skipf("Racy")
fakeReader := fake.NewFakeConnection()
input := "foo\n"
n, err := fakeReader.WriteString(input)
if err != nil {
t.Fatalf("Failed writing to connection. Error %s", err)
}
if n != len(input) {
t.Fatalf("Wrong length after write. Expected %d, got %d.", len(input), n)
}
user1 := chat.NewConnectedUser(server, fakeReader)
msg := user1.GetIncoming()
if msg != "foo" {
t.Errorf("Message was not read from the user, got %s", msg)
}
}
|
Add cssmin and jsmin to requires
|
from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'cssmin',
'jsmin',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
|
from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
|
Fix break in commentmap where first sibling is null
|
function commentsMap(comment, parent, op, score=4, nthSibling=0, nthNest=0, siblingHidden=false) {
var i = 0;
var length;
if (comment == undefined) {
return;
}
// Start degrading
score--;
// Show longer threads involving op
if (comment.author == op || comment.gilded) {
score++;
// Show longer threads if a parent has a higher score
} else if (parent && comment.score > (parent.score * (nthSibling + nthNest + 1))) {
score++;
}
if (nthSibling > score || nthSibling > 5 || nthNest > 5) {
comment.hidden = true;
}
// If score is low, or if it is a long sibling chain, hide
if (score < 0 || (parent && parent.hidden) || siblingHidden) {
comment.hidden = true;
}
if (comment.hidden && parent && !parent.hidden && !siblingHidden) {
comment.firstHidden = true;
}
comment.hideScore = score;
if (!comment.replies) {
return comment;
}
length = comment.replies.length;
i = 0;
// Increment the nesting level before we recurse through children
nthNest++;
comment.replies = comment.replies.map(function(c, i) {
var sh = siblingHidden;
if (i > 0 && comment.replies[i-1]) {
sh = comment.replies[i-1].hidden;
}
return commentsMap(c, comment, op, score, i, nthNest, sh);
});
return comment;
}
export default commentsMap;
|
function commentsMap(comment, parent, op, score=4, nthSibling=0, nthNest=0, siblingHidden=false) {
var i = 0;
var length;
if (comment == undefined) {
return;
}
// Start degrading
score--;
// Show longer threads involving op
if (comment.author == op || comment.gilded) {
score++;
// Show longer threads if a parent has a higher score
} else if (parent && comment.score > (parent.score * (nthSibling + nthNest + 1))) {
score++;
}
if (nthSibling > score || nthSibling > 5 || nthNest > 5) {
comment.hidden = true;
}
// If score is low, or if it is a long sibling chain, hide
if (score < 0 || (parent && parent.hidden) || siblingHidden) {
comment.hidden = true;
}
if (comment.hidden && parent && !parent.hidden && !siblingHidden) {
comment.firstHidden = true;
}
comment.hideScore = score;
if (!comment.replies) {
return comment;
}
length = comment.replies.length;
i = 0;
// Increment the nesting level before we recurse through children
nthNest++;
comment.replies = comment.replies.map(function(c, i) {
var sh = siblingHidden;
if (i > 0) {
sh = comment.replies[i-1].hidden;
}
return commentsMap(c, comment, op, score, i, nthNest, sh);
});
return comment;
}
export default commentsMap;
|
Remove constant only used once
|
package com.kickstarter.services.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.R;
import timber.log.Timber;
public class UnregisterService extends IntentService {
public UnregisterService() {
super("UnregisterService");
}
@Override
protected void onHandleIntent(@NonNull final Intent intent) {
Timber.d("onHandleIntent");
try {
final InstanceID instanceID = InstanceID.getInstance(this);
instanceID.deleteToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
Timber.d("Deleted token");
} catch (final Exception e) {
Timber.e("Failed to delete token: " + e.toString());
}
}
}
|
package com.kickstarter.services.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.R;
import timber.log.Timber;
public class UnregisterService extends IntentService {
private static final String WORKER_THREAD_NAME = "UnregisterService";
public UnregisterService() {
super(WORKER_THREAD_NAME);
}
@Override
protected void onHandleIntent(@NonNull final Intent intent) {
Timber.d("onHandleIntent");
try {
final InstanceID instanceID = InstanceID.getInstance(this);
instanceID.deleteToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
Timber.d("Deleted token");
} catch (final Exception e) {
Timber.e("Failed to delete token: " + e.toString());
}
}
}
|
Remove the navigator.platform info from my poor man’s error tracking script.
|
/* global ga */
var errorTracking = (function() {
'use strict';
// http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
var _sendErrorsToGoogleAnalytics = function () {
window.addEventListener('error', function (err) {
var ie = window.event || {};
var errorMessage = err.message || ie.errorMessage;
var errorFilename = err.filename || ie.errorUrl;
var errorLineNumber = ', Line: ' + (err.lineno || ie.errorLine);
var errorColumnNumber = ', Column: ' + (err.colno || 'undefined'); // print undefined as a string if it doesn’t exist
var userAgent = ', User Agent: ' + navigator.userAgent;
ga('send', 'event', 'JavaScript Errors', errorMessage, errorFilename + errorLineNumber + errorColumnNumber + userAgent, 0, true);
});
};
var init = function () {
_sendErrorsToGoogleAnalytics();
};
return {
init: init
};
}());
|
/* global ga */
var errorTracking = (function() {
'use strict';
// http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
var _sendErrorsToGoogleAnalytics = function () {
window.addEventListener('error', function (err) {
var ie = window.event || {};
var errorMessage = err.message || ie.errorMessage;
var errorFilename = err.filename || ie.errorUrl;
var errorLineNumber = ', Line: ' + (err.lineno || ie.errorLine);
var errorColumnNumber = ', Column: ' + (err.colno || 'undefined'); // print undefined as a string if it doesn’t exist
var userAgent = ', User Agent: ' + navigator.userAgent;
var platform = ', Platform: ' + navigator.platform;
ga('send', 'event', 'JavaScript Errors', errorMessage, errorFilename + errorLineNumber + errorColumnNumber + userAgent + platform, 0, true);
});
};
var init = function () {
_sendErrorsToGoogleAnalytics();
};
return {
init: init
};
}());
|
Set default values for fields
|
# -*- encoding: utf-8 -*-
from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
default=u''
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
default=False
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
|
# -*- encoding: utf-8 -*-
from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
|
Add removeFromQueue function to cancel sending a queued event
|
var MatrixClientPeg = require('./MatrixClientPeg');
var dis = require('./dispatcher');
module.exports = {
resend: function(event) {
MatrixClientPeg.get().resendEvent(
event, MatrixClientPeg.get().getRoom(event.getRoomId())
).done(function() {
dis.dispatch({
action: 'message_sent',
event: event
});
}, function() {
dis.dispatch({
action: 'message_send_failed',
event: event
});
});
dis.dispatch({
action: 'message_resend_started',
event: event
});
},
removeFromQueue: function(event) {
MatrixClientPeg.get().getScheduler().removeEventFromQueue(event);
var room = MatrixClientPeg.get().getRoom(event.getRoomId());
if (!room) {
return;
}
room.removeEvents([event.getId()]);
}
};
|
var MatrixClientPeg = require('./MatrixClientPeg');
var dis = require('./dispatcher');
module.exports = {
resend: function(event) {
MatrixClientPeg.get().resendEvent(
event, MatrixClientPeg.get().getRoom(event.getRoomId())
).done(function() {
dis.dispatch({
action: 'message_sent',
event: event
});
}, function() {
dis.dispatch({
action: 'message_send_failed',
event: event
});
});
dis.dispatch({
action: 'message_resend_started',
event: event
});
},
};
|
Add hashCode and equals to actor model, since a show holds all actors in a HashSet
|
package models;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "actors")
public class Actor extends Model {
@Id
private Long id;
@Constraints.Required
@Column(unique = true)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Finder<Long, Actor> find = new Finder<>(Long.class, Actor.class);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Actor actor = (Actor) o;
if (name != null ? !name.equals(actor.name) : actor.name != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
|
package models;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "actors")
public class Actor extends Model {
@Id
private Long id;
@Constraints.Required
@Column(unique = true)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Finder<Long, Actor> find = new Finder<>(Long.class, Actor.class);
}
|
Fix a bug where the review request summary shown in the Review dialog was being HTML-escaped but really needed to be JavaScript-escaped.
Fixes bug #860.
|
{% load djblets_utils %}
/*
* Initial state from the server. These should all be thought of as
* constants, not state.
*/
{% if not error %}
var gBugTrackerURL = "{{review_request.repository.bug_tracker}}";
var gReviewRequestPath = '{{review_request.get_absolute_url}}';
var gReviewRequestId = "{{review_request.id}}";
var gReviewRequestSummary = "{{review_request.summary|escapejs}}";
var gReviewPending = {% if review %}true{% else %}false{% endif %};
{% ifuserorperm review_request.submitter "reviews.can_edit_reviewrequest" %}
{% ifequal review_request.status 'P' %}
var gEditable = true;
{% endifequal %}
{% endifuserorperm %}
{% else %}{# error #}
var gReviewPending = false;
{% endif %}{# !error #}
var gUserURL = "{% url user user %}";
var gUserAuthenticated = {{user.is_authenticated|lower}};
{% if not user.is_anonymous %}
var gUserFullName = "{{user|user_displayname}}";
{% endif %}
|
{% load djblets_utils %}
/*
* Initial state from the server. These should all be thought of as
* constants, not state.
*/
{% if not error %}
var gBugTrackerURL = "{{review_request.repository.bug_tracker}}";
var gReviewRequestPath = '{{review_request.get_absolute_url}}';
var gReviewRequestId = "{{review_request.id}}";
var gReviewRequestSummary = "{{review_request.summary}}";
var gReviewPending = {% if review %}true{% else %}false{% endif %};
{% ifuserorperm review_request.submitter "reviews.can_edit_reviewrequest" %}
{% ifequal review_request.status 'P' %}
var gEditable = true;
{% endifequal %}
{% endifuserorperm %}
{% else %}{# error #}
var gReviewPending = false;
{% endif %}{# !error #}
var gUserURL = "{% url user user %}";
var gUserAuthenticated = {{user.is_authenticated|lower}};
{% if not user.is_anonymous %}
var gUserFullName = "{{user|user_displayname}}";
{% endif %}
|
Rename factory to match what it creates
|
"""
Factory that configures SQLAlchemy for PostgreSQL.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from microcosm.api import binding, defaults
@binding("postgres")
@defaults(
host="localhost",
port=5432,
password="secret",
)
def configure_sqlalchemy_engine(graph):
"""
Create the SQLAlchemy engine.
"""
# use different database name for testing
if graph.metadata.testing:
database_name = "{}_test_db".format(graph.metadata.name)
else:
database_name = "{}_db".format(graph.metadata.name)
# use the metadata name as the username
username = graph.metadata.name
password = graph.config.postgres.password or ""
uri = "postgresql://{}:{}@{}:{}/{}".format(
username,
password,
graph.config.postgres.host,
graph.config.postgres.port,
database_name,
)
return create_engine(uri)
def configure_sqlalchemy_sessionmaker(graph):
"""
Create the SQLAlchemy session class.
"""
return sessionmaker(bind=graph.postgres)
|
"""
Factory that configures SQLAlchemy for PostgreSQL.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from microcosm.api import binding, defaults
@binding("postgres")
@defaults(
host="localhost",
port=5432,
password="secret",
)
def configure_sqlalchemy_engine(graph):
"""
Create the SQLAlchemy engine.
"""
# use different database name for testing
if graph.metadata.testing:
database_name = "{}_test_db".format(graph.metadata.name)
else:
database_name = "{}_db".format(graph.metadata.name)
# use the metadata name as the username
username = graph.metadata.name
password = graph.config.postgres.password or ""
uri = "postgresql://{}:{}@{}:{}/{}".format(
username,
password,
graph.config.postgres.host,
graph.config.postgres.port,
database_name,
)
return create_engine(uri)
def configure_sqlalchemy_session(graph):
"""
Create the SQLAlchemy session class.
"""
return sessionmaker(bind=graph.postgres)
|
Make getPresentFields on Place more robust
Consider empty lists and empty strings not present. Leave zeroes alone
though.
|
import locations from '../core/locations';
import Model from '../base/model';
import {capfirst, makeAbsoluteURL} from '../utils';
export default class Place extends Model {
isStub() {
return this.data.is_stub;
}
isReference() {
return typeof this.data == 'number';
}
getName() {
return capfirst(this.data.full_name);
}
getPresentFields(...fields) {
return fields.filter(f => this.hasValue(f));
}
hasValue(field) {
const value = this.data[field];
const isDefined = value != null;
const hasLength = isDefined && value.hasOwnProperty('length');
return hasLength ? value.length > 0 : isDefined;
}
getLocation() {
return locations.get(this.data.location);
}
toJSONLD(app) {
const url = app.resolver.reverse('place', {id: this.data.id});
if (this.isReference()) {
return {
'@id': url,
}
}
const result = {
'@context': 'http://schema.org',
'@type': 'Place',
'@id': url,
name: this.getName(),
address: this.data.address,
}
if (!this.isStub()) {
result.url = makeAbsoluteURL(url);
}
if (this.data.url) {
result.sameAs = this.data.url;
}
return result;
}
}
|
import locations from '../core/locations';
import Model from '../base/model';
import {capfirst, makeAbsoluteURL} from '../utils';
export default class Place extends Model {
isStub() {
return this.data.is_stub;
}
isReference() {
return typeof this.data == 'number';
}
getName() {
return capfirst(this.data.full_name);
}
getPresentFields(...fields) {
return fields.filter(f => Boolean(this.data[f]))
}
getLocation() {
return locations.get(this.data.location);
}
toJSONLD(app) {
const url = app.resolver.reverse('place', {id: this.data.id});
if (this.isReference()) {
return {
'@id': url,
}
}
const result = {
'@context': 'http://schema.org',
'@type': 'Place',
'@id': url,
name: this.getName(),
address: this.data.address,
}
if (!this.isStub()) {
result.url = makeAbsoluteURL(url);
}
if (this.data.url) {
result.sameAs = this.data.url;
}
return result;
}
}
|
Remove dependency check done by Mopidy
|
from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
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(GMusicExtension, self).get_config_schema()
schema['username'] = config.String()
schema['password'] = config.Secret()
schema['deviceid'] = config.String(optional=True)
return schema
def get_backend_classes(self):
from .actor import GMusicBackend
return [GMusicBackend]
|
from __future__ import unicode_literals
import os
from mopidy import config, exceptions, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
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(GMusicExtension, self).get_config_schema()
schema['username'] = config.String()
schema['password'] = config.Secret()
schema['deviceid'] = config.String(optional=True)
return schema
def validate_environment(self):
try:
import gmusicapi # noqa
except ImportError as e:
raise exceptions.ExtensionError('gmusicapi library not found', e)
pass
def get_backend_classes(self):
from .actor import GMusicBackend
return [GMusicBackend]
|
Make vumi worker service available as vumi_worker and deprecate start_worker.
|
from zope.interface import implements
from twisted.application.service import IServiceMaker
from twisted.plugin import IPlugin
from vumi.start_worker import VumiService, StartWorkerOptions
# This create the service, runnable on command line with twistd
class VumiServiceMaker(object):
implements(IServiceMaker, IPlugin)
# the name of our plugin, this will be the subcommand for twistd
# e.g. $ twistd -n start_worker --option1= ...
tapname = "vumi_worker"
# description, also for twistd
description = "Start a Vumi worker"
# what command line options does this service expose
options = StartWorkerOptions
def makeService(self, options):
return VumiService(options)
class DeprecatedServiceMaker(VumiServiceMaker):
tapname = "start_worker"
description = "Deprecated copy of vumi_worker. Use vumi_worker instead."
# Announce the plugin as a service maker for twistd
# See: http://twistedmatrix.com/documents/current/core/howto/tap.html
serviceMaker = VumiServiceMaker()
deprecatedMaker = DeprecatedServiceMaker()
|
from zope.interface import implements
from twisted.application.service import IServiceMaker
from twisted.plugin import IPlugin
from vumi.start_worker import VumiService, StartWorkerOptions
# This create the service, runnable on command line with twistd
class VumiServiceMaker(object):
implements(IServiceMaker, IPlugin)
# the name of our plugin, this will be the subcommand for twistd
# e.g. $ twistd -n start_worker --option1= ...
tapname = "start_worker"
# description, also for twistd
description = "Start a Vumi worker"
# what command line options does this service expose
options = StartWorkerOptions
def makeService(self, options):
return VumiService(options)
# Announce the plugin as a service maker for twistd
# See: http://twistedmatrix.com/documents/current/core/howto/tap.html
serviceMaker = VumiServiceMaker()
|
[TASK] Update OutgoingPaymentProcessor to use new method.
|
var depositCallbackJob = require(__dirname+'/../jobs/deposit_completion_callback.js');
var OutgoingPayment = require(__dirname+'/outgoing_payment.js');
var gateway = require(__dirname+'/../../');
var RippleRestClient = require('ripple-rest-client');
function OutgoingPaymentProcessor(payment) {
this.outgoingPayment = new OutgoingPayment(payment);
}
OutgoingPaymentProcessor.prototype = {
processOutgoingPayment: function(callback) {
var self = this;
self.outgoingPayment.processOutgoingPayment(function(error, response) {
if (error) {
console.log('error', error);
setTimeout(callback, 2000);
} else {
callback();
}
});
}
};
var rippleRestClient = new RippleRestClient({
account: gateway.config.get('HOT_WALLET').address,
secret: ''
})
module.exports = OutgoingPaymentProcessor;
|
var depositCallbackJob = require(__dirname+'/../jobs/deposit_completion_callback.js');
var OutgoingPayment = require(__dirname+'/outgoing_payment.js');
var gateway = require(__dirname+'/../../');
var RippleRestClient = require('ripple-rest-client');
function OutgoingPaymentProcessor(payment) {
this.outgoingPayment = new OutgoingPayment(payment);
}
OutgoingPaymentProcessor.prototype = {
processOutgoingPayment: function(callback) {
var self = this;
self.outgoingPayment.sendToRippleRest(function(error, response) {
if (error) {
console.log('error', error);
setTimeout(callback, 2000);
} else {
callback();
}
});
}
};
var rippleRestClient = new RippleRestClient({
account: gateway.config.get('HOT_WALLET').address,
secret: ''
})
module.exports = OutgoingPaymentProcessor;
|
scripts: Fix typo in logging statement.
|
#!/usr/bin/env python3
import logging
import os
import sys
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ZULIP_PATH)
from scripts.lib.setup_path import setup_path
from scripts.lib.zulip_tools import DEPLOYMENTS_DIR, assert_not_running_as_root, parse_version_from
from version import ZULIP_VERSION as new_version
assert_not_running_as_root()
setup_path()
os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings"
import django
from django.db import connection
from django.db.migrations.loader import MigrationLoader
django.setup()
loader = MigrationLoader(connection)
missing = set(loader.applied_migrations)
for key, migration in loader.disk_migrations.items():
missing.discard(key)
missing.difference_update(migration.replaces)
if not missing:
sys.exit(0)
current_version = parse_version_from(os.path.join(DEPLOYMENTS_DIR, "current"))
logging.error(
"This is not an upgrade -- the current deployment (version %s) "
"contains %s database migrations which %s (version %s) does not.",
current_version,
len(missing),
ZULIP_PATH,
new_version,
)
sys.exit(1)
|
#!/usr/bin/env python3
import logging
import os
import sys
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ZULIP_PATH)
from scripts.lib.setup_path import setup_path
from scripts.lib.zulip_tools import DEPLOYMENTS_DIR, assert_not_running_as_root, parse_version_from
from version import ZULIP_VERSION as new_version
assert_not_running_as_root()
setup_path()
os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings"
import django
from django.db import connection
from django.db.migrations.loader import MigrationLoader
django.setup()
loader = MigrationLoader(connection)
missing = set(loader.applied_migrations)
for key, migration in loader.disk_migrations.items():
missing.discard(key)
missing.difference_update(migration.replaces)
if not missing:
sys.exit(0)
current_version = parse_version_from(os.path.join(DEPLOYMENTS_DIR, "current"))
logging.error(
"This is not an upgrade -- the current deployment (version %s) "
"contains database migrations which %s (version %s) does not.",
current_version,
len(missing),
ZULIP_PATH,
new_version,
)
sys.exit(1)
|
Add hash and eq methods to Token
|
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __hash__(self):
return hash((self.type, self.lexeme, self.literal))
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return (
self.type == other.type
and self.lexeme == other.lexeme
and self.literal == other.literal
)
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
|
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
|
Remove Agg backend in plot
Looks like applying the Agg backend in the plot_image function disables displaying images in Jupyter because the Agg backed is a non-GUI backend.
|
# Plot image to screen
import os
import cv2
import numpy as np
def plot_image(img, cmap=None):
"""Plot an image to the screen.
:param img: numpy.ndarray
:param cmap: str
:return:
"""
from matplotlib import pyplot as plt
dimensions = np.shape(img)
# If the image is color then OpenCV stores it as BGR, we plot it as RGB
if len(dimensions) == 3:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
elif cmap is None and len(dimensions) == 2:
plt.imshow(img, cmap="gray")
plt.show()
elif cmap is not None and len(dimensions) == 2:
plt.imshow(img, cmap=cmap)
plt.show()
|
# Plot image to screen
import os
import cv2
import numpy as np
def plot_image(img, cmap=None):
"""Plot an image to the screen.
:param img: numpy.ndarray
:param cmap: str
:return:
"""
import matplotlib
matplotlib.use('Agg', warn=False)
from matplotlib import pyplot as plt
dimensions = np.shape(img)
# If the image is color then OpenCV stores it as BGR, we plot it as RGB
if len(dimensions) == 3:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
elif cmap is None and len(dimensions) == 2:
plt.imshow(img, cmap="gray")
plt.show()
elif cmap is not None and len(dimensions) == 2:
plt.imshow(img, cmap=cmap)
plt.show()
|
Enhance generateTree function by adding edge condition for root
|
function generateTree(dataArr, root) {
let subTree, directChildren, subDataArr;
let { name, id, articlesCount } = root;
if (Object.keys(root).length === 0) {
return {};
}
if (dataArr.length === 0) {
return {
id,
name,
articlesCount,
subCategories: []
};
}
directChildren = dataArr.filter((node) => { return node.parentId === root.id; });
subDataArr = dataArr.filter((node) => { return node.parentId !== root.id; });
subTree = directChildren.map((node) => {
return generateTree(subDataArr, node);
});
return {
id,
name,
articlesCount,
subCategories: subTree
};
}
function transformToTree(dataArr) {
let root = dataArr.filter((node) => { return !node.parentId; })[0],
rest = dataArr.filter((node) => { return node.parentId; });
return generateTree(rest, root);
}
export { transformToTree };
|
function generateTree(dataArr, root) {
let subTree, directChildren, subDataArr;
let { name, id, articlesCount } = root;
if (dataArr.length === 0) {
return {
id,
name,
articlesCount,
subCategories: []
};
}
directChildren = dataArr.filter((node) => { return node.parentId === root.id; });
subDataArr = dataArr.filter((node) => { return node.parentId !== root.id; });
subTree = directChildren.map((node) => {
return generateTree(subDataArr, node);
});
return {
id,
name,
articlesCount,
subCategories: subTree
};
}
function transformToTree(dataArr) {
let root = dataArr.filter((node) => { return !node.parentId; })[0],
rest = dataArr.filter((node) => { return node.parentId; });
return generateTree(rest, root);
}
export { transformToTree };
|
Update version to 0.5.1 for Hyperion release
|
"""EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.5.1"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Create a logger, but by default, have it do nothing
_log = logging.getLogger('evelink')
_log.addHandler(NullHandler())
# Update the version number used in the user-agent
api._user_agent = 'evelink v%s' % __version__
__all__ = [
"account",
"api",
"char",
"constants",
"corp",
"eve",
"map",
"parsing",
"server",
]
|
"""EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.5.0"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Create a logger, but by default, have it do nothing
_log = logging.getLogger('evelink')
_log.addHandler(NullHandler())
# Update the version number used in the user-agent
api._user_agent = 'evelink v%s' % __version__
__all__ = [
"account",
"api",
"char",
"constants",
"corp",
"eve",
"map",
"parsing",
"server",
]
|
Update face detect example to take a path argument
|
from scannerpy import Database, DeviceType, Job
from scannerpy.stdlib import pipelines
import subprocess
import cv2
import sys
import os.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
import util
movie_path = util.download_video() if len(sys.argv) <= 1 else sys.argv[1]
print('Detecting faces in movie {}'.format(movie_path))
movie_name = os.path.splitext(os.path.basename(movie_path))[0]
with Database() as db:
print('Ingesting video into Scanner ...')
[input_table], _ = db.ingest_videos(
[(movie_name, movie_path)], force=True)
print('Detecting faces...')
bboxes_table = pipelines.detect_faces(
db, input_table, lambda t: t.all(),
movie_name + '_bboxes')
print('Drawing faces onto video...')
frame = input_table.as_op().all()
bboxes = bboxes_table.as_op().all()
out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes)
job = Job(columns = [out_frame], name = movie_name + '_bboxes_overlay')
out_table = db.run(job, force=True)
out_table.column('frame').save_mp4(movie_name + '_faces')
print('Successfully generated {:s}_faces.mp4'.format(movie_name))
|
from scannerpy import Database, DeviceType, Job
from scannerpy.stdlib import pipelines
import subprocess
import cv2
import sys
import os.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
import util
with Database() as db:
print('Ingesting video into Scanner ...')
[input_table], _ = db.ingest_videos(
[('example', util.download_video())], force=True)
print('Detecting faces...')
bboxes_table = pipelines.detect_faces(
db, input_table, lambda t: t.all(), 'example_bboxes')
print('Drawing faces onto video...')
frame = input_table.as_op().all()
bboxes = bboxes_table.as_op().all()
out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes)
job = Job(columns = [out_frame], name = 'example_bboxes_overlay')
out_table = db.run(job, force=True)
out_table.column('frame').save_mp4('example_faces')
print('Successfully generated example_faces.mp4')
|
Add ratelimit and help to autosummary.
Signed-off-by: Laura F. D <07c342be6e560e7f43842e2e21b774e61d85f047@veriny.tf>
|
# This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with curious. If not, see <http://www.gnu.org/licenses/>.
"""
Commands helpers.
.. currentmodule:: curious.commands
.. autosummary::
:toctree: commands
manager
context
decorators
plugin
utils
ratelimit
help
exc
converters
"""
from curious.commands.context import Context
from curious.commands.decorators import command, condition
from curious.commands.manager import CommandsManager
from curious.commands.plugin import Plugin
|
# This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with curious. If not, see <http://www.gnu.org/licenses/>.
"""
Commands helpers.
.. currentmodule:: curious.commands
.. autosummary::
:toctree: commands
manager
context
decorators
plugin
utils
exc
converters
"""
from curious.commands.context import Context
from curious.commands.decorators import command, condition
from curious.commands.manager import CommandsManager
from curious.commands.plugin import Plugin
|
Stop passing all store in each action
|
import isFunction from 'lodash/isFunction';
import { createAction as CA, handleActions as handle } from 'redux-actions';
// matches action names with reducers and returns an object to
// be used with handleActions
// passes all state as a third argument
export const bindActionsToReducers = (actions, reducerList) =>
Object.keys(actions).reduce((result, k) => {
const c = {};
const name = actions[k];
c[name] = (state, action) =>
reducerList.reduce((r, reducer) => {
const hasProperty = Object.prototype.hasOwnProperty.call(reducer, k);
if (!hasProperty || !isFunction(reducer[k])) return r;
return reducer[k](r, action);
}, state);
return { ...result, ...c };
}, {});
export const handleActions = (key, actions, reducers, state) =>
handle(bindActionsToReducers(actions, [reducers], state), state[key] || {});
// our own actioncreattor that can handle thunks
// fires the action as init
// and leaves resolve/reject to the thunk creator
export const createThunkAction = (name, thunkAction) => {
if (!thunkAction) return CA(name);
thunkAction.toString = () => name; // eslint-disable-line
return thunkAction;
};
|
import isFunction from 'lodash/isFunction';
import { createAction as CA, handleActions as handle } from 'redux-actions';
// matches action names with reducers and returns an object to
// be used with handleActions
// passes all state as a third argument
export const bindActionsToReducers = (actions, reducerList, appState) =>
Object.keys(actions).reduce((result, k) => {
const c = {};
const name = actions[k];
c[name] = (state, action) =>
reducerList.reduce((r, reducer) => {
if (!reducer.hasOwnProperty(k) || !isFunction(reducer[k])) return r;
return reducer[k](r, action, appState);
}, state);
return { ...result, ...c };
}, {});
export const handleActions = (key, actions, reducers, state) =>
handle(bindActionsToReducers(actions, [reducers], state), state[key] || {});
// our own actioncreattor that can handle thunks
// fires the action as init
// and leaves resolve/reject to the thunk creator
export const createThunkAction = (name, thunkAction) => {
if (!thunkAction) return CA(name);
thunkAction.toString = () => name;
return thunkAction;
};
|
Add success alert indicating registration began and to verify email.
|
core.controller('RegistrationController', function ($controller, $location, $scope, $timeout, AlertService, RestApi) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.registration = {
email: '',
token: ''
};
AlertService.create('auth/register');
AlertService.create('auth');
$scope.verifyEmail = function(email) {
RestApi.anonymousGet({
controller: 'auth',
method: 'register?email=' + email
}).then(function(data) {
$scope.registration.email = '';
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
if(typeof $location.search().token != 'undefined') {
$scope.registration.token = $location.search().token;
}
$scope.register = function() {
RestApi.anonymousGet({
'controller': 'auth',
'method': 'register',
'data': $scope.registration
}).then(function(data) {
$scope.registration = {
email: '',
token: ''
};
$location.path("/");
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
});
|
core.controller('RegistrationController', function ($controller, $location, $scope, $timeout, AlertService, RestApi) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.registration = {
email: '',
token: ''
};
AlertService.create('auth/register');
AlertService.create('auth');
$scope.verifyEmail = function(email) {
RestApi.anonymousGet({
controller: 'auth',
method: 'register?email=' + email
}).then(function(data) {
$scope.registration.email = '';
});
};
if(typeof $location.search().token != 'undefined') {
$scope.registration.token = $location.search().token;
}
$scope.register = function() {
RestApi.anonymousGet({
'controller': 'auth',
'method': 'register',
'data': $scope.registration
}).then(function(data) {
$scope.registration = {
email: '',
token: ''
};
$location.path("/");
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
});
|
Check that RootCtrl sets the default sort order
|
'use strict';
/* jasmine specs for controllers go here */
describe('RootCtrl', function(){
beforeEach(module('swiftBrowser.controllers'));
it('should list containers', inject(function($controller, $httpBackend) {
var containers = [
{"count": 10, "bytes": 1234, "name": "foo"},
{"count": 20, "bytes": 2345, "name": "bar"},
];
var scope = {};
$httpBackend.whenGET('/v1/AUTH_abc?format=json')
.respond(200, containers);
$controller('RootCtrl', {$scope: scope});
expect(scope.containers).toEqual([]);
$httpBackend.flush();
expect(scope.containers).toEqual(containers);
}));
it('should set sort order', inject(function($controller) {
var scope = {};
$controller('RootCtrl', {$scope: scope});
expect(scope.orderProp).toEqual('name');
}));
});
|
'use strict';
/* jasmine specs for controllers go here */
describe('RootCtrl', function(){
beforeEach(module('swiftBrowser.controllers'));
it('should list containers', inject(function($controller, $httpBackend) {
var containers = [
{"count": 10, "bytes": 1234, "name": "foo"},
{"count": 20, "bytes": 2345, "name": "bar"},
];
var scope = {};
$httpBackend.whenGET('/v1/AUTH_abc?format=json')
.respond(200, containers);
$controller('RootCtrl', {$scope: scope});
expect(scope.containers).toEqual([]);
$httpBackend.flush();
expect(scope.containers).toEqual(containers);
}));
});
|
Fix vote view to work with sharded Choice
|
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Choice, Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = Choice.objects.get(poll_id=p.pk, pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
Choice.objects.filter(pk=pk, poll_id=p.pk).update(votes=F('votes') + 1)
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
|
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Choice, Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
|
Return promise from snapshot builder to allow promise chain continuation
|
'use strict'
let connection = require('../../db/connection')
let logger = require('tracer').colorConsole()
/**
* Creates an aggregate object for a pipeline configuration snapshot.
*
* Includes:
* - initial variable values
* - stages
* - stage configuration values
*
* Ultimately, this is used to execute a pipeline and its stages.
*
* @param {int|string} pipelineId
* @param {function} callback
*/
module.exports = function snapshot(pipelineId, callback) {
let snapshot = {}
let promises = []
// Load pipeline
promises.push(new Promise((resolve, reject) => {
connection.first().where('id', pipelineId).from('pipeline_configs').then((pipeline) => {
snapshot.pipeline = pipeline
resolve()
}).catch(err => {
logger.error(err)
reject()
})
}))
// Load stages
promises.push(new Promise((resolve, reject) => {
connection.select().where('pipeline_config_id', pipelineId).orderBy('sort').from('pipeline_stage_configs').then((rows) => {
snapshot.stageConfigs = rows
resolve()
}).catch(err => {
logger.error(err)
reject()
})
}))
return Promise.all(promises).then(() => callback(snapshot))
}
|
'use strict'
let connection = require('../../db/connection')
let logger = require('tracer').colorConsole()
/**
* Creates an aggregate object for a pipeline configuration snapshot.
*
* Includes:
* - initial variable values
* - stages
* - stage configuration values
*
* Ultimately, this is used to execute a pipeline and its stages.
*
* @param {int|string} pipelineId
* @param {function} callback
*/
module.exports = function(pipelineId, callback) {
let snapshot = {}
let promises = []
// Load pipeline
promises.push(new Promise((resolve, reject) => {
connection.first().where('id', pipelineId).from('pipeline_configs').then((pipeline) => {
snapshot.pipeline = pipeline
resolve()
}).catch(err => {
logger.error(err)
reject()
})
}))
// Load stages
promises.push(new Promise((resolve, reject) => {
connection.select().where('pipeline_config_id', pipelineId).orderBy('sort').from('pipeline_stage_configs').then((rows) => {
snapshot.stageConfigs = rows
resolve()
}).catch(err => {
logger.error(err)
reject()
})
}))
Promise.all(promises).then(() => {
callback(snapshot)
})
}
|
Remove trailing ?> while investigating another page which is missing last_commit_id
|
<?php
#
# $Id: ports-deleted.php,v 1.2 2006-12-17 12:06:14 dan Exp $
#
# Copyright (c) 1998-2005 DVL Software Limited
#
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/databaselogin.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/getvalues.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports_page_list_ports.php');
$page = new freshports_page_list_ports();
$page->setDB($db);
$page->setTitle('Deleted ports');
$page->setDescription('These are the deleted ports');
$page->setStatus('D');
$page->setSQL('', $User->id);
$page->display();
|
<?php
#
# $Id: ports-deleted.php,v 1.2 2006-12-17 12:06:14 dan Exp $
#
# Copyright (c) 1998-2005 DVL Software Limited
#
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/databaselogin.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/getvalues.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports_page_list_ports.php');
$page = new freshports_page_list_ports();
$page->setDB($db);
$page->setTitle('Deleted ports');
$page->setDescription('These are the deleted ports');
$page->setStatus('D');
$page->setSQL('', $User->id);
$page->display();
?>
|
Make sure serverdate updates using the client clock.
|
// Small jQuery plugin to get dates from server.
(function($){
// Work out the difference between client time and server time.
var adjustment;
var init = function(){
if (!adjustment) {
$.ajax({
"url": "/course-signup/rest/user/current",
"type": "GET",
"async": false,
"dataType": "json",
"success": function(data){
var serverDate = data.date;
var clientDate = new Date().getTime();
adjustment = serverDate - clientDate;
}
});
}
};
$.serverDate = function(){
init();
return (new Date().getTime() + adjustment);
};
})(jQuery);
|
// Small jQuery plugin to get dates from server.
(function($){
var serverDate;
var init = function(){
if (!serverDate) {
$.ajax({
"url": "/course-signup/rest/user/current",
"type": "GET",
"async": false,
"dataType": "json",
"success": function(data){
serverDate = data.date;
}
});
}
};
$.serverDate = function(){
init();
return serverDate;
};
})(jQuery);
|
Break out items pending deprecation, remove double underscores
|
from fabric import api as _api
# Setup some default values.
_api.env.deploy_user = 'webapps'
from denim.paths import (cd_deploy, cd_application, deploy_path, application_path)
from denim import (scm, service, system, virtualenv, webserver)
from denim.decorators import deploy_env
# Pending deprecation
from denim.paths import (cd_package, package_path)
@_api.task(name="help")
def show_help():
"""
Help on common operations.
"""
from denim.environment import get_environments
import denim
print """
Common operations with Denim (%(version)s).
Provision server:
> fab {%(environments)s} init
Deploy (require a source control revision to be supplied. i.e. master):
> fab {%(environments)s} deploy:{revision}
Status of service:
> fab {%(environments)s} service.status
""" % {
'environments': '|'.join(get_environments()),
'version': denim.__version__,
}
@_api.task
def environments():
"""
Environments defined in fabfile.
"""
from denim.environment import get_environments
print 'Environments defined in fab file:'
print ', '.join(get_environments())
|
from fabric import api as __api
# Setup some default values.
__api.env.deploy_user = 'webapps'
from denim.paths import (cd_deploy, cd_package, deploy_path, package_path)
from denim import (scm, service, system, virtualenv, webserver)
from denim.decorators import deploy_env
@__api.task(name="help")
def show_help():
"""
Help on common operations.
"""
from denim.environment import get_environments
import denim
print """
Common operations with Denim (%(version)s).
Provision server:
> fab {%(environments)s} init
Deploy (require a source control revision to be supplied. i.e. master):
> fab {%(environments)s} deploy:{revision}
Status of service:
> fab {%(environments)s} service.status
""" % {
'environments': '|'.join(get_environments()),
'version': denim.__version__,
}
@__api.task
def environment():
"""
Environments defined in fabfile.
"""
from denim.environment import get_environments
print 'Environments defined in fab file:'
print ', '.join(get_environments())
|
Rename state to game in KerasPlayer
|
from keras.models import load_model
from . import Player
from ..utils import normalize_board, utility
class KerasPlayer(Player):
'''
Takes moves based on a Keras neural network model.
'''
name = 'Keras'
def __init__(self, filepath):
self.model = load_model(filepath)
def __str__(self):
return self.name
def __repr__(self):
return self.name
##########
# Player #
##########
def choose_move(self, game):
assert game.cur_player() == 0
best_move = None
best_value = -1000000
for move in game.legal_moves():
next_game = game.copy().make_move(move)
value = self.model.predict(normalize_board(next_game.board), batch_size=1)
assert value >= -1.0 and value <= 1.0
if value > best_value:
best_move = move
best_value = value
return best_move
|
from keras.models import load_model
from . import Player
from ..utils import normalize_board, utility
class KerasPlayer(Player):
'''
Takes moves based on a Keras neural network model.
'''
name = 'Keras'
def __init__(self, filepath):
self.model = load_model(filepath)
def __str__(self):
return self.name
def __repr__(self):
return self.name
##########
# Player #
##########
def choose_move(self, state):
assert state.cur_player() == 0
best_action = None
best_value = -1000000
for action in state.legal_moves():
s = state.copy()
s = s.make_move(action)
value = self.model.predict(normalize_board(s.board), batch_size=1)
assert value >= -1.0 and value <= 1.0
if value > best_value:
best_action = action
best_value = value
return best_action
|
Fix merge conflict - Remove TopNav story
|
/**
Copyright 2016 Autodesk,Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'hig.web/dist/hig.css';
import '../elements/basics/Button.story';
import '../elements/components/GlobalNav/TopNav/Search.story.js';
import '../elements/components/GlobalNav/TopNav/Profile.story';
import '../elements/components/GlobalNav/GlobalNav.story';
import '../elements/components/GlobalNav/TopNav/ProjectAccountSwitcher.story';
|
/**
Copyright 2016 Autodesk,Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'hig.web/dist/hig.css';
import '../elements/basics/Button.story';
import '../elements/components/GlobalNav/TopNav/Search.story.js';
import '../elements/components/GlobalNav/TopNav/Profile.story';
import '../elements/components/GlobalNav/GlobalNav.story';
import '../elements/components/GlobalNav/TopNav/TopNav.story';
import '../elements/components/GlobalNav/TopNav/ProjectAccountSwitcher.story';
|
Include versions tested on Travis in Trove classifiers
|
from setuptools import setup
import addict
SHORT='Addict is a dictionary whose items can be set using both attribute and item syntax.'
LONG=('Addict is a module that exposes a dictionary subclass that allows items to be set like attributes. '
'Values are gettable and settable using both attribute and item syntax. '
'For more info check out the README at \'github.com/mewwts/addict\'.')
setup(
name='addict',
version=addict.__version__,
packages=['addict'],
url='https://github.com/mewwts/addict',
author=addict.__author__,
author_email='mats@plysjbyen.net',
classifiers=(
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
),
description=SHORT,
long_description=LONG,
test_suite='test_addict'
)
|
from setuptools import setup
import addict
SHORT='Addict is a dictionary whose items can be set using both attribute and item syntax.'
LONG=('Addict is a module that exposes a dictionary subclass that allows items to be set like attributes. '
'Values are gettable and settable using both attribute and item syntax. '
'For more info check out the README at \'github.com/mewwts/addict\'.')
setup(
name='addict',
version=addict.__version__,
packages=['addict'],
url='https://github.com/mewwts/addict',
author=addict.__author__,
author_email='mats@plysjbyen.net',
classifiers=(
'Programming Language :: Python',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
),
description=SHORT,
long_description=LONG,
test_suite='test_addict'
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.