text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
[FIX] Use non ideal state component to show no challenges
|
import React from 'react';
import PropTypes from 'prop-types';
import { Spinner, NonIdealState } from '@blueprintjs/core';
import ChallengeCard from './ChallengeCard';
class ChallengeList extends React.Component {
static propTypes = {
challenges: PropTypes.array
}
render() {
const { challenges } = this.props;
if (challenges) {
if (challenges.length > 0) {
return challenges.map((challenge) => {
return <ChallengeCard key={challenge.key} order={challenge.order} challenge={challenge}/>;
})
.sort((a, b) => {
if (a.props.order > b.props.order) return 1;
else if (a.props.order < b.props.order) return -1;
else return 0;
});
}
else {
return (
<div style={{margin:'3rem 0'}}>
<NonIdealState title='No challenges' description='No challenges are currently available.' visual='map'/>
</div>
);
}
}
else {
return (
<div style={{textAlign:'center',margin:'3rem'}}>
<Spinner/>
</div>
);
}
}
}
export default ChallengeList;
|
import React from 'react';
import PropTypes from 'prop-types';
import { Spinner } from '@blueprintjs/core';
import ChallengeCard from './ChallengeCard';
class ChallengeList extends React.Component {
static propTypes = {
challenges: PropTypes.array
}
render() {
const { challenges } = this.props;
if (challenges) {
if (challenges.length > 0) {
return challenges.map((challenge) => {
return <ChallengeCard key={challenge.key} order={challenge.order} challenge={challenge}/>;
})
.sort((a, b) => {
if (a.props.order > b.props.order) return 1;
else if (a.props.order < b.props.order) return -1;
else return 0;
});
}
else {
return (
<div style={{textAlign:'center',margin:'3rem'}}>
<h4 className='pt-text-muted'>No challenges available.</h4>
</div>
);
}
}
else {
return (
<div style={{textAlign:'center',margin:'3rem'}}>
<Spinner/>
</div>
);
}
}
}
export default ChallengeList;
|
Make the interface clear when it comes to what happens when the container can't find the bean
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@389 3a8262b2-faa5-11dc-8610-ff947880b6b2
|
/*
* Copyright 2005 Joe Walker
*
* 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 uk.ltd.getahead.dwr;
/**
* A very basic IoC container
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public interface Container
{
/**
* Get an instance of a bean of a given type.
* @param id The type to get an instance of
* @return The object of the given type
* @throws IllegalArgumentException If the given id does not refer to a bean
*/
Object getBean(String id) throws IllegalArgumentException;
}
|
/*
* Copyright 2005 Joe Walker
*
* 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 uk.ltd.getahead.dwr;
/**
* A very basic IoC container
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public interface Container
{
/**
* Get an instance of a bean of a given type.
* @param id The type to get an instance of
* @return The object of the given type
*/
Object getBean(String id);
}
|
Add toggleIsCopied to UI actions
|
import * as types from '../constants/UIConstants'
export function selectKey(id) {
return { type: types.SELECT_KEY, id }
}
export function toggleComposer() {
return { type: types.TOGGLE_COMPOSER }
}
export function toggleGeneratingKey() {
return { type: types.TOGGLE_GENERATING_KEY }
}
export function toggleIsCopied() {
return { type: types.TOGGLE_IS_COPIED }
}
export function clearSelectedKeys() {
return { type: types.CLEAR_SELECTED_KEYS }
}
export function showComposerWithType(type) {
return { type: types.SHOW_COMPOSER_WITH_TYPE, data: type }
}
export function setOutput(output) {
console.log('inside ui actions', output)
return { type: types.SET_OUTPUT, output }
}
// export function setActiveAlias(keyId) {
// return async function (dispatch) {
// try {
// delete db.object.activeAlias
// await db.write()
// const activeAlias = await db('activeAlias').insert(keyId)
// return dispatch({ type: types.SET_ACTIVE_ALIAS, activeAlias })
// } catch (err) {
// console.log(err)
// }
// }
// }
|
import * as types from '../constants/UIConstants'
export function selectKey(id) {
return { type: types.SELECT_KEY, id }
}
export function toggleComposer() {
return { type: types.TOGGLE_COMPOSER }
}
export function toggleGeneratingKey() {
return { type: types.TOGGLE_GENERATING_KEY }
}
export function clearSelectedKeys() {
return { type: types.CLEAR_SELECTED_KEYS }
}
export function showComposerWithType(type) {
return { type: types.SHOW_COMPOSER_WITH_TYPE, data: type }
}
export function setOutput(output) {
console.log('inside ui actions', output)
return { type: types.SET_OUTPUT, output }
}
// export function setActiveAlias(keyId) {
// return async function (dispatch) {
// try {
// delete db.object.activeAlias
// await db.write()
// const activeAlias = await db('activeAlias').insert(keyId)
// return dispatch({ type: types.SET_ACTIVE_ALIAS, activeAlias })
// } catch (err) {
// console.log(err)
// }
// }
// }
|
Fix for 1.6 & 1.7
|
try:
from django.conf.urls.defaults import patterns, include, url
except ImportError:
from django.conf.urls import patterns, url, include
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}
),
url(r'^test/', 'test_app.views.test_index'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': os.path.join(
os.path.dirname(settings.__file__),
'static')}))
|
from django.conf.urls.defaults import patterns, include, url
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}
),
url(r'^test/', 'test_app.views.test_index'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': os.path.join(
os.path.dirname(settings.__file__),
'static')}))
|
Make signup just point to landing page
|
"""voteswap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import logout
from voteswap.views import index
from voteswap.views import landing_page
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url('^home/$', index, name='index'),
url('^$', landing_page, name='landing_page'),
url('^logout/$', logout, name='logout'),
url('^user/', include('users.urls', namespace='users')),
url('^signup/$', landing_page, name='signup'),
]
|
"""voteswap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import logout
from voteswap.views import index
from voteswap.views import landing_page
from voteswap.views import signup
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url('^home/$', index, name='index'),
url('^$', landing_page, name='landing_page'),
url('^logout/$', logout, name='logout'),
url('^user/', include('users.urls', namespace='users')),
url('^signup/$', signup, name='signup'),
]
|
Increase logwait to 10 instead of 5 secs
|
import os; # needed for opening/compiling file
import time; # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suitable for where the path is needed for initialisation."""
if allowCancel == True:
question = "Enter path of lilypond file (including file but without extension), or enter nothing to cancel: ";
else:
question = "Enter path of lilypond file (including file but without extension): ";
path = raw_input(question);
return path;
logwait = 10; # how long the program waits before opening the log
answer = "";
path = "";
while path == "":
path = getPath(False);
while answer.lower() != "e":
answer = raw_input("Enter Y or C to compile, E to exit, or P to change file path: ");
if answer.lower() == "y" or answer.lower() == "c":
os.startfile(path + ".ly");
print "Opening log file in " + str(logwait) + " seconds...";
time.sleep(logwait);
print "Log file: ==========================";
logfile = open(path + ".log", "r");
print logfile.read();
print "End of log file: ===================";
print "====================================";
elif answer.lower() == "p":
path = getPath();
|
import os; # needed for opening/compiling file
import time; # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suitable for where the path is needed for initialisation."""
if allowCancel == True:
question = "Enter path of lilypond file (including file but without extension), or enter nothing to cancel: ";
else:
question = "Enter path of lilypond file (including file but without extension): ";
path = raw_input(question);
return path;
logwait = 5; # how long the program waits before opening the log
answer = "";
path = "";
while path == "":
path = getPath(False);
while answer.lower() != "e":
answer = raw_input("Enter Y or C to compile, E to exit, or P to change file path: ");
if answer.lower() == "y" or answer.lower() == "c":
os.startfile(path + ".ly");
print "Opening log file in " + str(logwait) + " seconds...";
time.sleep(logwait);
print "Log file: ==========================";
logfile = open(path + ".log", "r");
print logfile.read();
print "End of log file: ===================";
print "====================================";
elif answer.lower() == "p":
path = getPath();
|
Add lxml and beautifulsoup dependencies
|
from setuptools import setup
setup(
name = "javasphinx",
packages = ["javasphinx"],
version = "0.9.8",
author = "Chris Thunes",
author_email = "cthunes@brewtab.com",
url = "http://github.com/bronto/javasphinx",
description = "Sphinx extension for documenting Java projects",
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries"
],
install_requires=["javalang>=0.9.2", "lxml", "beautifulsoup4"],
entry_points={
'console_scripts': [
'javasphinx-apidoc = javasphinx.apidoc:main'
]
},
long_description = """\
==========
javasphinx
==========
javasphinx is an extension to the Sphinx documentation system which adds support
for documenting Java projects. It includes a Java domain for writing
documentation manually and a javasphinx-apidoc utility which will automatically
generate API documentation from existing Javadoc markup.
"""
)
|
from setuptools import setup
setup(
name = "javasphinx",
packages = ["javasphinx"],
version = "0.9.8",
author = "Chris Thunes",
author_email = "cthunes@brewtab.com",
url = "http://github.com/bronto/javasphinx",
description = "Sphinx extension for documenting Java projects",
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries"
],
install_requires=["javalang>=0.9.2"],
entry_points={
'console_scripts': [
'javasphinx-apidoc = javasphinx.apidoc:main'
]
},
long_description = """\
==========
javasphinx
==========
javasphinx is an extension to the Sphinx documentation system which adds support
for documenting Java projects. It includes a Java domain for writing
documentation manually and a javasphinx-apidoc utility which will automatically
generate API documentation from existing Javadoc markup.
"""
)
|
[test] Fix tests for improved lazy loading
|
/*
* require-directory-test.js: Tests for `requireDir` and `requireDirLazy`
* methods.
*
* (C) 2011, Nodejitsu Inc.
* MIT LICENSE
*
*/
var assert = require('assert'),
path = require('path'),
vows = require('vows'),
macros = require('./helpers/macros'),
utile = require('../');
var requireFixtures = path.join(__dirname, 'fixtures', 'require-directory');
vows.describe('utile/require-directory').addBatch({
'When using utile': {
'the `requireDir()` function': {
topic: utile.requireDir(requireFixtures),
'should contain all wanted modules': macros.assertDirectoryRequired
},
'the `requireDirLazy()` function': {
topic: utile.requireDirLazy(requireFixtures),
'all properties should be getters': function (obj) {
assert.isObject(obj);
assert.isTrue(!!obj.__lookupGetter__('directory'));
assert.isTrue(!!obj.__lookupGetter__('helloWorld'));
},
'should contain all wanted modules': macros.assertDirectoryRequired
}
}
}).export(module);
|
/*
* require-directory-test.js: Tests for `requireDir` and `requireDirLazy`
* methods.
*
* (C) 2011, Nodejitsu Inc.
* MIT LICENSE
*
*/
var assert = require('assert'),
path = require('path'),
vows = require('vows'),
macros = require('./helpers/macros'),
utile = require('../');
var requireFixtures = path.join(__dirname, 'fixtures', 'require-directory');
vows.describe('utile/require-directory').addBatch({
'When using utile': {
'the `requireDir()` function': {
topic: utile.requireDir(requireFixtures),
'should contain all wanted modules': macros.assertDirectoryRequired
},
'the `requireDirLazy()` function': {
topic: utile.requireDirLazy(requireFixtures),
'should contain all wanted modules': macros.assertDirectoryRequired,
'all properties should be getters': function (obj) {
assert.isObject(obj);
assert.isTrue(!!obj.__lookupGetter__('directory'));
assert.isTrue(!!obj.__lookupGetter__('helloWorld'));
}
}
}
}).export(module);
|
Change the due datetime field for calculating late
|
<thead>
<tr>
<th>Item Name</th>
<th>Borrower Name</th>
<th>Borrower NetID</th>
<th>Pickup Time</th>
<th>Due Time</th>
</tr>
</thead>
<tbody>
<?php
include '../config.php';
include '../db.php';
$fdb = new FlatFileDB($db_filename, $table_sep, $cell_sep);
foreach ($fdb->getTable($loans_table) as $rownum => $row) {
$class = '';
if (date($row[4]) < date($dt_fmt)) {
$class = ' class="late"';
} elseif ($rownum % 2 == 0) {
$class = ' class="alt"';
}
echo '<tr' . $class . '>';
echo '<td class="item_name">' . $row[0] . '</td>';
echo '<td class="borrower_name">' . $row[1] . '</td>';
echo '<td class="borrower_netid">' . $row[2] . '</td>';
echo '<td class="pickup_datetime">' . $row[3] . '</td>';
echo '<td class="due_datetime">' . $row[4] . '</td>';
echo '</tr>';
$row++;
}
?>
</tbody>
|
<thead>
<tr>
<th>Item Name</th>
<th>Borrower Name</th>
<th>Borrower NetID</th>
<th>Pickup Time</th>
<th>Due Time</th>
</tr>
</thead>
<tbody>
<?php
include '../config.php';
include '../db.php';
$fdb = new FlatFileDB($db_filename, $table_sep, $cell_sep);
foreach ($fdb->getTable($loans_table) as $rownum => $row) {
$class = '';
if (date($row[5]) < date($dt_fmt)) {
$class = ' class="late"';
} elseif ($rownum % 2 == 0) {
$class = ' class="alt"';
}
echo '<tr' . $class . '>';
echo '<td class="item_name">' . $row[0] . '</td>';
echo '<td class="borrower_name">' . $row[1] . '</td>';
echo '<td class="borrower_netid">' . $row[2] . '</td>';
echo '<td class="pickup_datetime">' . $row[3] . '</td>';
echo '<td class="due_datetime">' . $row[4] . '</td>';
echo '</tr>';
$row++;
}
?>
</tbody>
|
Support user config. Located at phoxy_config function
|
<?php
error_reporting(E_ALL); ini_set('display_errors', '1');
include_once('connect.php');
if (!count($_GET))
{
include_once('index.html');
exit();
}
if (!function_exists("phoxy_conf"))
include_once("config.php");
function phoxy_default_conf()
{
return array(
"ip" => $_SERVER['REMOTE_ADDR'],
"site" => "http://localhost/phoxy",
"ejs_dir" => "ejs",
"js_dir" => "js",
"api_dir" => "api",
"get_api_param" => "api",
);
}
$get_param = phoxy_conf()["get_api_param"];
if (isset($_GET[$get_param]))
{
$file = $_GET[$get_param];
if ($file == 'htaccess')
exit('Rewrite engine work SUCCESS');
if (strpos($file, "/") > -1)
list($file, $func) = explode("/", $file);
if (!isset($func) || !$func)
$func = 'Reserve';
session_start();
include_once('include.php');
$a = IncludeModule(phoxy_conf()["api_dir"], $file);
$f = $func;
echo $a->$f();
}
|
<?php
error_reporting(E_ALL); ini_set('display_errors', '1');
include_once('connect.php');
if (!count($_GET))
{
include_once('index.html');
exit();
}
function conf()
{
return array(
"ip" => $_SERVER['REMOTE_ADDR'],
"site" => "http://localhost/phoxy/"
);
}
if (isset($_GET['api']))
{
$file = $_GET['api'];
if ($file == 'htaccess')
exit('Rewrite engine work SUCCESS');
if (strpos($file, "/") > -1)
list($file, $func) = explode("/", $_GET['api']);
if (!isset($func) || !$func)
$func = 'Reserve';
session_start();
include_once('include.php');
$a = IncludeModule('api', $file);
$f = $func;
echo $a->$f();
}
|
Use the release version rather than public version for GitHub links
|
#!/usr/bin/env python3
from importlib.metadata import version
from packaging.version import parse
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.extlinks",
"sphinx_autodoc_typehints",
"sphinxcontrib.asyncio",
"sphinx_tabs.tabs",
]
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "asphalt-web"
author = "Alex Grönholm"
copyright = "2022, " + author
v = parse(version(project))
version = v.base_version
release = v.public
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
highlight_language = "python3"
todo_include_todos = False
autodoc_inherit_docstrings = False
html_theme = "sphinx_rtd_theme"
html_static_path = ["_static"]
htmlhelp_basename = project.replace("-", "") + "doc"
extlinks = {
"github": (
f"https://github.com/asphalt-framework/{project}/tree/{release}/%s",
None,
)
}
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"asphalt": ("https://asphalt.readthedocs.io/en/latest/", None),
}
|
#!/usr/bin/env python3
from importlib.metadata import version
from packaging.version import parse
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.extlinks",
"sphinx_autodoc_typehints",
"sphinxcontrib.asyncio",
"sphinx_tabs.tabs",
]
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "asphalt-web"
author = "Alex Grönholm"
copyright = "2022, " + author
v = parse(version(project))
version = v.base_version
release = v.public
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
highlight_language = "python3"
todo_include_todos = False
autodoc_inherit_docstrings = False
html_theme = "sphinx_rtd_theme"
html_static_path = ["_static"]
htmlhelp_basename = project.replace("-", "") + "doc"
extlinks = {
"github": (
f"https://github.com/asphalt-framework/{project}/tree/{version}/%s",
None,
)
}
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"asphalt": ("https://asphalt.readthedocs.io/en/latest/", None),
}
|
Use stream.write() instead of console.log()
|
'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || { info: 'cyan' };
opts.stream = opts.stream || process.stderr;
if (res.headers['content-length']) {
var msg = chalk[opts.info](' downloading') + ' : ' + url;
var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas';
var len = parseInt(res.headers['content-length'], 10);
var bar = new ProgressBar(info, assign({
complete: '=',
incomplete: ' ',
width: 20,
total: len
}, opts));
opts.stream.write(msg);
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
opts.stream.write('\n');
cb();
});
}
};
};
|
'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || { info: 'cyan' };
if (res.headers['content-length']) {
var msg = chalk[opts.info](' downloading') + ' : ' + url;
var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas';
var len = parseInt(res.headers['content-length'], 10);
var bar = new ProgressBar(info, assign({
complete: '=',
incomplete: ' ',
width: 20,
total: len
}, opts));
console.log(msg);
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
console.log('\n');
cb();
});
}
};
};
|
Make the proxy server listen port configurable
|
package main
import (
"net"
"os"
"flag"
"strconv"
)
func handleConnection(conn net.Conn) {
connection := NewConnection(conn)
defer connection.Close()
connection.Handle()
}
func acceptedConnsChannel(listener net.Listener) chan net.Conn {
channel := make(chan net.Conn)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
logger.Info.Println("Could not accept socket:", err)
continue
}
channel <- conn
}
}()
return channel
}
func main() {
InitLogger()
portPtr := flag.Int("port", 25000, "listen port")
flag.Parse()
logger.Info.Println("Prepare for takeoff...")
listenOn := ":" + strconv.Itoa(*portPtr)
server, err := net.Listen("tcp", listenOn)
if err != nil {
logger.Fatal.Println("Could not start server:", err)
os.Exit(1)
}
logger.Info.Println("Server started on", listenOn)
acceptedConnsChannel := acceptedConnsChannel(server)
for {
go handleConnection(<-acceptedConnsChannel)
}
}
|
package main
import (
"net"
"os"
)
func handleConnection(conn net.Conn) {
connection := NewConnection(conn)
defer connection.Close()
connection.Handle()
}
func acceptedConnsChannel(listener net.Listener) chan net.Conn {
channel := make(chan net.Conn)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
logger.Info.Println("Could not accept socket:", err)
continue
}
channel <- conn
}
}()
return channel
}
func main() {
InitLogger()
logger.Info.Println("Prepare for takeoff...")
server, err := net.Listen("tcp", ":25000")
if err != nil {
logger.Fatal.Println("Could not start server:", err)
os.Exit(1)
}
logger.Info.Println("Server started on :25000")
acceptedConnsChannel := acceptedConnsChannel(server)
for {
go handleConnection(<-acceptedConnsChannel)
}
}
|
Fix broken GithubAPIClient constructor args
|
from __future__ import print_function
from getpass import getpass, _raw_input
import logging
import sys
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import envkey, GithubAPIClient
log = logging.getLogger(__name__)
parser = ArghParser()
def login_if_needed(gh, scopes):
if gh.logged_in:
log.info("Already logged in")
return
print("Please log into GitHub ({0})".format(gh.nickname or "public"),
file=sys.stderr)
username = _raw_input("Username: ")
password = getpass("Password: ")
gh.login(username, password, scopes=scopes)
@arg('-s', '--scope',
default=None,
action='append',
help='GitHub auth scopes to request')
@arg('github',
nargs='?',
help='GitHub instance nickname (e.g "enterprise")')
def login(args):
"""
Log into a GitHub instance, and print the resulting OAuth token.
"""
with cli.catch_api_errors():
client = GithubAPIClient(nickname=args.github)
login_if_needed(client, args.scope)
oauth_token_key = envkey(client.nickname, 'oauth_token')
print("export {0}='{1}'".format(oauth_token_key, client.token))
parser.set_default_command(login)
def main():
parser.dispatch()
if __name__ == '__main__':
main()
|
from __future__ import print_function
from getpass import getpass, _raw_input
import logging
import sys
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import envkey, GithubAPIClient
log = logging.getLogger(__name__)
parser = ArghParser()
def login_if_needed(gh, scopes):
if gh.logged_in:
log.info("Already logged in")
return
print("Please log into GitHub ({0})".format(gh.nickname or "public"),
file=sys.stderr)
username = _raw_input("Username: ")
password = getpass("Password: ")
gh.login(username, password, scopes=scopes)
@arg('-s', '--scope',
default=None,
action='append',
help='GitHub auth scopes to request')
@arg('github',
nargs='?',
help='GitHub instance nickname (e.g "enterprise")')
def login(args):
"""
Log into a GitHub instance, and print the resulting OAuth token.
"""
with cli.catch_api_errors():
client = GithubAPIClient(args.github)
login_if_needed(client, args.scope)
oauth_token_key = envkey(client.nickname, 'oauth_token')
print("export {0}='{1}'".format(oauth_token_key, client.token))
parser.set_default_command(login)
def main():
parser.dispatch()
if __name__ == '__main__':
main()
|
Rename node stream to avoid confusion with web streams
|
const Readable = require('readable-stream')
module.exports = function (snapshot) {
return checkCache.bind(null, snapshot._namespace)
}
function checkCache (namespace, req, rsp) {
if (rsp.createReadStream) return
const url = new URL(req.url)
return global.caches.open('planktos-' + namespace)
.then(c => c.match(url.pathname))
.then(cached => {
if (!cached) return
rsp.headers.set('Content-Type', cached.headers.get('Content-Type')) // TODO what if the cached header is not set ?
return cached.arrayBuffer()
})
.then(arrayBuffer => {
if (!arrayBuffer) return
const s = new Readable()
s._read = function noop () {}
s.push(Buffer.from(arrayBuffer))
s.push(null)
rsp.createReadStream = () => s
rsp.status = 200
rsp.statusText = 'OK'
rsp.headers.set('Content-Length', arrayBuffer.length)
})
}
|
const ReadableStream = require('readable-stream')
module.exports = function (snapshot) {
return checkCache.bind(null, snapshot._namespace)
}
function checkCache (namespace, req, rsp) {
if (rsp.createReadStream) return
const url = new URL(req.url)
return global.caches.open('planktos-' + namespace)
.then(c => c.match(url.pathname))
.then(cached => {
if (!cached) return
rsp.headers.set('Content-Type', cached.headers.get('Content-Type')) // TODO what if the cached header is not set ?
return cached.arrayBuffer()
})
.then(arrayBuffer => {
if (!arrayBuffer) return
const s = new ReadableStream()
s._read = function noop () {}
s.push(Buffer.from(arrayBuffer))
s.push(null)
rsp.createReadStream = () => s
rsp.status = 200
rsp.statusText = 'OK'
rsp.headers.set('Content-Length', arrayBuffer.length)
})
}
|
Fix py/capnp build for python 3.7
|
from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
|
from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
|
Update javadoc to cover desugaring
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=258431740
|
/*
* Copyright 2016 The Error Prone Authors.
*
* 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.google.errorprone.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
/**
* Annotation for constructors of AutoCloseables or methods that return an AutoCloseable and require
* that the resource is closed.
*
* <p>This is enforced by checking that invocations occur within the resource variable initializer
* of a try-with-resources statement, which guarantees that the resource is always closed. The
* analysis may be improved in the future to recognize other patterns where the resource will always
* be closed.
*
* <p>Note that Android SDK versions prior to 19 do not support try-with-resources, so the
* annotation should be avoided on APIs that may be used on Android, unless desugaring is used.
*/
@Documented
@Target({CONSTRUCTOR, METHOD})
public @interface MustBeClosed {}
|
/*
* Copyright 2016 The Error Prone Authors.
*
* 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.google.errorprone.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
/**
* Annotation for constructors of AutoCloseables or methods that return an AutoCloseable and require
* that the resource is closed.
*
* <p>This is enforced by checking that invocations occur within the resource variable initializer
* of a try-with-resources statement, which guarantees that the resource is always closed. The
* analysis may be improved in the future to recognize other patterns where the resource will always
* be closed.
*
* <p>Note that Android SDK versions prior to 19 do not support try-with-resources, so the
* annotation should be avoided on APIs that may be used on Android.
*/
@Documented
@Target({CONSTRUCTOR, METHOD})
public @interface MustBeClosed {}
|
Rework node-server-generator to use new util.
|
const generators = require('yeoman-generator');
const util = require('../../util/util.js');
const prompts = util.prompts.nodeServer;
const generator = generators.Base.extend({
// Cannot use arrow notation due to this object not referencing the correct object.
constructor: function () {
generators.Base.apply(this, arguments);
util.generator.constructor.call(this, prompts);
},
initializing() {
const done = this.async();
util.generator.initializing.call(this, done);
},
prompting() {
return util.generator.prompting.call(this, prompts);
},
composition() {
this.options.nodeServer = true;
this.composeWith('kk578:node', { options: this.options });
},
writing() {
this.template('npm-shrinkwrap.json', 'npm-shrinkwrap.json', this.options);
this.copy('.env');
this.copy('server/server.js');
this.copy('server/start.js');
this.copy('server/configs/logs.js');
this.copy('server/configs/setup.js');
this.copy('server/configs/router.js');
this.copy('server/configs/browser-sync.js');
this.copy('server/routes/static.js');
this.copy('server/routes/404.dev.js');
}
});
module.exports = generator;
|
const generators = require('yeoman-generator');
const util = require('../util.js');
const generator = generators.Base.extend({
// Cannot use arrow notation due to this object not referencing the correct object.
constructor: function () {
generators.Base.apply(this, arguments);
util.generatorConstructor.call(this, util.prompts.nodeServer);
},
initializing() {
const done = this.async();
util.generatorInitializing.call(this, done);
},
prompting() {
return util.generatorPrompting.call(this, util.prompts.nodeServer);
},
composition() {
this.options.nodeServer = true;
this.composeWith('kk578:node', { options: this.options });
},
writing() {
this.template('npm-shrinkwrap.json', 'npm-shrinkwrap.json', this.options);
this.copy('.env');
this.copy('server/server.js');
this.copy('server/start.js');
this.copy('server/configs/logs.js');
this.copy('server/configs/setup.js');
this.copy('server/configs/router.js');
this.copy('server/configs/browser-sync.js');
this.copy('server/routes/static.js');
this.copy('server/routes/404.dev.js');
}
});
module.exports = generator;
|
Add a new passing test for invalid week numbers.
|
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
@given(integers(MINYEAR, MAXYEAR), integers(None, 0), integers(1, 7))
def test_weeks_smaller_than_1_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
|
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
|
[Bugfix] Use memo parameter in TapBailout.copy
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
exc.py
~~~~~~
Exceptions for TAP file handling.
(c) BSD 3-clause.
"""
from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import os
import sys
__all__ = ['TapParseError', 'TapMissingPlan',
'TapInvalidNumbering', 'TapBailout']
class TapParseError(Exception):
pass
class TapMissingPlan(TapParseError):
pass
class TapInvalidNumbering(TapParseError):
pass
class TapBailout(Exception):
is_testcase = False
is_bailout = True
encoding = sys.stdout.encoding
def __init__(self, *args, **kwargs):
super(TapBailout, self).__init__(*args, **kwargs)
self.data = []
def __str__(self):
return unicode(self).encode(self.encoding or 'utf-8')
def __unicode__(self):
return u'Bail out! {}{}{}'.format(self.message, os.linesep,
os.linesep.join(self.data))
def copy(self, memo=None):
inst = TapBailout(memo or self.message)
inst.data = self.data
return inst
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
exc.py
~~~~~~
Exceptions for TAP file handling.
(c) BSD 3-clause.
"""
from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import os
import sys
__all__ = ['TapParseError', 'TapMissingPlan',
'TapInvalidNumbering', 'TapBailout']
class TapParseError(Exception):
pass
class TapMissingPlan(TapParseError):
pass
class TapInvalidNumbering(TapParseError):
pass
class TapBailout(Exception):
is_testcase = False
is_bailout = True
encoding = sys.stdout.encoding
def __init__(self, *args, **kwargs):
super(TapBailout, self).__init__(*args, **kwargs)
self.data = []
def __str__(self):
return unicode(self).encode(self.encoding or 'utf-8')
def __unicode__(self):
return u'Bail out! {}{}{}'.format(self.message, os.linesep,
os.linesep.join(self.data))
def copy(self, memo=None):
inst = TapBailout(self.message)
inst.data = self.data
return inst
|
Create a compound index for status and type
|
module.exports = [
{
collection: 'entries',
spec: { locationId: 1 },
options: {},
},
{
collection: 'events',
spec: { time: 1 },
options: {},
},
{
collection: 'events',
spec: { locationId: 1 },
options: {},
},
{
collection: 'locations',
spec: { geom: '2dsphere' },
options: {},
},
{
collection: 'locations',
spec: { layer: 1 },
options: {},
},
{
collection: 'locations',
spec: { status: 1, type: 1 },
options: {},
},
{
// Text index
collection: 'locations',
spec: {
text1: 'text', // primary
text2: 'text', // secondary
},
options: {
weights: {
text1: 3,
text2: 1,
},
name: 'TextIndex',
},
},
{
collection: 'users',
spec: { email: 1 },
options: { unique: true },
},
{
collection: 'users',
spec: { name: 1 },
options: { unique: true },
},
];
|
module.exports = [
{
collection: 'entries',
spec: { locationId: 1 },
options: {},
},
{
collection: 'events',
spec: { time: 1 },
options: {},
},
{
collection: 'events',
spec: { locationId: 1 },
options: {},
},
{
collection: 'locations',
spec: { geom: '2dsphere' },
options: {},
},
{
collection: 'locations',
spec: { layer: 1 },
options: {},
},
{
// Text index
collection: 'locations',
spec: {
text1: 'text', // primary
text2: 'text', // secondary
},
options: {
weights: {
text1: 3,
text2: 1,
},
name: 'TextIndex',
},
},
{
collection: 'users',
spec: { email: 1 },
options: { unique: true },
},
{
collection: 'users',
spec: { name: 1 },
options: { unique: true },
},
];
|
Use fmt.Print instead of the print builtin in stripReader
|
// Package deansify strips ANSI escape codes from either a named file or
// from STDIN.
package deansify
import (
"bufio"
"fmt"
"io"
"log"
"os"
"regexp"
)
var version = "0.0.2"
var ansiRegexp = regexp.MustCompile("\x1b[^m]*m")
func stripAnsi(s string) string {
return ansiRegexp.ReplaceAllLiteralString(s, "")
}
func stripReader(reader *bufio.Reader) {
for {
line, err := reader.ReadString('\n')
if err == nil || err == io.EOF {
fmt.Print(stripAnsi(line))
}
if err != nil {
break
}
}
}
// StripStdin reads text from SDTIN and emits that same text minus any
// ANSI escape codes.
func StripStdin() {
reader := bufio.NewReader(os.Stdin)
stripReader(reader)
}
// StripFile reads text from the file located at fileName and emits that same
// text minus any ANSI escape codes.
func StripFile(fileName string) {
file, err := os.Open(fileName)
if err != nil {
log.Fatalf("Error opening file %s, %v", fileName, err)
}
reader := bufio.NewReader(file)
stripReader(reader)
}
|
// Package deansify strips ANSI escape codes from either a named file or
// from STDIN.
package deansify
import (
"bufio"
"io"
"log"
"os"
"regexp"
)
var version = "0.0.2"
var ansiRegexp = regexp.MustCompile("\x1b[^m]*m")
func stripAnsi(s string) string {
return ansiRegexp.ReplaceAllLiteralString(s, "")
}
func stripReader(reader *bufio.Reader) {
for {
line, err := reader.ReadString('\n')
if err == nil || err == io.EOF {
print(stripAnsi(line))
}
if err != nil {
break
}
}
}
// StripStdin reads text from SDTIN and emits that same text minus any
// ANSI escape codes.
func StripStdin() {
reader := bufio.NewReader(os.Stdin)
stripReader(reader)
}
// StripFile reads text from the file located at fileName and emits that same
// text minus any ANSI escape codes.
func StripFile(fileName string) {
file, err := os.Open(fileName)
if err != nil {
log.Fatalf("Error opening file %s, %v", fileName, err)
}
reader := bufio.NewReader(file)
stripReader(reader)
}
|
Change development status to Alpha
It better reflects the project's immature state.
|
#!/usr/bin/env python2
from distutils.core import setup
setup(name='visram',
version='0.1.0',
description='Graphical RAM/CPU Visualizer',
license='MIT',
author='Matthew Pfeiffer',
author_email='spferical@gmail.com',
url='http://github.com/Spferical/visram',
packages=['visram', 'visram.test'],
scripts=['bin/visram'],
platforms=['any'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: X11 Applications',
'Environment :: MacOS X :: Cocoa',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 2 :: Only',
'Topic :: System :: Monitoring',
],
)
|
#!/usr/bin/env python2
from distutils.core import setup
setup(name='visram',
version='0.1.0',
description='Graphical RAM/CPU Visualizer',
license='MIT',
author='Matthew Pfeiffer',
author_email='spferical@gmail.com',
url='http://github.com/Spferical/visram',
packages=['visram', 'visram.test'],
scripts=['bin/visram'],
platforms=['any'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: X11 Applications',
'Environment :: MacOS X :: Cocoa',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 2 :: Only',
'Topic :: System :: Monitoring',
],
)
|
Rename image sizes, add store image size.
|
<?php
function brewtah_theme_support() {
// Add language support
load_theme_textdomain('brewtah', get_template_directory() . '/languages');
// Add menu support
add_theme_support('menus');
// Add post thumbnail support: http://codex.wordpress.org/Post_Thumbnails
add_theme_support('post-thumbnails');
set_post_thumbnail_size(150, 150, false);
// rss thingy
add_theme_support('automatic-feed-links');
// Add post formarts support: http://codex.wordpress.org/Post_Formats
add_theme_support('post-formats', array('aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat'));
// Add image sizes
add_image_size( 'archive-image', 100, 100, true );
add_image_size( 'sidebar-image', 50, 50, true );
add_image_size( 'store-image', 250, 188, true );
}
add_action('after_setup_theme', 'brewtah_theme_support');
?>
|
<?php
function brewtah_theme_support() {
// Add language support
load_theme_textdomain('brewtah', get_template_directory() . '/languages');
// Add menu support
add_theme_support('menus');
// Add post thumbnail support: http://codex.wordpress.org/Post_Thumbnails
add_theme_support('post-thumbnails');
set_post_thumbnail_size(150, 150, false);
// rss thingy
add_theme_support('automatic-feed-links');
// Add post formarts support: http://codex.wordpress.org/Post_Formats
add_theme_support('post-formats', array('aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat'));
// Add image sizes
add_image_size( 'beer-image', 100, 100, true );
add_image_size( 'beer-sidebar-image', 50, 50, true );
}
add_action('after_setup_theme', 'brewtah_theme_support');
?>
|
Add the test task dependency back to the default gulp task
|
'use strict';
var gulp = require('gulp');
var options = {
name: 'ec2prices',
dependantFiles: ['node_modules/babel/browser-polyfill.js'],
mainFiles: [
'app/scripts/app.es6',
'app/scripts/**/!(*.spec|*.mock).{js,es6}'
],
templateFiles: ['app/scripts/**/*.htm{,l}'],
specFiles: ['app/scripts/**/*.{spec,mock}.es6'],
views: {
src: ['app/views/{,*/}*.htm{,l}'],
base: 'app/views/'
},
normalFiles: ['app/instances.json'],
buildDir: 'build',
version: false,
};
require('./gulp/copy.js')(options);
require('./gulp/css.js')(options);
require('./gulp/deploy.js')(options);
require('./gulp/html.js')(options);
require('./gulp/js.js')(options);
require('./gulp/lint.js')(options);
require('./gulp/serve.js')(options);
require('./gulp/tests.js')(options);
gulp.task('default', ['lint', 'test', 'js', 'html', 'copy', 'css']);
|
'use strict';
var gulp = require('gulp');
var options = {
name: 'ec2prices',
dependantFiles: ['node_modules/babel/browser-polyfill.js'],
mainFiles: [
'app/scripts/app.es6',
'app/scripts/**/!(*.spec|*.mock).{js,es6}'
],
templateFiles: ['app/scripts/**/*.htm{,l}'],
specFiles: ['app/scripts/**/*.{spec,mock}.es6'],
views: {
src: ['app/views/{,*/}*.htm{,l}'],
base: 'app/views/'
},
normalFiles: ['app/instances.json'],
buildDir: 'build',
version: false,
};
require('./gulp/copy.js')(options);
require('./gulp/css.js')(options);
require('./gulp/deploy.js')(options);
require('./gulp/html.js')(options);
require('./gulp/js.js')(options);
require('./gulp/lint.js')(options);
require('./gulp/serve.js')(options);
require('./gulp/tests.js')(options);
gulp.task('default', ['lint', 'js', 'html', 'copy', 'css']);
|
Add commment to stop recorder once done with it
|
package vcr_test
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/dnaeon/go-vcr/recorder"
)
func TestSimple(t *testing.T) {
// Start our recorder
r, err := recorder.New("fixtures/golang-org")
if err != nil {
t.Fatal(err)
}
defer r.Stop() // Make sure recorder is stopped once done with it
// Create an HTTP client and inject our transport
client := &http.Client{
Transport: r.Transport, // Inject our transport!
}
url := "http://golang.org/"
resp, err := client.Get(url)
if err != nil {
t.Fatalf("Failed to get url %s: %s", url, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response body: %s", err)
}
wantTitle := "<title>The Go Programming Language</title>"
bodyContent := string(body)
if !strings.Contains(bodyContent, wantTitle) {
t.Errorf("Title %s not found in response", wantTitle)
}
}
|
package vcr_test
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/dnaeon/go-vcr/recorder"
)
func TestSimple(t *testing.T) {
// Start our recorder
r, err := recorder.New("fixtures/golang-org")
if err != nil {
t.Fatal(err)
}
defer r.Stop()
// Create an HTTP client and inject our transport
client := &http.Client{
Transport: r.Transport, // Inject our transport!
}
url := "http://golang.org/"
resp, err := client.Get(url)
if err != nil {
t.Fatalf("Failed to get url %s: %s", url, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response body: %s", err)
}
wantTitle := "<title>The Go Programming Language</title>"
bodyContent := string(body)
if !strings.Contains(bodyContent, wantTitle) {
t.Errorf("Title %s not found in response", wantTitle)
}
}
|
Mark all descendants of Defs as seen after a draw
When adding clipping paths in a def and changing properties of that clipping path (or its descendants), redraw is triggered only once as updates are never marked as seen.
This change makes sure to call `markUpdateSeen` on all descendants of the Defs node on a `draw`.
|
/**
* Copyright (c) 2015-present, Horcrux.
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.horcrux.svg;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Shadow node for virtual RNSVGPath view
*/
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {
@Override
public void draw(Canvas canvas, Paint paint, float opacity) {
traverseChildren(new NodeRunnable() {
public boolean run(RNSVGVirtualNode node) {
node.saveDefinition();
return true;
}
});
traverseChildren(new NodeRunnable() {
public boolean run(RNSVGVirtualNode node) {
node.markUpdateSeen();
node.traverseChildren(this);
return true;
}
});
}
}
|
/**
* Copyright (c) 2015-present, Horcrux.
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.horcrux.svg;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Shadow node for virtual RNSVGPath view
*/
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {
@Override
public void draw(Canvas canvas, Paint paint, float opacity) {
traverseChildren(new NodeRunnable() {
public boolean run(RNSVGVirtualNode node) {
node.saveDefinition();
return true;
}
});
}
}
|
Clean up for Dungeon loot code
|
package techreborn.world;
import java.util.Arrays;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import techreborn.items.ItemIngots;
public class DungeonLoot {
public static void init()
{
generate(ItemIngots.getIngotByName("steel").getItem(), 5);
}
public static void generate(Item item, int rare)
{
for (String category : Arrays.asList(ChestGenHooks.VILLAGE_BLACKSMITH, ChestGenHooks.MINESHAFT_CORRIDOR, ChestGenHooks.PYRAMID_DESERT_CHEST, ChestGenHooks.PYRAMID_JUNGLE_CHEST, ChestGenHooks.PYRAMID_JUNGLE_DISPENSER, ChestGenHooks.STRONGHOLD_CORRIDOR, ChestGenHooks.STRONGHOLD_LIBRARY, ChestGenHooks.STRONGHOLD_CROSSING, ChestGenHooks.BONUS_CHEST, ChestGenHooks.DUNGEON_CHEST))
{
ChestGenHooks.addItem(category, new WeightedRandomChestContent(item, 0, 1, 3, rare));
}
}
}
|
package techreborn.world;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import techreborn.items.ItemIngots;
public class DungeonLoot {
public static void init()
{
generate(ItemIngots.getIngotByName("steel"), 5);
}
public static void generate(ItemStack itemStack, int rare)
{
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(itemStack, itemStack.getItemDamage(), itemStack.stackSize, rare));
ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(new WeightedRandomChestContent(itemStack, itemStack.getItemDamage(), itemStack.stackSize, rare));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(itemStack ,itemStack.getItemDamage(), itemStack.stackSize, rare));
ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CORRIDOR).addItem(new WeightedRandomChestContent(itemStack ,itemStack.getItemDamage(), itemStack.stackSize, rare));
}
}
|
Make the call to gladiator to unsubscribe a user
|
<?php
namespace Northstar\Http\Controllers\Web;
use Illuminate\Http\Request;
use DoSomething\Gateway\Gladiator;
use Illuminate\Routing\Controller as BaseController;
class UnsubscribeController extends BaseController
{
/**
* Gladiator instance.
*
* @var \DoSomething\Gateway\Gladiator
*/
protected $gladiator;
/**
* Create the controller instance.
*
* @param \DoSomething\Gateway\Gladiator $gladiator
*/
public function __construct(Gladiator $gladiator)
{
$this->gladiator = $gladiator;
}
/**
* Displays the subscriptions page
*/
public function getSubscriptions()
{
return view('auth.subscriptions');
}
/**
*
*/
public function postSubscriptions(Request $request)
{
$user = $request->input('user');
$competition = $request->input('competition');
if ($user && $competition) {
$response = $this->gladiator->unsubscribeUser($user, $competition);
}
}
}
|
<?php
namespace Northstar\Http\Controllers\Web;
use Illuminate\Http\Request;
use DoSomething\Gateway\Gladiator;
use Illuminate\Routing\Controller as BaseController;
class UnsubscribeController extends BaseController
{
/**
* Gladiator instance.
*
* @var \DoSomething\Gateway\Gladiator
*/
protected $gladiator;
/**
* Create the controller instance.
*
* @param \DoSomething\Gateway\Gladiator $gladiator
*/
public function __construct(Gladiator $gladiator)
{
$this->gladiator = $gladiator;
}
/**
* Displays the subscriptions page
*/
public function getSubscriptions()
{
return view('auth.subscriptions');
}
/**
*
*/
public function postSubscriptions(Request $request)
{
dd($this->gladiator);
// make sure to check that inputs exist.
dd($request->input('competition'));
}
}
|
Fix bug with multiprocessing and Nose.
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
try:
import multiprocessing # Seems to fix http://bugs.python.org/issue15881
except ImportError:
pass
setup_requires = []
if 'nosetests' in sys.argv[1:]:
setup_requires.append('nose')
setup(
name='modeldict',
version='0.1.1',
author='DISQUS',
author_email='opensource@disqus.com',
url='http://github.com/disqus/modeldict/',
description = 'Dictionary-style access to different types of models.',
packages=find_packages(),
zip_safe=False,
tests_require=[
'Django',
'nose',
'mock',
'redis'
],
test_suite = 'nose.collector',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
setup(
name='modeldict',
version='0.1.1',
author='DISQUS',
author_email='opensource@disqus.com',
url='http://github.com/disqus/modeldict/',
description = 'Dictionary-style access to different types of models.',
packages=find_packages(),
zip_safe=False,
tests_require=[
'Django',
'nose',
'mock',
'redis'
],
test_suite = 'nose.collector',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
Set server listen to 0.0.0.0
|
import Express from 'express';
import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
const webpackConfig = require('../webpack.dev.config');
const webpackCompiler = webpack(webpackConfig);
const webpackServerOptions = {
hot: true,
publicPath: webpackConfig.output.publicPath
};
const app = new Express();
app.use(webpackDevMiddleware(webpackCompiler, webpackServerOptions));
app.use(webpackHotMiddleware(webpackCompiler));
app.use(Express.static(path.join(__dirname, '..', 'static')));
app.use((req, res) => {
res.status(200);
res.sendFile(path.join(__dirname, 'index.dev.html'));
});
app.listen(3001, '0.0.0.0', () => {
console.info('Running on 3001');
});
|
import Express from 'express';
import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
const webpackConfig = require('../webpack.dev.config');
const webpackCompiler = webpack(webpackConfig);
const webpackServerOptions = {
hot: true,
publicPath: webpackConfig.output.publicPath
};
const app = new Express();
app.use(webpackDevMiddleware(webpackCompiler, webpackServerOptions));
app.use(webpackHotMiddleware(webpackCompiler));
app.use(Express.static(path.join(__dirname, '..', 'static')));
app.use((req, res) => {
res.status(200);
res.sendFile(path.join(__dirname, 'index.dev.html'));
});
app.listen(3001, 'localhost', () => {
console.info('Running on 3001');
});
|
Update User-Agent: Node -> node
|
var resources = require('./lib').resources;
var maybePromise = require('./lib').maybePromise;
var version = require('./package.json').version;
module.exports = function client(apiKey, config) {
//
// #client provides the top-level interface to making API requests to Button.
// It requires a Button API key, which can be found at
// https://app.usebutton.com/settings/organization.
//
// @param {string} apiKey your Button API key
// @param {Object=} config an optional object
// @param {number=} config.timeout a timeout in ms to abort API calls
// @param {Func=} config.promise a function which should return a promise
// @returns {Object} a client
//
if (!apiKey) {
throw new Error('Must provide a Button API key. Find yours at https://app.usebutton.com/settings/organization');
}
if (!config) {
config = {};
}
var requestOptions = {
hostname: 'api.usebutton.com',
auth: apiKey + ':',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'button-client-node/' + version + ' node/' + process.versions.node
}
};
return {
orders: resources.orders(requestOptions, config)
};
}
|
var resources = require('./lib').resources;
var maybePromise = require('./lib').maybePromise;
var version = require('./package.json').version;
module.exports = function client(apiKey, config) {
//
// #client provides the top-level interface to making API requests to Button.
// It requires a Button API key, which can be found at
// https://app.usebutton.com/settings/organization.
//
// @param {string} apiKey your Button API key
// @param {Object=} config an optional object
// @param {number=} config.timeout a timeout in ms to abort API calls
// @param {Func=} config.promise a function which should return a promise
// @returns {Object} a client
//
if (!apiKey) {
throw new Error('Must provide a Button API key. Find yours at https://app.usebutton.com/settings/organization');
}
if (!config) {
config = {};
}
var requestOptions = {
hostname: 'api.usebutton.com',
auth: apiKey + ':',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'button-client-node/' + version + ' Node/' + process.versions.node
}
};
return {
orders: resources.orders(requestOptions, config)
};
}
|
Set radial max amount to more reasonable 16.
|
/* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
* Copyright (c) 2010 Mr.doob, rhyolight, bebraw
*/
function RadialMirror() {
this.init();
}
RadialMirror.prototype = {
type: 'instance',
attributes: {'amount': {'type': 'int', 'min': 1, 'max': 16, 'value': 1}},
init: function () {},
destroy: function () {},
modify: function (x, y) { // XXX: this should modify x, y of the previous radial
amount = panels['modifiers'].radialValue; // XXX: stash this at the instance itself!
// XXX: replace with a nice math lib
angle = 2 * Math.PI / (amount + 1);
cosine = Math.cos(angle);
sine = Math.sin(angle);
centerX = window.innerWidth / 2;
centerY = window.innerHeight / 2;
originX = x - centerX;
originY = y - centerY;
return {'x': originX * cosine - originY * sine + centerX,
'y': originY * cosine + originX * sine + centerY};
}
}
|
/* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
* Copyright (c) 2010 Mr.doob, rhyolight, bebraw
*/
function RadialMirror() {
this.init();
}
RadialMirror.prototype = {
type: 'instance',
attributes: {'amount': {'type': 'int', 'min': 1, 'max': 64, 'value': 1}},
init: function () {},
destroy: function () {},
modify: function (x, y) { // XXX: this should modify x, y of the previous radial
amount = panels['modifiers'].radialValue; // XXX: stash this at the instance itself!
// XXX: replace with a nice math lib
angle = 2 * Math.PI / (amount + 1);
cosine = Math.cos(angle);
sine = Math.sin(angle);
centerX = window.innerWidth / 2;
centerY = window.innerHeight / 2;
originX = x - centerX;
originY = y - centerY;
return {'x': originX * cosine - originY * sine + centerX,
'y': originY * cosine + originX * sine + centerY};
}
}
|
Change standard function to arrow function
|
document.addEventListener("DOMContentLoaded", () => {
main();
});
const main = () => {
const button = document.getElementById("start");
button.addEventListener("click", () => {
const num = 1000000;
let text = "";
for (let i = 0; i < 1024; i++) {
text = text + "a";
}
for (let i = 0; i < num; i ++) {
try {
window.sessionStorage.setItem(i, text);
} catch (error) {
changeText("note", filesize(new Blob([text]).size * i) + " text was saved in Session Storage.");
throw error;
}
}
changeText("note", "Congrats! All " + filesize(new Blob([text]).size * num) + " text was saved in Session Storage.");
});
};
const changeText = (id, text) => {
document.getElementById(id).textContent = text;
}
|
document.addEventListener("DOMContentLoaded", function() {
main();
});
const main = () => {
const button = document.getElementById("start");
button.addEventListener("click", () => {
const num = 1000000;
let text = "";
for (let i = 0; i < 1024; i++) {
text = text + "a";
}
for (let i = 0; i < num; i ++) {
try {
window.sessionStorage.setItem(i, text);
} catch (error) {
changeText("note", filesize(new Blob([text]).size * i) + " text was saved in Session Storage.");
throw error;
}
}
changeText("note", "Congrats! All " + filesize(new Blob([text]).size * num) + " text was saved in Session Storage.");
});
};
const changeText = (id, text) => {
document.getElementById(id).textContent = text;
}
|
Rename cookie keys to be consistent with naming
|
'use strict';
/**
* @module code-project/handler/select-messaging-platform
*/
/**
* Stores the messaging platform information
* @param {Request} request - Hapi Request
* @param {Reply} reply - Hapi Reply
* @returns {Null} responds with a redirect
*/
function selectMessagingPlatform (request, reply) {
const {prefix} = request.route.realm.modifiers.route;
request
.yar
.set({
'slack-project-access-token': request.payload.accessToken,
'slack-project-course-channel-names': request.payload.courseChannelNames,
'slack-project-team-channel-names': request.payload.teamChannelNames,
'slack-project-use-slack': request.payload.useSlack
});
reply().redirect(`${prefix}/recipe/code-project/choose-assessment-system`);
}
module.exports = selectMessagingPlatform;
|
'use strict';
/**
* @module code-project/handler/select-messaging-platform
*/
/**
* Stores the messaging platform information
* @param {Request} request - Hapi Request
* @param {Reply} reply - Hapi Reply
* @returns {Null} responds with a redirect
*/
function selectMessagingPlatform (request, reply) {
const {prefix} = request.route.realm.modifiers.route;
request
.yar
.set({
'slack-team-access-token': request.payload.accessToken,
'slack-team-course-channel-names': request.payload.courseChannelNames,
'slack-team-team-channel-names': request.payload.teamChannelNames
});
reply().redirect(`${prefix}/recipe/code-project/choose-assessment-system`);
}
module.exports = selectMessagingPlatform;
|
Fix state machine using wrong variable
|
#!/usr/bin/env python
import rospy
class StopStates(object):
NORMAL = 0
FULL_STOP = 1
IGNORE_STOP_SIGNS = 2
class StopSign(object):
def __init__(self):
self.state = StopStates.NORMAL
self.stopDuration = 2
self.ignoreDuration = 4
def stopSignDetected(self):
self.state = StopStates.FULL_STOP
timer = rospy.Timer(rospy.Duration(self.stopDuration),
self.stepStateMachine,
oneshot=True)
def stepStateMachine(self, event):
if self.state is StopStates.NORMAL:
self.state = StopStates.FULL_STOP
elif self.state is StopStates.FULL_STOP:
self.state = StopStates.IGNORE_STOP_SIGNS
timer = rospy.Timer(rospy.Duration(self.ignoreDuration),
self.stepStateMachine,
oneshot=True)
elif self.state is StopStates.IGNORE_STOP_SIGNS:
self.state = StopStates.NORMAL
|
#!/usr/bin/env python
import rospy
class StopStates(object):
NORMAL = 0
FULL_STOP = 1
IGNORE_STOP_SIGNS = 2
class StopSign(object):
def __init__(self):
self.state = StopStates.NORMAL
self.stopDuration = 2
self.ignoreDuration = 2
def stopSignDetected(self):
self.state = StopStates.FULL_STOP
timer = rospy.Timer(rospy.Duration(self.stopDuration),
self.stepStateMachine,
oneshot=True)
def stepStateMachine(self):
if self.state is StopStates.NORMAL:
self.action = StopStates.FULL_STOP
elif self.state is StopStates.FULL_STOP:
self.action = StopStates.IGNORE_STOP_SIGNS
timer = rospy.Timer(rospy.Duration(self.ignoreDuration),
self.stepStateMachine,
oneshot=True)
elif self.state is StopStates.IGNORE_STOP_SIGNS:
self.action = StopStates.NORMAL
|
Fix force_unicode for Python 3, use force_text()
|
"""
Internal utils for search.
"""
from django.utils.encoding import force_text
from django.utils.html import strip_tags
import six
def get_search_field_values(contentitem):
"""
Extract the search fields from the model.
"""
plugin = contentitem.plugin
values = []
for field_name in plugin.search_fields:
value = getattr(contentitem, field_name)
# Just assume all strings may contain HTML.
# Not checking for just the PluginHtmlField here.
if value and isinstance(value, six.string_types):
value = get_cleaned_string(value)
values.append(value)
return values
def get_search_text(contentitem):
bits = get_search_field_values(contentitem)
return clean_join(u" ", bits)
def get_cleaned_string(data):
"""
Cleanup a string/HTML output to consist of words only.
"""
return strip_tags(force_text(data))
def clean_join(separator, iterable):
"""
Filters out iterable to only join non empty items.
"""
return separator.join(filter(None, iterable))
#def get_cleaned_bits(data):
# return smart_split(get_cleaned_bits(data))
|
"""
Internal utils for search.
"""
from django.utils.encoding import force_unicode
from django.utils.html import strip_tags
import six
def get_search_field_values(contentitem):
"""
Extract the search fields from the model.
"""
plugin = contentitem.plugin
values = []
for field_name in plugin.search_fields:
value = getattr(contentitem, field_name)
# Just assume all strings may contain HTML.
# Not checking for just the PluginHtmlField here.
if value and isinstance(value, six.string_types):
value = get_cleaned_string(value)
values.append(value)
return values
def get_search_text(contentitem):
bits = get_search_field_values(contentitem)
return clean_join(u" ", bits)
def get_cleaned_string(data):
"""
Cleanup a string/HTML output to consist of words only.
"""
return strip_tags(force_unicode(data))
def clean_join(separator, iterable):
"""
Filters out iterable to only join non empty items.
"""
return separator.join(filter(None, iterable))
#def get_cleaned_bits(data):
# return smart_split(get_cleaned_bits(data))
|
Throw exception when primary tests fail
|
import os
import sys
import contextlib
import subprocess
@contextlib.contextmanager
def binding(binding):
"""Prepare an environment for a specific binding"""
sys.stderr.write("""\
#
# Running tests with %s..
#
""" % binding)
os.environ["QT_PREFERRED_BINDING"] = binding
try:
yield
except:
pass
os.environ.pop("QT_PREFERRED_BINDING")
if __name__ == "__main__":
argv = [
"nosetests",
"--verbose",
"--with-process-isolation",
"--exe",
]
errors = 0
# Running each test independently via subprocess
# enables tests to filter out from tests.py before
# being split into individual processes via the
# --with-process-isolation feature of nose.
with binding("PyQt4"):
errors += subprocess.call(argv)
with binding("PySide"):
errors += subprocess.call(argv)
with binding("PyQt5"):
errors += subprocess.call(argv)
with binding("PySide2"):
errors += subprocess.call(argv)
if errors:
raise Exception("%i binding(s) failed." % errors)
|
import os
import sys
import contextlib
import subprocess
@contextlib.contextmanager
def binding(binding):
"""Prepare an environment for a specific binding"""
sys.stderr.write("""\
#
# Running tests with %s..
#
""" % binding)
os.environ["QT_PREFERRED_BINDING"] = binding
try:
yield
except:
pass
os.environ.pop("QT_PREFERRED_BINDING")
if __name__ == "__main__":
argv = [
"nosetests",
"--verbose",
"--with-process-isolation",
"--exe",
]
# argv.extend(sys.argv[1:])
# Running each test independently via subprocess
# enables tests to filter out from tests.py before
# being split into individual processes via the
# --with-process-isolation feature of nose.
with binding("PyQt4"):
subprocess.call(argv)
with binding("PySide"):
subprocess.call(argv)
with binding("PyQt5"):
subprocess.call(argv)
with binding("PySide2"):
subprocess.call(argv)
|
Fix PRIVATE_PORT env variable read
|
'use strict';
const EventEmitter = require('events');
const createPublicWebApp = require('./web/public');
const createPrivateWebApp = require('./web/private');
const actions = require('./core/actions');
const logger = require('./lib/logger');
const emitter = new EventEmitter();
const githubSecret = process.env.GH_SECRET;
const publicWebApp = createPublicWebApp(emitter, githubSecret);
const privateWebApp = createPrivateWebApp(actions);
actions.subscribeCheckersToEvents(emitter);
const publicPort = process.env.PORT || 8080;
publicWebApp.listen(publicPort, err => {
if (err) logger.error('Error starting the public server', err);
else logger.info(`Listening public server in ${publicPort}`);
});
const privatePort = process.env.PRIVATE_PORT || 8484;
privateWebApp.listen(privatePort, err => {
if (err) logger.error('Error starting the private server', err);
else logger.info(`Listening private server in ${privatePort}`);
});
|
'use strict';
const EventEmitter = require('events');
const createPublicWebApp = require('./web/public');
const createPrivateWebApp = require('./web/private');
const actions = require('./core/actions');
const logger = require('./lib/logger');
const emitter = new EventEmitter();
const githubSecret = process.env.GH_SECRET;
const publicWebApp = createPublicWebApp(emitter, githubSecret);
const privateWebApp = createPrivateWebApp(actions);
actions.subscribeCheckersToEvents(emitter);
const publicPort = process.env.PORT || 8080;
publicWebApp.listen(publicPort, err => {
if (err) logger.error('Error starting the public server', err);
else logger.info(`Listening public server in ${publicPort}`);
});
const privatePort = process.PRIVATE_PORT || 8484;
privateWebApp.listen(privatePort, err => {
if (err) logger.error('Error starting the private server', err);
else logger.info(`Listening private server in ${privatePort}`);
});
|
Add check for empty tags
|
from .request import url
class Search(object):
def __init__(self, key=None, q=[], sf="created_at", sd="desc"):
self._parameters = {
"key": key,
"q": [str(tag).strip() for tag in q if tag],
"sf": sf,
"sd": sd
}
@property
def parameters(self):
return self._parameters
@property
def url(self):
return url(**self.parameters)
def key(self, key=None):
self._parameters["key"] = key
return Search(**self._parameters)
def query(self, *q):
self._parameters["q"] = [str(tag).strip() for tag in q if tag]
return Search(**self._parameters)
def descending(self):
self._parameters["sd"] = "desc"
return Search(**self._parameters)
def ascending(self):
self._parameters["sd"] = "asc"
return Search(**self._parameters)
def sort_by(self, sf):
self._parameters["sf"] = sf
return Search(**self._parameters)
|
from .request import url
class Search(object):
def __init__(self, key=None, q=[], sf="created_at", sd="desc"):
self._parameters = {
"key": key,
"q": q,
"sf": sf,
"sd": sd
}
@property
def parameters(self):
return self._parameters
@property
def url(self):
return url(**self.parameters)
def key(self, key=None):
self._parameters["key"] = key
return Search(**self._parameters)
def query(self, *q):
self._parameters["q"] = [str(tag).strip() for tag in q]
return Search(**self._parameters)
def descending(self):
self._parameters["sd"] = "desc"
return Search(**self._parameters)
def ascending(self):
self._parameters["sd"] = "asc"
return Search(**self._parameters)
def sort_by(self, sf):
self._parameters["sf"] = sf
return Search(**self._parameters)
|
Make `is_authenticated` a property access rather than a function call.
This is a change in Django that was still functional for compatibility
reasons until recently, but ultimately should be an attribute.
|
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from server.models import *
class AddToBU(MiddlewareMixin):
"""
This middleware will add the current user to any BU's they've not already
been explicitly added to.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
if hasattr(settings, 'ADD_TO_ALL_BUSINESS_UNITS'):
if request.user.is_authenticated:
if settings.ADD_TO_ALL_BUSINESS_UNITS \
and request.user.userprofile.level != 'GA':
for business_unit in BusinessUnit.objects.all():
if request.user not in business_unit.users.all():
business_unit.users.add(request.user)
business_unit.save()
return None
|
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from server.models import *
class AddToBU(MiddlewareMixin):
"""
This middleware will add the current user to any BU's they've not already
been explicitly added to.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
if hasattr(settings, 'ADD_TO_ALL_BUSINESS_UNITS'):
if request.user.is_authenticated():
if settings.ADD_TO_ALL_BUSINESS_UNITS \
and request.user.userprofile.level != 'GA':
for business_unit in BusinessUnit.objects.all():
if request.user not in business_unit.users.all():
business_unit.users.add(request.user)
business_unit.save()
return None
|
Clarify missing output file error
|
var React = require('react');
var evaluate = require('eval');
function ReactToHtmlWebpackPlugin(destPath, srcPath) {
this.srcPath = srcPath;
this.destPath = destPath;
}
ReactToHtmlWebpackPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compiler, done) {
try {
var asset = compiler.assets[this.srcPath];
if (asset === undefined) {
throw new Error('Output file not found: "' + this.srcPath + '"');
}
var source = asset.source();
var Component = evaluate(source);
var html = React.renderToString(Component());
compiler.assets[this.destPath] = createAssetFromContents(html);
} catch (err) {
return done(err);
}
done();
}.bind(this));
};
var createAssetFromContents = function(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
};
module.exports = ReactToHtmlWebpackPlugin;
|
var React = require('react');
var evaluate = require('eval');
function ReactToHtmlWebpackPlugin(destPath, srcPath) {
this.srcPath = srcPath;
this.destPath = destPath;
}
ReactToHtmlWebpackPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compiler, done) {
try {
var asset = compiler.assets[this.srcPath];
if (asset === undefined) {
throw new Error('File not found: "' + this.srcPath + '"');
}
var source = asset.source();
var Component = evaluate(source);
var html = React.renderToString(Component());
compiler.assets[this.destPath] = createAssetFromContents(html);
} catch (err) {
return done(err);
}
done();
}.bind(this));
};
var createAssetFromContents = function(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
};
module.exports = ReactToHtmlWebpackPlugin;
|
Add another TBD for future reference
|
from blinkytape import color
class Gradient(object):
# TBD: If this had a length it would also work as a streak; consider
def __init__(self, pixel_count, start_color, end_color):
self._pixels = self._rgb_gradient(pixel_count, start_color, end_color)
@property
def pixels(self):
return list(self._pixels)
def _rgb_gradient(self, pixel_count, start_color, end_color):
red_gradient = self._gradient(start_color.red, end_color.red, pixel_count)
green_gradient = self._gradient(start_color.green, end_color.green, pixel_count)
blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count)
rgb_gradient = zip(red_gradient, green_gradient, blue_gradient)
return [color.Color(*rgb) for rgb in rgb_gradient]
def _gradient(self, start, end, count):
delta = (end - start) / float(count - 1)
return [start + (delta * index) for index in range(0, count)]
|
from blinkytape import color
class Gradient(object):
def __init__(self, pixel_count, start_color, end_color):
self._pixels = self._rgb_gradient(pixel_count, start_color, end_color)
@property
def pixels(self):
return list(self._pixels)
def _rgb_gradient(self, pixel_count, start_color, end_color):
red_gradient = self._gradient(start_color.red, end_color.red, pixel_count)
green_gradient = self._gradient(start_color.green, end_color.green, pixel_count)
blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count)
rgb_gradient = zip(red_gradient, green_gradient, blue_gradient)
return [color.Color(*rgb) for rgb in rgb_gradient]
def _gradient(self, start, end, count):
delta = (end - start) / float(count - 1)
return [start + (delta * index) for index in range(0, count)]
|
Fix to use single quotes instead of double quotes
|
const binding = require('bindings')('contextify');
const ContextifyContext = binding.ContextifyContext;
const ContextifyScript = binding.ContextifyScript;
function Contextify (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
let ctx = new ContextifyContext(sandbox);
sandbox.run = function () {
return ctx.run.apply(ctx, arguments);
};
sandbox.getGlobal = function () {
return ctx.getGlobal();
}
sandbox.dispose = function () {
sandbox.run = function () {
throw new Error('Called run() after dispose().');
};
sandbox.getGlobal = function () {
throw new Error('Called getGlobal() after dispose().');
};
sandbox.dispose = function () {
throw new Error('Called dispose() after dispose().');
};
ctx = null;
}
return sandbox;
}
Contextify.createContext = function (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
return new ContextifyContext(sandbox);
};
Contextify.createScript = function (code, filename) {
if (typeof code != 'string') {
throw new TypeError('Code argument is required');
}
return new ContextifyScript(code, filename);
};
module.exports = Contextify;
|
const binding = require('bindings')('contextify');
const ContextifyContext = binding.ContextifyContext;
const ContextifyScript = binding.ContextifyScript;
function Contextify (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
let ctx = new ContextifyContext(sandbox);
sandbox.run = function () {
return ctx.run.apply(ctx, arguments);
};
sandbox.getGlobal = function () {
return ctx.getGlobal();
}
sandbox.dispose = function () {
sandbox.run = function () {
throw new Error("Called run() after dispose().");
};
sandbox.getGlobal = function () {
throw new Error("Called getGlobal() after dispose().");
};
sandbox.dispose = function () {
throw new Error("Called dispose() after dispose().");
};
ctx = null;
}
return sandbox;
}
Contextify.createContext = function (sandbox) {
if (typeof sandbox != 'object') {
sandbox = {};
}
return new ContextifyContext(sandbox);
};
Contextify.createScript = function (code, filename) {
if (typeof code != 'string') {
throw new TypeError('Code argument is required');
}
return new ContextifyScript(code, filename);
};
module.exports = Contextify;
|
Make log event format more readable
|
/*
* Copyright 2018, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.k8s.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogEventLogger implements EventLogger {
private static final Logger log = LoggerFactory.getLogger(LogEventLogger.class);
@Override
public void log(Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
log(log, reason, message, type, objectKind, objectName);
}
public static void log(Logger logger, Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
String line = String.format("%s (kind=%s name=%s): %s", reason.name(), objectKind.name(), objectName, message);
switch (type) {
case Warning:
logger.warn(line);
break;
case Normal:
logger.info(line);
break;
}
}
}
|
/*
* Copyright 2018, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.k8s.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogEventLogger implements EventLogger {
private static final Logger log = LoggerFactory.getLogger(LogEventLogger.class);
@Override
public void log(Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
log(log, reason, message, type, objectKind, objectName);
}
public static void log(Logger logger, Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
String line = String.format("%s (%s): %s %s", objectName, objectKind.name(), reason.name(), message);
switch (type) {
case Warning:
logger.warn(line);
break;
case Normal:
logger.info(line);
break;
}
}
}
|
Load pagination per_page limit from configuration.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Story\Routing;
use Illuminate\Routing\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\View;
use Orchestra\Story\Model\Content;
class HomeController extends Controller {
/**
* Get landing page.
*
* @access public
* @return Response
*/
public function index()
{
$page = Config::get('orchestra/story::default_page', '_posts_');
if ($page === '_posts_') return $this->showPosts();
return $this->showDefaultPage($page);
}
/**
* Show posts.
*
* @access public
* @return Response
*/
public function showPosts()
{
$posts = Content::post()->publish()->paginate(Config::get('orchestra/story::per_page', 10));
return View::make('orchestra/story::posts', compact('posts'));
}
/**
* Show default page.
*
* @access protected
* @param string $slug
* @return Response
*/
protected function showDefaultPage($slug)
{
$page = Content::page()->publish()->where('slug', '=', $slug)->firstOrFail();
if ( ! View::exists($view = "orchestra/story::pages.{$slug}"))
{
$view = 'orchestra/story::page';
}
return View::make($view, compact('page'));
}
}
|
<?php namespace Orchestra\Story\Routing;
use Illuminate\Routing\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\View;
use Orchestra\Story\Model\Content;
class HomeController extends Controller {
/**
* Get landing page.
*
* @access public
* @return Response
*/
public function index()
{
$page = Config::get('orchestra/story::default_page', '_posts_');
if ($page === '_posts_') return $this->showPosts();
return $this->showDefaultPage($page);
}
/**
* Show posts.
*
* @access public
* @return Response
*/
public function showPosts()
{
$posts = Content::post()->publish()->paginate(10);
return View::make('orchestra/story::posts', compact('posts'));
}
/**
* Show default page.
*
* @access protected
* @param string $slug
* @return Response
*/
protected function showDefaultPage($slug)
{
$page = Content::page()->publish()->where('slug', '=', $slug)->firstOrFail();
if ( ! View::exists($view = "orchestra/story::pages.{$slug}"))
{
$view = 'orchestra/story::page';
}
return View::make($view, compact('page'));
}
}
|
Fix Flask example to allow freezing
|
import logging
import webview
from contextlib import redirect_stdout
from io import StringIO
from threading import Thread, Lock
from time import sleep
from server import run_server
server_lock = Lock()
logger = logging.getLogger(__name__)
def url_ok(url, port):
# Use httplib on Python 2
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
try:
conn = HTTPConnection(url, port)
conn.request('GET', '/')
r = conn.getresponse()
return r.status == 200
except:
logger.exception('Server not started')
return False
if __name__ == '__main__':
stream = StringIO()
with redirect_stdout(stream):
logger.debug('Starting server')
t = Thread(target=run_server)
t.daemon = True
t.start()
logger.debug('Checking server')
while not url_ok('127.0.0.1', 23948):
sleep(1)
logger.debug('Server started')
window = webview.create_window('My first pywebview application', 'http://127.0.0.1:23948')
webview.start(debug=True)
|
from threading import Thread, Lock
import logging
import webview
from time import sleep
from server import run_server
server_lock = Lock()
logger = logging.getLogger(__name__)
def url_ok(url, port):
# Use httplib on Python 2
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
try:
conn = HTTPConnection(url, port)
conn.request('GET', '/')
r = conn.getresponse()
return r.status == 200
except:
logger.exception('Server not started')
return False
if __name__ == '__main__':
logger.debug('Starting server')
t = Thread(target=run_server)
t.daemon = True
t.start()
logger.debug('Checking server')
while not url_ok('127.0.0.1', 23948):
sleep(1)
logger.debug('Server started')
window = webview.create_window('My first pywebview application', 'http://127.0.0.1:23948')
webview.start(debug=True)
|
Make sure there actually is an object
|
var txt_cache='604800';chrome.webRequest.onHeadersReceived.addListener(function(object){'use strict';if(object){var object_type=object.type.toLowerCase();if((object_type!=='main_frame')&&(object_type!=='sub_frame')&&(object_type!=='xmlhttprequest')){var headers=object.responseHeaders,len=headers.length-1,f=false,elem=null;do{elem=headers[len];switch(elem.name.toLowerCase()){case'cache-control':if(!f){f=true;elem.value='private, max-age='+txt_cache;}else{headers.splice(len,1);}
break;case'expires':case'last-modified':case'etag':headers.splice(len,1);break;default:break;}}while(len--);if(!f){var obj=null;obj={};obj.name='Cache-Control';obj.value='private, max-age='+txt_cache;headers.push(obj);}
return{responseHeaders:headers};}}},{urls:['<all_urls>']},['blocking','responseHeaders']);chrome.runtime.onInstalled.addListener(function(){localStorage.run=true;txt_cache=localStorage.txt_cache='604800';});if(localStorage.run){txt_cache=localStorage.txt_cache;}else{localStorage.run=true;txt_cache=localStorage.txt_cache='604800';}
|
var txt_cache='604800';chrome.webRequest.onHeadersReceived.addListener(function(object){'use strict';var object_type=object.type.toLowerCase();if((object_type!=='main_frame')&&(object_type!=='sub_frame')&&(object_type!=='xmlhttprequest')){var headers=object.responseHeaders,len=headers.length-1,f=false,elem=null;do{elem=headers[len];switch(elem.name.toLowerCase()){case'cache-control':if(!f){f=true;elem.value='private, max-age='+txt_cache;}else{headers.splice(len,1);}
break;case'expires':case'last-modified':case'etag':headers.splice(len,1);break;default:break;}}while(len--);if(!f){var obj=null;obj={};obj.name='Cache-Control';obj.value='private, max-age='+txt_cache;headers.push(obj);}
return{responseHeaders:headers};}},{urls:['<all_urls>']},['blocking','responseHeaders']);chrome.runtime.onInstalled.addListener(function(){localStorage.run=true;txt_cache=localStorage.txt_cache='604800';});if(localStorage.run){txt_cache=localStorage.txt_cache;}else{localStorage.run=true;txt_cache=localStorage.txt_cache='604800';}
|
Add period to keep grammar nazis and godoc happy.
Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>
|
package ninja
import (
"time"
)
type ServiceClient struct {
conn *Connection
topic string
}
//
// OnEvent builds a simple subscriber which supports pulling apart the topic
//
// err := sm.conn.GetServiceClient("$device/:deviceid/channel/:channelid")
// .OnEvent("state", func(params *YourEventType, topicKeys map[string]string) bool {
// ..
// return true
// })
//
// YourEventType must either be *json.RawMessage or a pointer to go type to which the raw JSON message can successfully be unmarshalled.
//
// There is one entry in the topicKeys map for each parameter marker in the topic string used to obtain the ServiceClient.
//
// Both the params and topicKeys parameters can be omitted. If the topicKeys parameter is required, the params parameter must also be specified.
//
func (c *ServiceClient) OnEvent(event string, callback interface{}) error {
return c.conn.Subscribe(c.topic+"/event/"+event, callback);
}
func (c *ServiceClient) Call(method string, args interface{}, reply interface{}, timeout time.Duration) error {
return c.conn.rpc.CallWithTimeout(c.topic, method, args, reply, timeout)
}
|
package ninja
import (
"time"
)
type ServiceClient struct {
conn *Connection
topic string
}
//
// OnEvent builds a simple subscriber which supports pulling apart the topic
//
// err := sm.conn.GetServiceClient("$device/:deviceid/channel/:channelid")
// .OnEvent("state", func(params *YourEventType, topicKeys map[string]string) bool {
// ..
// return true
// })
//
// YourEventType must either be *json.RawMessage or a pointer to go type to which the raw JSON message can successfully be unmarshalled.
//
// There is one entry in the topicKeys map for each parameter marker in the topic string used to obtain the ServiceClient
//
// Both the params and topicKeys parameters can be omitted. If the topicKeys parameter is required, the params parameter must also be specified.
//
func (c *ServiceClient) OnEvent(event string, callback interface{}) error {
return c.conn.Subscribe(c.topic+"/event/"+event, callback);
}
func (c *ServiceClient) Call(method string, args interface{}, reply interface{}, timeout time.Duration) error {
return c.conn.rpc.CallWithTimeout(c.topic, method, args, reply, timeout)
}
|
Add comment for event state
|
/*
* Copyright 2017 Axway Software
*
* 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.axway.ats.log.autodb.events;
import org.apache.log4j.Logger;
import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;
@SuppressWarnings( "serial")
public class StartAfterClassEvent extends AbstractLoggingEvent {
public StartAfterClassEvent( String loggerFQCN, Logger logger ) {
super(loggerFQCN, logger, "Start after class execution", LoggingEventType.START_AFTER_CLASS);
}
@Override
protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {
/* This event is fired after a suite is already closed,
since ATS (AtsTestngListener) could not be certain that @AfterClass will be available
*/
return LifeCycleState.ATLEAST_RUN_STARTED;
}
}
|
/*
* Copyright 2017 Axway Software
*
* 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.axway.ats.log.autodb.events;
import org.apache.log4j.Logger;
import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;
@SuppressWarnings( "serial")
public class StartAfterClassEvent extends AbstractLoggingEvent {
public StartAfterClassEvent( String loggerFQCN, Logger logger ) {
super(loggerFQCN, logger, "Start after class execution", LoggingEventType.START_AFTER_CLASS);
}
@Override
protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {
return LifeCycleState.ATLEAST_RUN_STARTED;
}
}
|
Move the package comments above package
|
/*
Copyright 2018 The Kubernetes Authors.
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 imports dependencies required for "dep ensure" to fetch all of the go package dependencies needed
by kubebuilder commands to work without rerunning "dep ensure".
Example: make sure the testing libraries and apimachinery libraries are fetched by "dep ensure" so that
dep ensure doesn't need to be rerun after "kubebuilder create resource".
This is necessary for subsequent commands - such as building docs, tests, etc - to work without rerunning "dep ensure"
afterward.
*/
package hack
import _ "github.com/kubernetes-sigs/kubebuilder/pkg/imports"
|
/*
Copyright 2018 The Kubernetes Authors.
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 hack
/*
Package imports dependencies required for "dep ensure" to fetch all of the go package dependencies needed
by kubebuilder commands to work without rerunning "dep ensure".
Example: make sure the testing libraries and apimachinery libraries are fetched by "dep ensure" so that
dep ensure doesn't need to be rerun after "kubebuilder create resource".
This is necessary for subsequent commands - such as building docs, tests, etc - to work without rerunning "dep ensure"
afterward.
*/
import _ "github.com/kubernetes-sigs/kubebuilder/pkg/imports"
|
Add class active to first tabs link
|
export default function normalizeTabControllerClick() {
const hashLinks = document.querySelectorAll(".js-tabs-control a[href^='#']");
const firstLink = document.querySelector('.js-tabs-control > a');
function setActiveLink(event) {
Array.prototype.forEach.call(hashLinks, (link) => {
link.classList.remove('active');
});
event.target.classList.add('active');
}
Array.prototype.forEach.call(hashLinks, (link) => {
link.addEventListener('click', (event) => {
event.preventDefault();
setActiveLink(event);
window.history.pushState({}, '', link.href);
// Update the URL again with the same hash, then go back
window.history.pushState({}, '', link.href);
window.history.back();
});
});
if (window.location.hash) return;
if (firstLink) firstLink.click();
if (firstLink) firstLink.classList.add('active');
}
|
export default function normalizeTabControllerClick() {
const hashLinks = document.querySelectorAll(".js-tabs-control a[href^='#']");
const firstLink = document.querySelector('.js-tabs-control > a');
function setActiveLink(event) {
Array.prototype.forEach.call(hashLinks, (link) => {
link.classList.remove('active');
});
event.target.classList.add('active');
}
Array.prototype.forEach.call(hashLinks, (link) => {
link.addEventListener('click', (event) => {
event.preventDefault();
setActiveLink(event);
window.history.pushState({}, '', link.href);
// Update the URL again with the same hash, then go back
window.history.pushState({}, '', link.href);
window.history.back();
});
});
if (window.location.hash) return;
if (firstLink) firstLink.click();
}
|
Update SUPPORTS_TRANSACTIONS attribute to what is expected by Django 1.2.
Patch contributed by Felix Leong. Thanks.
Fixes Issue #162.
|
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
def create_test_db(self, *args, **kw):
"""Destroys the test datastore. A new store will be recreated on demand"""
# Only needed for Django 1.1, deprecated @ 1.2.
settings.DATABASE_SUPPORTS_TRANSACTIONS = False
self.connection.settings_dict['SUPPORTS_TRANSACTIONS'] = False
self.destroy_test_db()
self.connection.use_test_datastore = True
self.connection.flush()
def destroy_test_db(self, *args, **kw):
"""Destroys the test datastore files."""
from appengine_django.db.base import destroy_datastore
from appengine_django.db.base import get_test_datastore_paths
destroy_datastore(*get_test_datastore_paths())
logging.debug("Destroyed test datastore")
|
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
def create_test_db(self, *args, **kw):
"""Destroys the test datastore. A new store will be recreated on demand"""
settings.DATABASE_SUPPORTS_TRANSACTIONS = False
self.destroy_test_db()
self.connection.use_test_datastore = True
self.connection.flush()
def destroy_test_db(self, *args, **kw):
"""Destroys the test datastore files."""
from appengine_django.db.base import destroy_datastore
from appengine_django.db.base import get_test_datastore_paths
destroy_datastore(*get_test_datastore_paths())
logging.debug("Destroyed test datastore")
|
Allow counting sort to handle negative numbers
|
public class CountingSort {
public static int[] countingSort(int[] unsorted) {
int minValue = min(unsorted);
int maxValue = max(unsorted);
// Adjust max so that min equals zero
int offset = -minValue;
int adjustedMax = maxValue + offset;
// Count occurrences of each value in unsorted
int[] counts = new int[adjustedMax + 1];
for(int value : unsorted)
counts[value + offset]++;
for(int i = 1; i < counts.length; i++)
counts[i] += counts[i - 1];
// Reorder values in unsorted
int[] sorted = new int[unsorted.length];
for(int value : unsorted) {
int index = --counts[value + offset];
sorted[index] = value;
}
return sorted;
}
private static int min(int[] array) {
int min = Integer.MAX_VALUE;
for(int value : array)
if(value < min) min = value;
return min;
}
private static int max(int[] array) {
int max = Integer.MIN_VALUE;
for(int value : array)
if(value > max) max = value;
return max;
}
public static void main(String[] args) {
int[] unsorted = {5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -3, -3};
int[] sorted = countingSort(unsorted);
for(int value : sorted)
System.out.println(value);
}
}
|
public class CountingSort {
public static int[] countingSort(int[] unsorted) {
int maxValue = max(unsorted);
// Count occurrences of each value in unsorted
int[] counts = new int[maxValue + 1];
for(int value : unsorted)
counts[value]++;
for(int i = 1; i < counts.length; i++)
counts[i] += counts[i - 1];
// Reorder values in unsorted
int[] sorted = new int[unsorted.length];
for(int value : unsorted) {
counts[value] -= 1;
int index = counts[value];
sorted[index] = value;
}
return sorted;
}
private static int max(int[] array) {
int max = Integer.MIN_VALUE;
for(int value : array) {
if(value > max) max = value;
}
return max;
}
public static void main(String[] args) {
int[] unsorted = {5, 5, 5, 4, 3, 2, 1, 0};
int[] sorted = countingSort(unsorted);
for(int value : sorted)
System.out.println(value);
}
}
|
Set return on parent when using api::create
|
<?php
/**
* Created by PhpStorm.
* User: mark.smith
* Date: 04/09/2017
* Time: 19:31
*/
namespace AppBundle\Utils\Api;
use AppBundle\Utils\Api;
class Redis extends Api implements \AppBundle\Utils\Api\ApiInterface
{
protected $storageClass = 'redis';
public function __construct()
{
$this->setStorageClass($this->storageClass);
}
public function read($what)
{
$this->setWhat($what);
return parent::doRead();
}
public function update($data, $what)
{
}
public function create($data)
{
$this->setData($data);
return parent::doCreate();
}
public function delete($what)
{
}
}
|
<?php
/**
* Created by PhpStorm.
* User: mark.smith
* Date: 04/09/2017
* Time: 19:31
*/
namespace AppBundle\Utils\Api;
use AppBundle\Utils\Api;
class Redis extends Api implements \AppBundle\Utils\Api\ApiInterface
{
protected $storageClass = 'redis';
public function __construct()
{
$this->setStorageClass($this->storageClass);
}
public function read($what)
{
$this->setWhat($what);
return parent::doRead();
}
public function update($data, $what)
{
}
public function create($data)
{
$this->setData($data);
parent::doCreate();
}
public function delete($what)
{
}
}
|
Document that Close must be called on the reader returned from NewStreamReader
|
package fasthttp
import (
"bufio"
"io"
"runtime/debug"
"sync"
)
// StreamWriter must write data to w.
//
// Usually StreamWriter writes data to w in a loop (aka 'data streaming').
//
// StreamWriter must return immediately if w returns error.
//
// Since the written data is buffered, do not forget calling w.Flush
// when the data must be propagated to reader.
type StreamWriter func(w *bufio.Writer)
// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// Close must be called on the returned reader after after all the required data
// has been read. Otherwise goroutine leak may occur.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.ReadCloser {
pr, pw := io.Pipe()
var bw *bufio.Writer
v := streamWriterBufPool.Get()
if v == nil {
bw = bufio.NewWriter(pw)
} else {
bw = v.(*bufio.Writer)
bw.Reset(pw)
}
go func() {
defer func() {
if r := recover(); r != nil {
defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
}
}()
sw(bw)
bw.Flush()
pw.Close()
streamWriterBufPool.Put(bw)
}()
return pr
}
var streamWriterBufPool sync.Pool
|
package fasthttp
import (
"bufio"
"io"
"runtime/debug"
"sync"
)
// StreamWriter must write data to w.
//
// Usually StreamWriter writes data to w in a loop (aka 'data streaming').
//
// StreamWriter must return immediately if w returns error.
//
// Since the written data is buffered, do not forget calling w.Flush
// when the data must be propagated to reader.
type StreamWriter func(w *bufio.Writer)
// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.Reader {
pr, pw := io.Pipe()
var bw *bufio.Writer
v := streamWriterBufPool.Get()
if v == nil {
bw = bufio.NewWriter(pw)
} else {
bw = v.(*bufio.Writer)
bw.Reset(pw)
}
go func() {
defer func() {
if r := recover(); r != nil {
defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
}
}()
sw(bw)
bw.Flush()
pw.Close()
streamWriterBufPool.Put(bw)
}()
return pr
}
var streamWriterBufPool sync.Pool
|
Update tonic example for new API
|
var jss = require('jss');
var extend = require('jss-extend');
var nested = require('jss-nested');
var camelCase = require('jss-camel-case');
var defaultUnit = require('jss-default-unit');
var perdido = require('perdido');
jss.use(extend());
jss.use(nested());
jss.use(camelCase());
jss.use(defaultUnit());
var testGrid = {
article: {
extend: perdido.flexContainer('row'),
'& div': {
extend: perdido.column('1/3'),
},
},
};
var styleSheet = jss.createStyleSheet(testGrid, {named: false});
styleSheet.toString();
var perdidoFlex = perdido.create('30px', {flex: true});
perdido.flex = true;
var testGrid2 = {
article: {
extend: perdidoFlex.flexContainer('row'),
'& div': {
extend: perdidoFlex.column('1/3'),
},
},
};
var styleSheet2 = jss.createStyleSheet(testGrid2, {named: false});
styleSheet2.toString();
|
var jss = require('jss');
var extend = require('jss-extend');
var nested = require('jss-nested');
var camelCase = require('jss-camel-case');
var defaultUnit = require('jss-default-unit');
var perdido = require('perdido');
jss.use(extend());
jss.use(nested());
jss.use(camelCase());
jss.use(defaultUnit());
var testGrid = {
article: {
extend: perdido.flexContainer('row'),
'& div': {
extend: perdido.column('1/3'),
},
},
};
var styleSheet = jss.createStyleSheet(testGrid, {named: false});
styleSheet.toString();
perdido = perdido.create('30px', true);
perdido.flex = true;
var testGrid2 = {
article: {
extend: perdido.flexContainer('row'),
'& div': {
extend: perdido.column('1/3'),
},
},
};
var styleSheet2 = jss.createStyleSheet(testGrid2, {named: false});
styleSheet2.toString();
|
Fix token types for comments in SOM
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
|
package som.langserv.som;
import java.util.ArrayList;
import java.util.List;
import som.langserv.SemanticTokenType;
import trufflesom.compiler.Lexer;
public class SomLexer extends Lexer {
private List<Integer> commentTokens = new ArrayList<Integer>();
protected SomLexer(final String content) {
super(content);
}
@Override
protected void skipComment() {
if (currentChar() == '"') {
int length = 0;
int col = state.ptr - state.lastLineEnd;
do {
length++;
if (currentChar() == '\n') {
addCoordsToTokens(state.lineNumber - 1, 0, length);
state.lineNumber += 1;
state.lastLineEnd = state.ptr;
length = 0;
}
state.incPtr();
} while (currentChar() != '"');
addCoordsToTokens(state.lineNumber - 1, col - 1, length + 1);
state.incPtr();
}
}
private void addCoordsToTokens(final int line, final int col, final int length) {
commentTokens.add(line);
commentTokens.add(col);
commentTokens.add(length);
commentTokens.add(SemanticTokenType.COMMENT.ordinal()); // token type
commentTokens.add(0); // token modifiers
}
public List<Integer> getCommentsPositions() {
return commentTokens;
}
}
|
package som.langserv.som;
import java.util.ArrayList;
import java.util.List;
import trufflesom.compiler.Lexer;
public class SomLexer extends Lexer {
private List<Integer> commentTokens = new ArrayList<Integer>();
protected SomLexer(final String content) {
super(content);
}
@Override
protected void skipComment() {
if (currentChar() == '"') {
int length = 0;
int col = state.ptr - state.lastLineEnd;
do {
length++;
if (currentChar() == '\n') {
addCoordsToTokens(state.lineNumber - 1, 0, length);
state.lineNumber += 1;
state.lastLineEnd = state.ptr;
length = 0;
}
state.incPtr();
} while (currentChar() != '"');
addCoordsToTokens(state.lineNumber - 1, col - 1, length + 1);
state.incPtr();
}
}
private void addCoordsToTokens(final int line, final int col, final int length) {
commentTokens.add(line);
commentTokens.add(col);
commentTokens.add(length);
commentTokens.add(5);
commentTokens.add(0);
}
public List<Integer> getCommentsPositions() {
return commentTokens;
}
}
|
Make status the last optional arg.
|
from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
|
from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
|
Fix eslint errors in leaderboard.js
|
'use strict'
let RatView = Marionette.ItemView.extend({
tagName: 'tr',
template: Handlebars.compile(
'<td>{{CMDRname}}</td>' +
'<td>{{successfulRescueCount}}</td>'
)
})
Marionette.CompositeView.extend({
childView: RatView,
childViewContainer: 'tbody',
className: 'card',
initialize: function () {
$(window).on('resize', this.render)
this.listenTo(this.model, 'change', this.render)
},
onRender: function () {},
tagName: 'div',
template: Handlebars.compile(
'<div class="card-header">' +
'Leaderboard' +
'</div>' +
'<table id="leaderboard" class="table table-hover table-striped">' +
'<thead>' +
'<tr>' +
'<th>CMDR</th>' +
'<th>Rescues</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'</tbody>' +
'</table>'
)
})
|
var LeaderboardView, RatView
RatView = Marionette.ItemView.extend({
tagName: 'tr',
template: Handlebars.compile(
'<td>{{CMDRname}}</td>' +
'<td>{{successfulRescueCount}}</td>'
)
})
LeaderboardView = Marionette.CompositeView.extend({
childView: RatView,
childViewContainer: 'tbody',
className: 'card',
initialize: function () {
$(window).on('resize', this.render)
this.listenTo(this.model, 'change', this.render)
},
onRender: function () {},
tagName: 'div',
template: Handlebars.compile(
'<div class="card-header">' +
'Leaderboard' +
'</div>' +
'<table id="leaderboard" class="table table-hover table-striped">' +
'<thead>' +
'<tr>' +
'<th>CMDR</th>' +
'<th>Rescues</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'</tbody>' +
'</table>'
)
})
|
Remove unnecessary operation when sorting users
|
var _ = require("lodash");
module.exports = Chan;
Chan.Type = {
CHANNEL: "channel",
LOBBY: "lobby",
QUERY: "query"
};
var id = 0;
function Chan(attr) {
_.merge(this, _.extend({
id: id++,
messages: [],
name: "",
topic: "",
type: Chan.Type.CHANNEL,
unread: 0,
users: []
}, attr));
}
Chan.prototype.sortUsers = function() {
this.users = _.sortBy(
this.users,
function(u) { return u.name.toLowerCase(); }
);
["+", "%", "@", "&", "~"].forEach(function(mode) {
this.users = _.remove(
this.users,
function(u) { return u.mode === mode; }
).concat(this.users);
}, this);
};
Chan.prototype.getMode = function(name) {
var user = _.find(this.users, {name: name});
if (user) {
return user.mode;
} else {
return "";
}
};
Chan.prototype.toJSON = function() {
var clone = _.clone(this);
clone.messages = clone.messages.slice(-100);
return clone;
};
|
var _ = require("lodash");
module.exports = Chan;
Chan.Type = {
CHANNEL: "channel",
LOBBY: "lobby",
QUERY: "query"
};
var id = 0;
function Chan(attr) {
_.merge(this, _.extend({
id: id++,
messages: [],
name: "",
topic: "",
type: Chan.Type.CHANNEL,
unread: 0,
users: []
}, attr));
}
Chan.prototype.sortUsers = function() {
this.users = _.sortBy(
this.users,
function(u) { return u.name.toLowerCase(); }
);
var modes = [
"~",
"&",
"@",
"%",
"+",
].reverse();
modes.forEach(function(mode) {
this.users = _.remove(
this.users,
function(u) { return u.mode === mode; }
).concat(this.users);
}, this);
};
Chan.prototype.getMode = function(name) {
var user = _.find(this.users, {name: name});
if (user) {
return user.mode;
} else {
return "";
}
};
Chan.prototype.toJSON = function() {
var clone = _.clone(this);
clone.messages = clone.messages.slice(-100);
return clone;
};
|
Use variable for key name
|
/*
Copyright 2016 OpenMarket Ltd
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.
*/
var DEFAULTS = {
};
class SdkConfig {
static get() {
return global.mxReactSdkConfig;
}
static put(cfg) {
var defaultKeys = Object.keys(DEFAULTS);
for (var i = 0; i < defaultKeys.length; ++i) {
var key = defaultKeys[i];
if (cfg[key] === undefined) {
cfg[key] = DEFAULTS[key];
}
}
global.mxReactSdkConfig = cfg;
}
static unset() {
global.mxReactSdkConfig = undefined;
}
}
module.exports = SdkConfig;
|
/*
Copyright 2016 OpenMarket Ltd
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.
*/
var DEFAULTS = {
};
class SdkConfig {
static get() {
return global.mxReactSdkConfig;
}
static put(cfg) {
var defaultKeys = Object.keys(DEFAULTS);
for (var i = 0; i < defaultKeys.length; ++i) {
if (cfg[defaultKeys[i]] === undefined) {
cfg[defaultKeys[i]] = DEFAULTS[defaultKeys[i]];
}
}
global.mxReactSdkConfig = cfg;
}
static unset() {
global.mxReactSdkConfig = undefined;
}
}
module.exports = SdkConfig;
|
Hide logger from outside of the package
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from tabledata import DataError, InvalidHeaderNameError, InvalidTableNameError
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._constant import PatternMatch
from ._logger import set_log_level, set_logger
from .csv.core import CsvTableFileLoader, CsvTableTextLoader
from .error import (
APIError,
HTTPError,
InvalidFilePathError,
LoaderNotFoundError,
OpenError,
PathError,
ProxyError,
PypandocImportError,
UrlError,
ValidationError,
)
from .html.core import HtmlTableFileLoader, HtmlTableTextLoader
from .json.core import JsonTableDictLoader, JsonTableFileLoader, JsonTableTextLoader
from .jsonlines.core import JsonLinesTableFileLoader, JsonLinesTableTextLoader
from .loadermanager import TableFileLoader, TableUrlLoader
from .ltsv.core import LtsvTableFileLoader, LtsvTableTextLoader
from .markdown.core import MarkdownTableFileLoader, MarkdownTableTextLoader
from .mediawiki.core import MediaWikiTableFileLoader, MediaWikiTableTextLoader
from .spreadsheet.excelloader import ExcelTableFileLoader
from .spreadsheet.gsloader import GoogleSheetsTableLoader
from .sqlite.core import SqliteFileLoader
from .tsv.core import TsvTableFileLoader, TsvTableTextLoader
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from tabledata import DataError, InvalidHeaderNameError, InvalidTableNameError
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._constant import PatternMatch
from ._logger import logger, set_log_level, set_logger
from .csv.core import CsvTableFileLoader, CsvTableTextLoader
from .error import (
APIError,
HTTPError,
InvalidFilePathError,
LoaderNotFoundError,
OpenError,
PathError,
ProxyError,
PypandocImportError,
UrlError,
ValidationError,
)
from .html.core import HtmlTableFileLoader, HtmlTableTextLoader
from .json.core import JsonTableDictLoader, JsonTableFileLoader, JsonTableTextLoader
from .jsonlines.core import JsonLinesTableFileLoader, JsonLinesTableTextLoader
from .loadermanager import TableFileLoader, TableUrlLoader
from .ltsv.core import LtsvTableFileLoader, LtsvTableTextLoader
from .markdown.core import MarkdownTableFileLoader, MarkdownTableTextLoader
from .mediawiki.core import MediaWikiTableFileLoader, MediaWikiTableTextLoader
from .spreadsheet.excelloader import ExcelTableFileLoader
from .spreadsheet.gsloader import GoogleSheetsTableLoader
from .sqlite.core import SqliteFileLoader
from .tsv.core import TsvTableFileLoader, TsvTableTextLoader
|
Use the PlaygroundQuickLook(reflecting:) constructor in this test case
|
# TestREPLQuickLookObject.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('PlaygroundQuickLook(reflecting: true)', patterns=['Logical = true'])
self.command('PlaygroundQuickLook(reflecting: 1.25)', patterns=['Double = 1.25'])
self.command('PlaygroundQuickLook(reflecting: Float(1.25))', patterns=['Float = 1.25'])
self.command('PlaygroundQuickLook(reflecting: "Hello")', patterns=['Text = \"Hello\"'])
|
# TestREPLQuickLookObject.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('true.customPlaygroundQuickLook()', patterns=['Logical = true'])
self.command('1.25.customPlaygroundQuickLook()', patterns=['Double = 1.25'])
self.command('Float(1.25).customPlaygroundQuickLook()', patterns=['Float = 1.25'])
self.command('"Hello".customPlaygroundQuickLook()', patterns=['Text = \"Hello\"'])
|
Fix functions into Session class
|
<?php
/*
----------------------------------------------------------------------
FusionInventory
Copyright (C) 2010-2011 by the FusionInventory Development Team.
http://www.fusioninventory.org/ http://forge.fusioninventory.org/
----------------------------------------------------------------------
LICENSE
This file is part of FusionInventory.
FusionInventory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
FusionInventory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Original Author of file: David DURIEUX
Co-authors of file:
Purpose of file:
----------------------------------------------------------------------
*/
if (strpos($_SERVER['PHP_SELF'],"showporthistory.php")) {
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/inc/includes.php");
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
}
if (!defined('GLPI_ROOT')) {
die("Can not acces directly to this file");
}
Session::checkCentralAccess();
echo PluginFusinvsnmpNetworkPortLog::showHistory($_POST["ports_id"]);
?>
|
<?php
/*
----------------------------------------------------------------------
FusionInventory
Copyright (C) 2010-2011 by the FusionInventory Development Team.
http://www.fusioninventory.org/ http://forge.fusioninventory.org/
----------------------------------------------------------------------
LICENSE
This file is part of FusionInventory.
FusionInventory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
FusionInventory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Original Author of file: David DURIEUX
Co-authors of file:
Purpose of file:
----------------------------------------------------------------------
*/
if (strpos($_SERVER['PHP_SELF'],"showporthistory.php")) {
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/inc/includes.php");
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
}
if (!defined('GLPI_ROOT')) {
die("Can not acces directly to this file");
}
checkCentralAccess();
echo PluginFusinvsnmpNetworkPortLog::showHistory($_POST["ports_id"]);
?>
|
Fix no message attribute in exception
For py35, message attribute in exception seems removed.
We should directly get the string message from exception object
if message attribute not presented. And since get message attribute
already been deprecated. We should remove sopport on
exception.message after we fully jump to py35.
Partial-Bug: #1704725
Change-Id: I3970aa7c161aa82d179779f1a2f46405d5b0dddb
|
#
# 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.
from oslo_log import log as logging
import six
LOG = logging.getLogger(__name__)
def log_fail_msg(manager, entrypoint, exception):
LOG.warning('Encountered exception while loading %(module_name)s: '
'"%(message)s". Not using %(name)s.',
{'module_name': entrypoint.module_name,
'message': getattr(exception, 'message',
six.text_type(exception)),
'name': entrypoint.name})
|
#
# 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.
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def log_fail_msg(manager, entrypoint, exception):
LOG.warning('Encountered exception while loading %(module_name)s: '
'"%(message)s". Not using %(name)s.',
{'module_name': entrypoint.module_name,
'message': exception.message,
'name': entrypoint.name})
|
Fix the mock Service to implement "Debug" also.
|
package mocks
import "time"
type Service struct {
URLCall struct {
ReturnURL string
Err error
}
StartCall struct {
Called bool
Err error
}
StopCall struct {
Called bool
Err error
}
WaitForBootCall struct {
Timeout time.Duration
Err error
}
}
func (s *Service) URL() (string, error) {
return s.URLCall.ReturnURL, s.URLCall.Err
}
func (s *Service) Start() error {
s.StartCall.Called = true
return s.StartCall.Err
}
func (s *Service) Stop() error {
s.StopCall.Called = true
return s.StopCall.Err
}
func (s *Service) WaitForBoot(timeout time.Duration) error {
s.WaitForBootCall.Timeout = timeout
return s.WaitForBootCall.Err
}
func (s *Service) Debug(state bool) {
}
|
package mocks
import "time"
type Service struct {
URLCall struct {
ReturnURL string
Err error
}
StartCall struct {
Called bool
Err error
}
StopCall struct {
Called bool
Err error
}
WaitForBootCall struct {
Timeout time.Duration
Err error
}
}
func (s *Service) URL() (string, error) {
return s.URLCall.ReturnURL, s.URLCall.Err
}
func (s *Service) Start() error {
s.StartCall.Called = true
return s.StartCall.Err
}
func (s *Service) Stop() error {
s.StopCall.Called = true
return s.StopCall.Err
}
func (s *Service) WaitForBoot(timeout time.Duration) error {
s.WaitForBootCall.Timeout = timeout
return s.WaitForBootCall.Err
}
|
Use proxy methods for getPrecision() and getRecall().
|
package edu.ntnu.idi.goldfish;
import org.apache.mahout.cf.taste.eval.IRStatistics;
public class Result {
String recommender;
// RMSE
double RMSE;
//
double AAD;
// IR stats (precision, recall)
IRStatistics irStats;
public Result(String recommender, double RMSE, double AAD, IRStatistics irStats) {
this.recommender = recommender;
// NaN is messing up sorting, so we overwrite it
if(Double.isNaN(RMSE)) RMSE = 10;
this.RMSE = RMSE;
this.AAD = AAD;
this.irStats = irStats;
}
public String toString() {
return String.format("%-40s | RMSE: %6.3f | AAD: %6.3f | Precision: %6.3f | Recall %6.3f", recommender, RMSE, AAD, getPrecision(), getRecall());
}
public String toCSV() {
return String.format("%s,%.3f,%.3f,%.3f,%.3f", recommender, RMSE, AAD, getPrecision(), getRecall());
}
public double getPrecision() {
return irStats.getPrecision();
}
public double getRecall() {
return irStats.getRecall();
}
}
|
package edu.ntnu.idi.goldfish;
import org.apache.mahout.cf.taste.eval.IRStatistics;
public class Result {
String recommender;
// RMSE
double RMSE;
//
double AAD;
// IR stats (precision, recall)
IRStatistics irStats;
public Result(String recommender, double RMSE, double AAD, IRStatistics irStats) {
this.recommender = recommender;
// NaN is messing up sorting, so we overwrite it
if(Double.isNaN(RMSE)) RMSE = 10;
this.RMSE = RMSE;
this.AAD = AAD;
this.irStats = irStats;
}
public String toString() {
return String.format("%-40s | RMSE: %6.3f | AAD: %6.3f | Precision: %6.3f | Recall %6.3f", recommender, RMSE, AAD, irStats.getPrecision(), irStats.getRecall());
}
public String toCSV() {
return String.format("%s,%.3f,%.3f,%.3f,%.3f", recommender, RMSE, AAD, irStats.getPrecision(), irStats.getRecall());
}
public double getPrecision() {
return irStats.getPrecision();
}
public double getRecall() {
return irStats.getRecall();
}
}
|
Add json5 and toml to supported formats, add Python 3.5 to supported Python versions
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='anymarkup-core',
version='0.6.2',
description='Core library for anymarkup',
long_description=''.join(open('README.rst').readlines()),
keywords='xml, yaml, toml, json, json5, ini',
author='Slavek Kabrda',
author_email='slavek.kabrda@gmail.com',
url='https://github.com/bkabrda/anymarkup-core',
license='BSD',
packages=['anymarkup_core'],
install_requires=open('requirements.txt').read().splitlines(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='anymarkup-core',
version='0.6.2',
description='Core library for anymarkup',
long_description=''.join(open('README.rst').readlines()),
keywords='xml, yaml, json, ini',
author='Slavek Kabrda',
author_email='slavek.kabrda@gmail.com',
url='https://github.com/bkabrda/anymarkup-core',
license='BSD',
packages=['anymarkup_core'],
install_requires=open('requirements.txt').read().splitlines(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
]
)
|
Rename form BucketlistItem to Activity
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
username = StringField("Username", validators=[DataRequired(), Length(2, 32)])
password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)])
class LoginForm(FlaskForm):
"""Form to let users login"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)])
remember = BooleanField("Remember Me")
class BucketlistForm(FlaskForm):
"""Form to CRUd a bucketlist"""
name = StringField("Name", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
class ActivityForm(FlaskForm):
"""Form to CRUd a bucketlist item"""
title = StringField("Title", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
status = BooleanField("Status")
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
username = StringField("Username", validators=[DataRequired(), Length(2, 32)])
password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)])
class LoginForm(FlaskForm):
"""Form to let users login"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)])
password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)])
remember = BooleanField("Remember Me")
class BucketlistForm(FlaskForm):
"""Form to CRUd a bucketlist"""
name = StringField("Name", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
class BucketlistItemForm(FlaskForm):
"""Form to CRUd a bucketlist item"""
title = StringField("Title", validators=[DataRequired()])
description = TextAreaField("Description", validators=[DataRequired()])
status = BooleanField("Status")
|
Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
Allow for 2nd argument to be destination filename
|
#!/usr/bin/env node
require('coffee-script').register()
var fs = require('fs'),
indentation = require('../lib/indentation'),
buf, emblemFile, hbsFile, output;
if (process.argv.length < 3) {
if (process.stdin.isTTY) {
console.log('USAGE: emblem2hbs filetoconvert.emblem or in piped format `pbcopy | emblem2hbs | pbpaste`');
}
else {
processFromPipe();
}
} else {
emblemFile = process.argv[2];
hbsFile = process.argv[3] ? process.argv[3] : emblemFile.substr(0, emblemFile.lastIndexOf('.')) + '.hbs';
buf = fs.readFileSync(emblemFile, 'utf8');
output = require('emblem').default.compile(buf);
fs.writeFileSync(hbsFile, indentation.indent(output));
}
function processFromPipe() {
var input = process.stdin;
var output = process.stdout;
var error = null;
var data = '';
input.setEncoding('utf8');
input.on('data', function(chunk){
data += chunk;
});
input.on('end', function(){
var converted = require('emblem').default.compile(data);
output.end(indentation.indent(converted));
});
output.on('error', function(err) {
error = err;
});
}
|
#!/usr/bin/env node
require('coffee-script').register()
var fs = require('fs'),
indentation = require('../lib/indentation'),
buf, emblemFile, hbsFile, output;
if (process.argv.length < 3) {
if (process.stdin.isTTY) {
console.log('USAGE: emblem2hbs filetoconvert.emblem or in piped format `pbcopy | emblem2hbs | pbpaste`');
return;
}
else {
processFromPipe();
}
} else {
emblemFile = process.argv[2];
hbsFile = emblemFile.substr(0, emblemFile.lastIndexOf('.')) + '.hbs';
buf = fs.readFileSync(emblemFile, 'utf8');
output = require('emblem').default.compile(buf);
fs.writeFileSync(hbsFile, indentation.indent(output));
}
function processFromPipe() {
var input = process.stdin;
var output = process.stdout;
var error = null;
var data = '';
input.setEncoding('utf8');
input.on('data', function(chunk){
data += chunk;
});
input.on('end', function(){
var converted = require('emblem').default.compile(data);
output.end(indentation.indent(converted));
});
output.on('error', function(err) {
error = err;
});
}
|
Fix incorrect dotenv path fallback
|
/* eslint-disable import/no-dynamic-require,global-require */
import fs from 'fs';
import path from 'path';
import log from 'fancy-log';
import dotenv from 'dotenv';
import config from './lib/config';
/**
* Update `cwd` if `package.json` is a symlink.
*/
const packageLocation = fs.realpathSync(path.resolve(process.cwd(), 'package.json'));
const realPath = path.dirname(packageLocation);
if (process.cwd() !== realPath) {
try {
process.chdir(realPath);
} catch (error) {
log.error(`Unable to switch to symbolic directory: ${error}`);
process.exit(1);
}
}
/**
* Load environment variables from `.env`.
*/
dotenv.config({ path: config.get('dotenv.file') || `${process.cwd()}/.env` });
/**
* Gulp tasks are defined in separate files in the tasks folder.
*/
const taskFolder = path.join(__dirname, 'tasks');
fs.readdirSync(taskFolder)
.filter(name => /(\.(js)$)/i.test(path.extname(name)))
.forEach(task => require(path.join(taskFolder, task)));
/**
* Custom `SIGINT` listener to exit process.
*/
process.on('SIGINT', e => process.exit(1));
|
/* eslint-disable import/no-dynamic-require,global-require */
import fs from 'fs';
import path from 'path';
import log from 'fancy-log';
import dotenv from 'dotenv';
import config from './lib/config';
/**
* Update `cwd` if `package.json` is a symlink.
*/
const packageLocation = fs.realpathSync(path.resolve(process.cwd(), 'package.json'));
const realPath = path.dirname(packageLocation);
if (process.cwd() !== realPath) {
try {
process.chdir(realPath);
} catch (error) {
log.error(`Unable to switch to symbolic directory: ${error}`);
process.exit(1);
}
}
/**
* Load environment variables from `.env`.
*/
dotenv.config({ path: config.get('dotenv.file') || process.cwd() });
/**
* Gulp tasks are defined in separate files in the tasks folder.
*/
const taskFolder = path.join(__dirname, 'tasks');
fs.readdirSync(taskFolder)
.filter(name => /(\.(js)$)/i.test(path.extname(name)))
.forEach(task => require(path.join(taskFolder, task)));
/**
* Custom `SIGINT` listener to exit process.
*/
process.on('SIGINT', e => process.exit(1));
|
Enable passing custom columns to be serialized
|
'use strict';
const p = require('path');
const _ = require('lodash');
const passport = require('passport');
// const User = require('../services/users/model');
const config = require(p.join(process.cwd(), 'server/config/membership'));
let serializeUser;
let deserializeUser;
const pick = ['id', 'username', 'email', 'roles'];
if (typeof config.serializeUser === 'function') {
serializeUser = config.serializeUser;
}
if (Array.isArray(config.serializeColumns)) {
pick.push(...config.serializeColumns);
}
// if (typeof config.serializeUser === 'function') {
// if (config.serializeUser.length === 1) {
// serializeUser = config.serializeUser(User);
// } else {
// serializeUser = config.serializeUser;
// }
// }
// if (typeof config.deserializeUser === 'function') {
// if (config.deserializeUser.length === 1) {
// deserializeUser = config.deserializeUser(User);
// } else {
// deserializeUser = config.deserializeUser;
// }
// }
// used to serialize the user for the session
passport.serializeUser(serializeUser || ((user, done) => {
done(null, _.pick(user, pick));
}));
// used to deserialize the user
passport.deserializeUser(deserializeUser || ((user, done) => {
done(null, user);
}));
require('./req');
require('./strategies');
|
'use strict';
// const p = require('path');
const _ = require('lodash');
const passport = require('passport');
// const User = require('../services/users/model');
// const config = require(p.join(process.cwd(), 'server/config/membership'));
let serializeUser;
let deserializeUser;
// if (typeof config.serializeUser === 'function') {
// if (config.serializeUser.length === 1) {
// serializeUser = config.serializeUser(User);
// } else {
// serializeUser = config.serializeUser;
// }
// }
// if (typeof config.deserializeUser === 'function') {
// if (config.deserializeUser.length === 1) {
// deserializeUser = config.deserializeUser(User);
// } else {
// deserializeUser = config.deserializeUser;
// }
// }
// used to serialize the user for the session
passport.serializeUser(serializeUser || ((user, done) => {
done(null, _.pick(user, ['id', 'username', 'email', 'roles']));
}));
// used to deserialize the user
passport.deserializeUser(deserializeUser || ((user, done) => {
done(null, user);
// User.findById(user, (err, user) => {
// done(err, user);
// });
}));
require('./req');
require('./strategies');
|
Switch tests back to tinkerpop graph api
|
package com.gentics.mesh.test;
import javax.annotation.PostConstruct;
import org.elasticsearch.node.Node;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.gentics.mesh.cli.Mesh;
import com.gentics.mesh.etc.config.MeshOptions;
import com.gentics.mesh.graphdb.TinkerGraphDatabaseProviderImpl;
@Configuration
@ComponentScan(basePackages = { "com.gentics.mesh" })
public class SpringTestConfiguration {
@Bean
public String graphProviderClassname() {
return TinkerGraphDatabaseProviderImpl.class.getName();
//return OrientDBDatabaseProviderImpl.class.getName();
// return TitanDBDatabaseProviderImpl.class.getName();
}
@Bean
public Node elasticSearchNode() {
// For testing it is not needed to start ES in most cases. This will speedup test execution since ES does not need to initialize.
return null;
}
@PostConstruct
public void setup() {
MeshOptions options = new MeshOptions();
options.setDatabaseProviderClass(graphProviderClassname());
options.setHttpPort(TestUtil.getRandomPort());
Mesh.initalize(options);
}
}
|
package com.gentics.mesh.test;
import javax.annotation.PostConstruct;
import org.elasticsearch.node.Node;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.gentics.mesh.cli.Mesh;
import com.gentics.mesh.etc.config.MeshOptions;
import com.gentics.mesh.graphdb.OrientDBDatabaseProviderImpl;
@Configuration
@ComponentScan(basePackages = { "com.gentics.mesh" })
public class SpringTestConfiguration {
@Bean
public String graphProviderClassname() {
// return TinkerGraphDatabaseProviderImpl.class.getName();
return OrientDBDatabaseProviderImpl.class.getName();
// return TitanDBDatabaseProviderImpl.class.getName();
}
@Bean
public Node elasticSearchNode() {
// For testing it is not needed to start ES in most cases. This will speedup test execution since ES does not need to initialize.
return null;
}
@PostConstruct
public void setup() {
MeshOptions options = new MeshOptions();
options.setDatabaseProviderClass(graphProviderClassname());
options.setHttpPort(TestUtil.getRandomPort());
Mesh.initalize(options);
}
}
|
Add a text vs number composite statement example
|
import Local
import Global
"Global.x:" <input data=Global.x dataType="number" style={ display:'block' }/>
"Global.y:" <input data=Global.y dataType="number" style={ display:'block' }/>
let five = 5,
two = 2,
greeting = "hello ",
name = "world"
<table>
<tr>
<th>"Global.x + Global.y"</th>
Global.x + Global.y
</tr><tr>
<th>"Global.x * Global.y + Global.x * five"</th>
Global.x * Global.y + Global.x * five
</tr><tr>
<th>"five + 2 * Global.x"</th>
five + 2 * Global.x
</tr><tr>
<th>"two - 3 / Global.y"</th>
two - 3 / Global.y
</tr><tr>
<th>"greeting + name"</th>
greeting + name
</tr>
</table>
<br />"Numbers: "
<input data=Local.x dataType="number" /> "+" <input data=Local.y dataType="number" /> "=" Local.x + Local.y
<br />"Strings: "
<input data=Local.foo /> "+" <input data=Local.bar /> "=" Local.foo + Local.bar
|
import Local
import Global
"Global.x:" <input data=Global.x dataType="number" style={ display:'block' }/>
"Global.y:" <input data=Global.y dataType="number" style={ display:'block' }/>
let five = 5,
two = 2,
greeting = "hello ",
name = "world"
<table>
<tr>
<th>"Global.x + Global.y"</th>
Global.x + Global.y
</tr><tr>
<th>"Global.x * Global.y + Global.x * five"</th>
Global.x * Global.y + Global.x * five
</tr><tr>
<th>"five + 2 * Global.x"</th>
five + 2 * Global.x
</tr><tr>
<th>"two - 3 / Global.y"</th>
two - 3 / Global.y
</tr><tr>
<th>"greeting + name"</th>
greeting + name
</tr>
</table>
|
Fix the condition when a monster has no flags.
|
<?php
class Monster implements Robbo\Presenter\PresentableInterface
{
use MagicModel;
protected $data;
public function load($data)
{
$this->data = $data;
}
public function getPresenter()
{
return new Presenters\Monster($this);
}
public function getMinDamage()
{
return $this->melee_dice+$this->melee_cut;
}
public function getMaxDamage()
{
return ($this->melee_dice*$this->melee_dice_sides)+$this->melee_cut;
}
public function getAvgDamage()
{
return ($this->minDamage+$this->maxDamage)/2;
}
public function getSpecies()
{
return (array) $this->data->species;
}
public function getFlags()
{
if(!isset($this->data->flags))
return array();
return (array) $this->data->flags;
}
public function getId()
{
return $this->data->id;
}
}
|
<?php
class Monster implements Robbo\Presenter\PresentableInterface
{
use MagicModel;
protected $data;
public function load($data)
{
$this->data = $data;
}
public function getPresenter()
{
return new Presenters\Monster($this);
}
public function getMinDamage()
{
return $this->melee_dice+$this->melee_cut;
}
public function getMaxDamage()
{
return ($this->melee_dice*$this->melee_dice_sides)+$this->melee_cut;
}
public function getAvgDamage()
{
return ($this->minDamage+$this->maxDamage)/2;
}
public function getSpecies()
{
return (array) $this->data->species;
}
public function getFlags()
{
return (array) $this->data->flags;
}
public function getId()
{
return $this->data->id;
}
}
|
Change package name to 'cirm' to avoid confusion.
|
#
# Copyright 2012 University of Southern California
#
# 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.
#
from distutils.core import setup
setup(name="cirm-rest",
description="cirm web application",
version="0.1",
package_dir={"": "src"},
packages=["cirm"],
requires=["web.py", "psycopg2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
#
# Copyright 2012 University of Southern California
#
# 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.
#
from distutils.core import setup
setup(name="cirm-rest",
description="cirm web application",
version="0.1",
package_dir={"": "src"},
packages=["cirmrest"],
requires=["web.py", "psycopg2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Adjust import statements to be sorted
|
from ..auth_provider import KnowledgeAuthProvider
from ..models import User
from ..utils.auth import is_safe_url
import flask
from flask import (
flash,
redirect,
render_template,
request,
url_for,
)
from flask_login import login_user
class DebugAuthProvider(KnowledgeAuthProvider):
_registry_keys = ['debug']
def prompt(self):
if request.method == 'POST':
user = request.form['username']
login_user(User(identifier=user))
flash('Logged in successfully.')
next = request.args.get('next')
# is_safe_url should check if the url is safe for redirects.
# See http://flask.pocoo.org/snippets/62/ for an example.
if not is_safe_url(next):
return flask.abort(400)
return redirect(next or url_for('index.render_feed'))
return render_template('auth-login-form.html', skip_password=True)
def get_user(self):
return User(identifier=request.form['username'])
|
import flask
from flask import request, render_template, flash, redirect, url_for
from flask_login import login_user
from ..models import User
from ..utils.auth import is_safe_url
from ..auth_provider import KnowledgeAuthProvider
class DebugAuthProvider(KnowledgeAuthProvider):
_registry_keys = ['debug']
def prompt(self):
if request.method == 'POST':
user = request.form['username']
login_user(User(identifier=user))
flash('Logged in successfully.')
next = request.args.get('next')
# is_safe_url should check if the url is safe for redirects.
# See http://flask.pocoo.org/snippets/62/ for an example.
if not is_safe_url(next):
return flask.abort(400)
return redirect(next or url_for('index.render_feed'))
return render_template('auth-login-form.html', skip_password=True)
def get_user(self):
return User(identifier=request.form['username'])
|
Add a newline before @param (again)
Co-authored-by: Zach Ghera <7d293d7aa3d73ce243886706f2742c0d78eb864e@gmail.com>
|
/**
* Format a timestamp (in milliseconds) into a pretty string with just the time.
*
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "10:19 AM".
*/
export function timestampToTimeFormatted(msTimestamp, timezone = "America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
hour: 'numeric',
minute: '2-digit',
timeZone: timezone
};
let formatted = date.toLocaleTimeString('en-US', formatOptions);
return formatted;
}
/**
* Format a timestamp (in milliseconds) into a pretty string with just the date.
*
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "Monday, January 19, 1970".
*/
export function timestampToDateFormatted(msTimestamp, timezone="America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: timezone
};
let formatted = date.toLocaleDateString('en-US', formatOptions);
return formatted;
}
|
/**
* Format a timestamp (in milliseconds) into a pretty string with just the time.
*
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "10:19 AM".
*/
export function timestampToTimeFormatted(msTimestamp, timezone = "America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
hour: 'numeric',
minute: '2-digit',
timeZone: timezone
};
let formatted = date.toLocaleTimeString('en-US', formatOptions);
return formatted;
}
/**
* Format a timestamp (in milliseconds) into a pretty string with just the date.
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "Monday, January 19, 1970".
*/
export function timestampToDateFormatted(msTimestamp, timezone="America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: timezone
};
let formatted = date.toLocaleDateString('en-US', formatOptions);
return formatted;
}
|
Update foundation asset and fixed minor html syntax error.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{{ HTML::title() }}</title>
<?php
$asset = Asset::container('cello.frontend');
$asset->style('foundation', 'bundles/orchestra/vendor/foundation/css/foundation.min.css');
$asset->script('foundation', 'bundles/orchestra/vendor/foundation/js/foundation.min.js'); ?>
{{ $asset->styles() }}
{{ $asset->scripts() }}
</head>
<body>
<div class="row">
<div class="twelve columns">
<h2>{{ memorize('site.name') }}</h2>
<p>{{ memorize('site.description') }}</p>
<hr />
</div>
</div>
@yield('content')
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{{ HTML::title() }}</title>
<?php
$asset = Asset::container('cello.frontend');
$asset->style('foundation', 'bundles/orchestra/vendor/foundation/stylesheets/foundation.min.css');
$asset->script('foundation', 'bundles/orchestra/vendor/foundation/javascripts/foundation.min.js'); ?>
{{ $asset->styles() }}
{{ $asset->scripts() }}
</head>
<body>
<div class="row">
<div class="twelve columns">
<h2>{{ memorize('site.name') }}<h2>
<p>{{ memorize('site.description') }}</p>
<hr />
</div>
</div>
@yield('content')
</body>
</html>
|
Use 3.3 api for redirects
|
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User extends Controller_Website
{
public function action_logout()
{
Auth::instance()->logout(TRUE);
$this->redirect(url::site());
}
public function action_login()
{
$this->template->title = 'Login - ';
$this->template->content = View::factory('user/login');
}
public function action_process_login()
{
$auth = Auth::instance();
if ($auth->login($_POST['username'], $_POST['password']))
{
$this->redirect('admin');
}
else
{
Notices::add('error', 'Incorrect username or password.');
$this->redirect('user/login');
}
}
}
|
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User extends Controller_Website
{
public function action_logout()
{
Auth::instance()->logout(TRUE);
$this->request->redirect(url::site());
}
public function action_login()
{
$this->template->title = 'Login - ';
$this->template->content = View::factory('user/login');
}
public function action_process_login()
{
$auth = Auth::instance();
if ($auth->login($_POST['username'], $_POST['password']))
{
$this->request->redirect('admin');
}
else
{
Notices::add('error', 'Incorrect username or password.');
$this->request->redirect('user/login');
}
}
}
|
Fix CTRL-ALT-DEL button on Spice consoles
Appears that the current Spice JS library requires polluting the global namespace for this feature to work.
https://github.com/himdel/spice-html5-bower/blob/master/spiceHTML5/TODO#L28
https://bugzilla.redhat.com/show_bug.cgi?id=1491387
|
//= require jquery
//= require spice-html5-bower
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
$('#ctrlaltdel').click(sendCtrlAltDel);
sc = new SpiceMainConn({
uri: (encrypt ? 'wss://' : 'ws://') + host + ':' + port + '/' + $('#remote-console').attr('data-url'),
screen_id: "remote-console",
password: $('#remote-console').attr('data-secret'),
onerror: function(e) {
spice.stop();
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error("SPICE", e);
},
onsuccess: function() {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
},
});
});
|
//= require jquery
//= require spice-html5-bower
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
$('#ctrlaltdel').click(sendCtrlAltDel);
var spice = new SpiceMainConn({
uri: (encrypt ? 'wss://' : 'ws://') + host + ':' + port + '/' + $('#remote-console').attr('data-url'),
screen_id: "remote-console",
password: $('#remote-console').attr('data-secret'),
onerror: function(e) {
spice.stop();
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error("SPICE", e);
},
onsuccess: function() {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
},
});
});
|
Set password in env var
|
import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
|
from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
|
[test] Test for colons in the password
|
var assert = require('assert'),
vows = require('vows'),
basicAuthParser = require('../');
vows.describe('basic-auth-parser').addBatch({
'When using `basic-auth-parser`': {
'with a correct string input': {
topic: basicAuthParser('Basic YWRtaW46cGFzc3dvcmQ='),
'it should return parsed data': function (result) {
assert.deepEqual(result, {
scheme: 'Basic',
username: 'admin',
password: 'password'
});
}
},
'with a wrong scheme': {
topic: basicAuthParser('Digest DEADC0FFEE'),
'it should return parsed data': function (result) {
assert.deepEqual(result, {
scheme: 'Digest'
});
}
},
'with a correct string and a colon in password': {
topic: basicAuthParser('Basic YWRtaW46cGFzczp3b3Jk'),
'it should return parsed data': function (result) {
assert.deepEqual(result, {
scheme: 'Basic',
username: 'admin',
password: 'pass:word'
});
}
}
}
}).export(module);
|
var assert = require('assert'),
vows = require('vows'),
basicAuthParser = require('../');
vows.describe('basic-auth-parser').addBatch({
'When using `basic-auth-parser`': {
'with a correct string input': {
topic: basicAuthParser('Basic YWRtaW46cGFzc3dvcmQ='),
'it should return parsed data': function (result) {
assert.deepEqual(result, {
scheme: 'Basic',
username: 'admin',
password: 'password'
});
}
},
'with a wrong scheme': {
topic: basicAuthParser('Digest DEADC0FFEE'),
'it should return parsed data': function (result) {
assert.deepEqual(result, {
scheme: 'Digest'
});
}
}
}
}).export(module);
|
Add test for new file upload to existing bucket
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connection = boto.connect_s3()
# Create a bucket to test on existing bucket
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
# Create test file
open(test_dir + '/' + test_file, 'w').close()
return
def tearDown(self):
connection = boto.connect_s3()
# Remove all files uploaded to s3
bucket = connection.get_bucket(existing_bucket)
for s3_file in bucket.list():
bucket.delete_key(s3_file.key)
# Remove bucket created to test on existing bucket
bucket = connection.delete_bucket(existing_bucket)
# Remove test file
os.remove(test_dir + '/' + test_file)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
def testNewFileUploadExistingBucket(self):
result = commit.commit_to_s3(existing_bucket, test_dir)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main()
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connection = boto.connect_s3()
# Create a bucket to test on existing bucket
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
# Create test file
open(test_dir + '/' + test_file, 'w').close()
return
def tearDown(self):
connection = boto.connect_s3()
# Remove all files uploaded to s3
bucket = connection.get_bucket(existing_bucket)
for s3_file in bucket.list():
bucket.delete_key(s3_file.key)
# Remove bucket created to test on existing bucket
bucket = connection.delete_bucket(existing_bucket)
# Remove test file
os.remove(test_dir + '/' + test_file)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
if __name__ == '__main__':
unittest.main()
|
Make the test a bit less idiotic.
|
package com.topsy.jmxproxy.jmx.tests;
import com.topsy.jmxproxy.jmx.ConnectionCredentials;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class ConnectionCredentialsTest {
@Test
public void compareEquals() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
final ConnectionCredentials auth2 = new ConnectionCredentials(new String("user"), new String("pass"));
assertTrue(auth1.equals(auth2));
}
@Test
public void compareNotEquals() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
final ConnectionCredentials auth2 = new ConnectionCredentials(new String("pass"), new String("user"));
assertFalse(auth1.equals(auth2));
}
@Test
public void compareNotEqualsNull() throws Exception {
final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), new String("pass"));
assertFalse(auth.equals(null));
}
}
|
package com.topsy.jmxproxy.jmx.tests;
import com.topsy.jmxproxy.jmx.ConnectionCredentials;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class ConnectionCredentialsTest {
@Test
public void compareEquals() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials("user", "pass");
final ConnectionCredentials auth2 = new ConnectionCredentials("user", "pass");
assertTrue(auth1.equals(auth2));
}
@Test
public void compareNotEquals() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials("user", "pass");
final ConnectionCredentials auth2 = new ConnectionCredentials("pass", "user");
assertFalse(auth1.equals(auth2));
}
@Test
public void compareNotEqualsNull() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials("user", "pass");
assertFalse(auth1.equals(null));
}
}
|
FIX (sharing gists): Fix shared gist not being loaded properly and now displays gist files.
|
'use strict';
function sharedCtrl($scope, ghAPI, gistData, $routeParams, $location, notificationService, $window) {
$scope.author = $routeParams.user;
ghAPI.gist($routeParams.id).then(function(gist) {
$scope.gist = gist;
});
console.log($scope.gist);
$scope.fork = function() {
ghAPI.fork($routeParams.id).then(function(data) {
notificationService.remove($routeParams.id);
notificationService.send('notificationRead', {gistId: $routeParams.id});
$location.url('/gist/' + data.id);
});
};
$scope.reject = function() {
notificationService.remove($routeParams.id);
console.log('sending notificationRead request');
notificationService.send('notificationRead', {gistId: $routeParams.id});
$window.history.back(-1);
};
};
|
'use strict';
function sharedCtrl($scope, ghAPI, gistData, $routeParams, $location, notificationService, $window) {
$scope.author = $routeParams.user;
$scope.gist = ghAPI.gist($routeParams.id);
$scope.fork = function() {
ghAPI.fork($routeParams.id).then(function(data) {
notificationService.remove($routeParams.id);
notificationService.send('notificationRead', {gistId: $routeParams.id});
$location.url('/gist/' + data.id);
});
};
$scope.reject = function() {
notificationService.remove($routeParams.id);
console.log('sending notificationRead request');
notificationService.send('notificationRead', {gistId: $routeParams.id});
$window.history.back(-1);
};
};
|
Format the clock time when a bus will arrive at the stop
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['timeline__event'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
arrivalTime: Ember.computed('clock.time', function () {
return moment(this.get('arrival.time')).format('hh:mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['timeline__event'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
|
Add logging to background assign
|
"""
Assign articles from AmCAT sets for background processing in nlpipe
"""
import sys, argparse
from nlpipe import tasks
from nlpipe.pipeline import parse_background
from nlpipe.backend import get_input_ids
from nlpipe.celery import app
import logging
FORMAT = '[%(asctime)-15s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
modules = {n.split(".")[-1]: t for (n,t) in app.tasks.iteritems() if n.startswith("nlpipe")}
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('module', help='nlpipe module (task) name ({})'.format(", ".join(sorted(modules))),
choices=modules, metavar="module")
parser.add_argument('sets', type=int, nargs='+', help='Article set id(s)')
parser.add_argument('--max', type=int, help='maximum number of articles to assign')
parser.add_argument('--queue', default='background', help='Celery queue to put the articles on')
args = parser.parse_args()
task = modules[args.module]
body = {u'filter': {'terms': {u'sets': args.sets}}}
logging.info("Assigning {max} articles from set(s) {args.sets} for processing by {task.name}"
.format(max=("up to {}".format(args.max) if args.max is not None else "all"), **locals()))
ids = list(get_input_ids(body))
logging.info("... Found {} articles".format(len(ids)))
parse_background(ids, task, max=args.max, queue=args.queue)
|
"""
Assign articles from AmCAT sets for background processing in nlpipe
"""
import sys, argparse
from nlpipe import tasks
from nlpipe.pipeline import parse_background
from nlpipe.backend import get_input_ids
from nlpipe.celery import app
modules = {n.split(".")[-1]: t for (n,t) in app.tasks.iteritems() if n.startswith("nlpipe")}
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('module', help='nlpipe module (task) name ({})'.format(", ".join(sorted(modules))),
choices=modules, metavar="module")
parser.add_argument('sets', type=int, nargs='+', help='Article set id(s)')
parser.add_argument('--max', type=int, help='maximum number of articles to assign')
parser.add_argument('--queue', default='background', help='Celery queue to put the articles on')
args = parser.parse_args()
task = modules[args.module]
body = {u'filter': {'terms': {u'sets': args.sets}}}
print("Assigning {max} articles from set(s) {args.sets} for processing by {task.name}"
.format(max=("up to {}".format(args.max) if args.max is not None else "all"), **locals()))
ids = list(get_input_ids(body))
parse_background(ids, task, max=args.max, queue=args.queue)
|
Write Views to Global Obj.
|
var views = [];
$.get("http://127.0.0.1:1338/views", function (views) {
window.views = views;
});
function loadData(view) {
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) {
var table = `<div class="table-responsive"><table class="table table-striped"><thead><tr>`;
view.headers.forEach(function (header) {
table += "<th>" + header.text + "</th>";
});
table += `</tr></thead><tbody>`;
view.data.forEach(function (datum) {
table += `<tr>`;
view.headers.forEach(function (header) {
table += "<td>" + getDescendantProp(datum, header.value) + "</td>";
});
table += `</tr>`;
});
table += `</tbody></table></div>`
$(".main").html(table);
$('table').DataTable({
"order": []
});
});
});
}
/* http://stackoverflow.com/a/8052100 */
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
loadData("matches");
|
function loadData(view) {
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) {
var table = `<div class="table-responsive"><table class="table table-striped"><thead><tr>`;
view.headers.forEach(function (header) {
table += "<th>" + header.text + "</th>";
});
table += `</tr></thead><tbody>`;
view.data.forEach(function (datum) {
table += `<tr>`;
view.headers.forEach(function (header) {
table += "<td>" + getDescendantProp(datum, header.value) + "</td>";
});
table += `</tr>`;
});
table += `</tbody></table></div>`
$(".main").html(table);
$('table').DataTable({
"order": []
});
});
});
}
/* http://stackoverflow.com/a/8052100 */
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
loadData("matches");
|
Remove limit from ember post API calls
ref #3004
- this is unnecessary and causing bugs
|
import styleBody from 'ghost/mixins/style-body';
import AuthenticatedRoute from 'ghost/routes/authenticated';
var paginationSettings = {
status: 'all',
staticPages: 'all',
page: 1
};
var PostsRoute = AuthenticatedRoute.extend(styleBody, {
classNames: ['manage'],
model: function () {
// using `.filter` allows the template to auto-update when new models are pulled in from the server.
// we just need to 'return true' to allow all models by default.
return this.store.filter('post', paginationSettings, function () {
return true;
});
},
setupController: function (controller, model) {
this._super(controller, model);
controller.set('paginationSettings', paginationSettings);
},
actions: {
openEditor: function (post) {
this.transitionTo('editor', post);
}
}
});
export default PostsRoute;
|
import styleBody from 'ghost/mixins/style-body';
import AuthenticatedRoute from 'ghost/routes/authenticated';
var paginationSettings = {
status: 'all',
staticPages: 'all',
page: 1,
limit: 15
};
var PostsRoute = AuthenticatedRoute.extend(styleBody, {
classNames: ['manage'],
model: function () {
// using `.filter` allows the template to auto-update when new models are pulled in from the server.
// we just need to 'return true' to allow all models by default.
return this.store.filter('post', paginationSettings, function () {
return true;
});
},
setupController: function (controller, model) {
this._super(controller, model);
controller.set('paginationSettings', paginationSettings);
},
actions: {
openEditor: function (post) {
this.transitionTo('editor', post);
}
}
});
export default PostsRoute;
|
Simplify keeping test temp files
- adds withSuppressCleanup method that can be used in the Rule directly
- useful when manually debugging a single test
|
/*
* Copyright 2010 the original author or authors.
*
* 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 org.gradle.test.fixtures.file;
import org.junit.runners.model.FrameworkMethod;
import java.io.File;
/**
* A JUnit rule which provides a unique temporary folder for the test.
*/
public class TestNameTestDirectoryProvider extends AbstractTestDirectoryProvider {
static {
// NOTE: the space in the directory name is intentional
root = new TestFile(new File("build/tmp/test files"));
}
public static TestNameTestDirectoryProvider newInstance() {
return new TestNameTestDirectoryProvider();
}
public static TestNameTestDirectoryProvider newInstance(FrameworkMethod method, Object target) {
TestNameTestDirectoryProvider testDirectoryProvider = new TestNameTestDirectoryProvider();
testDirectoryProvider.init(method.getName(), target.getClass().getSimpleName());
return testDirectoryProvider;
}
public TestNameTestDirectoryProvider withSuppressCleanup() {
suppressCleanup();
return this;
}
}
|
/*
* Copyright 2010 the original author or authors.
*
* 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 org.gradle.test.fixtures.file;
import org.junit.runners.model.FrameworkMethod;
import java.io.File;
/**
* A JUnit rule which provides a unique temporary folder for the test.
*/
public class TestNameTestDirectoryProvider extends AbstractTestDirectoryProvider {
static {
// NOTE: the space in the directory name is intentional
root = new TestFile(new File("build/tmp/test files"));
}
public static TestNameTestDirectoryProvider newInstance() {
return new TestNameTestDirectoryProvider();
}
public static TestNameTestDirectoryProvider newInstance(FrameworkMethod method, Object target) {
TestNameTestDirectoryProvider testDirectoryProvider = new TestNameTestDirectoryProvider();
testDirectoryProvider.init(method.getName(), target.getClass().getSimpleName());
return testDirectoryProvider;
}
}
|
core: Use a mixer mock in tests
|
from __future__ import absolute_import, unicode_literals
import unittest
import mock
from mopidy import core, mixer
class CoreMixerTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.mixer = mock.Mock(spec=mixer.Mixer)
self.core = core.Core(mixer=self.mixer, backends=[])
def test_get_volume(self):
self.mixer.get_volume.return_value.get.return_value = 30
self.assertEqual(self.core.mixer.get_volume(), 30)
self.mixer.get_volume.assert_called_once_with()
def test_set_volume(self):
self.core.mixer.set_volume(30)
self.mixer.set_volume.assert_called_once_with(30)
def test_get_mute(self):
self.mixer.get_mute.return_value.get.return_value = True
self.assertEqual(self.core.mixer.get_mute(), True)
self.mixer.get_mute.assert_called_once_with()
def test_set_mute(self):
self.core.mixer.set_mute(True)
self.mixer.set_mute.assert_called_once_with(True)
|
from __future__ import absolute_import, unicode_literals
import unittest
from mopidy import core
class CoreMixerTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.core = core.Core(mixer=None, backends=[])
def test_volume(self):
self.assertEqual(self.core.mixer.get_volume(), None)
self.core.mixer.set_volume(30)
self.assertEqual(self.core.mixer.get_volume(), 30)
self.core.mixer.set_volume(70)
self.assertEqual(self.core.mixer.get_volume(), 70)
def test_mute(self):
self.assertEqual(self.core.mixer.get_mute(), False)
self.core.mixer.set_mute(True)
self.assertEqual(self.core.mixer.get_mute(), True)
|
Change tests to ignore Illustrator's faulty bounds calculation of symbols.
|
module('Placed Symbol');
test('placedSymbol bounds', function() {
var doc = new Document();
var path = new Path.Circle([50, 50], 50);
path.strokeWidth = 1;
path.strokeCap = 'round';
path.strokeJoin = 'round';
compareRectangles(path.strokeBounds,
{ x: -0.5, y: -0.5, width: 101, height: 101 },
'Path initial bounds.');
var symbol = new Symbol(path);
var placedSymbol = new PlacedSymbol(symbol);
// These tests currently fail because we haven't implemented
// Item#strokeBounds yet.
compareRectangles(placedSymbol.bounds,
new Rectangle(-50.5, -50.5, 101, 101),
'PlacedSymbol initial bounds.');
placedSymbol.scale(0.5);
compareRectangles(placedSymbol.bounds,
{ x: -25.25, y: -25.25, width: 50.5, height: 50.5 },
'Bounds after scale.');
placedSymbol.rotate(40);
compareRectangles(placedSymbol.bounds,
{ x: -25.50049, y: -25.50049, width: 51.00098, height: 51.00098 },
'Bounds after rotation.');
});
|
module('Placed Symbol');
test('placedSymbol bounds', function() {
var doc = new Document();
var path = new Path.Circle([50, 50], 50);
path.strokeWidth = 1;
path.strokeCap = 'round';
path.strokeJoin = 'round';
compareRectangles(path.strokeBounds,
new Rectangle(-0.5, -0.5, 101, 101),
'Path initial bounds.');
var symbol = new Symbol(path);
var placedSymbol = new PlacedSymbol(symbol);
// These tests currently fail because we haven't implemented
// Item#strokeBounds yet.
compareRectangles(placedSymbol.bounds,
new Rectangle(-50.5, -50.5, 101, 101),
'PlacedSymbol initial bounds.');
placedSymbol.scale(0.5);
compareRectangles(placedSymbol.bounds,
{ x: -25.5, y: -25.5, width: 51, height: 51 },
'Bounds after scale.');
placedSymbol.rotate(40);
compareRectangles(placedSymbol.bounds,
{ x: -25.50049, y: -25.50049, width: 51.00098, height: 51.00098 },
'Bounds after rotation.');
});
|
Handle posts with malformed email addresses
|
<?php
namespace duncan3dc\Twitter\Posts;
use duncan3dc\DomParser\HtmlParser;
class Php extends AbstractPost
{
public $hostname = "http://news.php.net";
public $avatar = "/images/php.png";
public function __construct(array $row)
{
parent::__construct($row);
$a = (new HtmlParser($this->data["description"]))->getTag("a");
if ($a) {
$email = $a->getAttribute("href");
$email = str_replace("mailto:", "", $email);
$email = str_replace("+dot+", ".", $email);
$email = str_replace("+at+", "@", $email);
$this->username = $email;
$this->fullname = $a->nodeValue;
} else {
$this->username = $this->data["description"];
$this->fullname = $this->data["description"];
}
$this->link = $this->data["link"];
}
public function getHtml()
{
return $this->data["title"] . "<br><a href='" . $this->data["link"] . "'>" . $this->data["link"] . "</a>";
}
}
|
<?php
namespace duncan3dc\Twitter\Posts;
use duncan3dc\DomParser\HtmlParser;
class Php extends AbstractPost
{
public $hostname = "http://news.php.net";
public $avatar = "/images/php.png";
public function __construct(array $row)
{
parent::__construct($row);
$a = (new HtmlParser($this->data["description"]))->getTag("a");
$email = $a->getAttribute("href");
$email = str_replace("mailto:", "", $email);
$email = str_replace("+dot+", ".", $email);
$email = str_replace("+at+", "@", $email);
$this->username = $email;
$this->fullname = $a->nodeValue;
$this->link = $this->data["link"];
}
public function getHtml()
{
return $this->data["title"] . "<br><a href='" . $this->data["link"] . "'>" . $this->data["link"] . "</a>";
}
}
|
Fix content block test failing because of layout changes
|
<?php
namespace Backend\Modules\ContentBlocks\Tests\Action;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
class IndexTest extends BackendWebTestCase
{
public function testAuthenticationIsNeeded(Client $client): void
{
self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
}
public function testIndexHasNoItems(Client $client): void
{
$this->login($client);
self::assertPageLoadedCorrectly(
$client,
'/private/en/content_blocks/index',
[
'There are no content blocks yet.',
'Add content block',
'Add a content block',
]
);
}
}
|
<?php
namespace Backend\Modules\ContentBlocks\Tests\Action;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
class IndexTest extends BackendWebTestCase
{
public function testAuthenticationIsNeeded(Client $client): void
{
self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
}
public function testIndexHasNoItems(Client $client): void
{
$this->login($client);
self::assertPageLoadedCorrectly(
$client,
'/private/en/content_blocks/index',
[
'There are no items yet.',
'Add content block',
]
);
}
}
|
Add inline SVG feature detection
|
(function() {
// Feature detection results
const supports = {};
// Detect localStorage support
try {
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
supports.localStorage = true;
} catch (e) {
supports.localStorage = false;
}
// Detect inline SVG support
supports.inlineSVG = (function() {
const div = document.createElement('div');
div.innerHTML = '<svg/>';
return (
typeof SVGRect != 'undefined'
&& div.firstChild
&& div.firstChild.namespaceURI
) == 'http://www.w3.org/2000/svg';
})();
// Add ios class to body on iOS devices
function iosBodyClass() {
if(
/iPad|iPhone|iPod/.test(navigator.userAgent)
&& !window.MSStream
&& document.body.classList
) {
document.body.classList.add('ios');
}
}
// Check if DOM has already loaded as we're loading async
['interactive', 'complete'].indexOf(document.readyState) >= 0
? init()
: document.addEventListener('DOMContentLoaded', init);
// When DOM is ready
function init() {
// Check for iOS
iosBodyClass();
}
})();
|
(function() {
// Feature detection results
const supports = {};
// Detect localStorage support
try {
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
supports.localStorage = true;
} catch (e) {
supports.localStorage = false;
}
// Add ios class to body on iOS devices
function iosBodyClass() {
if(
/iPad|iPhone|iPod/.test(navigator.userAgent)
&& !window.MSStream
&& document.body.classList
) {
document.body.classList.add('ios');
}
}
// Check if DOM has already loaded as we're loading async
['interactive', 'complete'].indexOf(document.readyState) >= 0
? init()
: document.addEventListener('DOMContentLoaded', init);
// When DOM is ready
function init() {
// Check for iOS
iosBodyClass();
}
})();
|
Make the calendar server a singleton
|
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
private static Server server = null;
DatabaseConnector connector;
protected CalendarServer() {
}
public static Server getServer() {
if (server == null) {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
return server;
}
public static void main(String[] args) {
CalendarServer.getServer();
}
}
|
package com.gruppe27.fellesprosjekt.server;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;
import java.io.IOException;
public class CalendarServer {
Server server;
DatabaseConnector connector;
public CalendarServer() {
server = new Server() {
protected Connection newConnection() {
return new CalendarConnection();
}
};
Network.register(server);
server.addListener(new CalendarListener(server));
try {
server.bind(Network.PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
server.start();
}
public static void main(String[] args) {
CalendarServer server = new CalendarServer();
}
}
|
Update tooltip copy for analytics referrals chart
|
<?php
namespace Minds\Core\Analytics\Dashboards\Metrics\Engagement;
use Minds\Core\Di\Di;
use Minds\Core\Session;
use Minds\Core\Data\ElasticSearch;
use Minds\Core\Analytics\Dashboards\Metrics\AbstractMetric;
use Minds\Core\Analytics\Dashboards\Metrics\MetricSummary;
use Minds\Core\Analytics\Dashboards\Metrics\Visualisations;
use Minds\Core\Analytics\Dashboards\Metrics\HistogramSegment;
class ReferralsMetric extends AbstractEngagementMetric
{
public function __construct($es = null)
{
parent::__construct($es);
$this->segments = [
(new HistogramSegment())
->setAggField('referral::total')
->setAggType('sum'),
(new HistogramSegment())
->setAggField('referral::active')
->setAggType('sum')
->setLabel('Active'),
];
}
/** @var string */
protected $id = 'referrals';
/** @var string */
protected $label = 'Referrals';
/** @var string */
protected $description = "Earnings from content posted by users you referred to Minds";
/** @var array */
protected $permissions = [ 'user', 'admin' ];
/** @var string */
protected $aggField = 'referral::total';
}
|
<?php
namespace Minds\Core\Analytics\Dashboards\Metrics\Engagement;
use Minds\Core\Di\Di;
use Minds\Core\Session;
use Minds\Core\Data\ElasticSearch;
use Minds\Core\Analytics\Dashboards\Metrics\AbstractMetric;
use Minds\Core\Analytics\Dashboards\Metrics\MetricSummary;
use Minds\Core\Analytics\Dashboards\Metrics\Visualisations;
use Minds\Core\Analytics\Dashboards\Metrics\HistogramSegment;
class ReferralsMetric extends AbstractEngagementMetric
{
public function __construct($es = null)
{
parent::__construct($es);
$this->segments = [
(new HistogramSegment())
->setAggField('referral::total')
->setAggType('sum'),
(new HistogramSegment())
->setAggField('referral::active')
->setAggType('sum')
->setLabel('Active'),
];
}
/** @var string */
protected $id = 'referrals';
/** @var string */
protected $label = 'Referrals';
/** @var string */
protected $description = "Number of comments you have received on your content";
/** @var array */
protected $permissions = [ 'user', 'admin' ];
/** @var string */
protected $aggField = 'referral::total';
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.