text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change the way properties on document.body are set while loading canvas.
In the default setup, when no width and height options are passed and
`createGL` is called on page load, it throws an error if the script is
included before the body element, since `document.body.style` is null.
The function already accounts for this fact while appending the canvas
to the page, but not while setting `style.margin = '0px'`. This PR
changes that.
|
const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
const appendCanvas = () => {
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
document.body.appendChild(canvas)
}
if (document.body) {
appendCanvas()
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', appendCanvas)
}
}
const gl = canvas.getContext('webgl', opts)
return gl
}
module.exports = createGL
|
const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
if (document.body) {
document.body.appendChild(canvas)
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(canvas)
})
}
}
const gl = canvas.getContext('webgl', opts)
return gl
}
module.exports = createGL
|
Simplify read until pattern test
|
var test = require('tap').test;
var streamBuffers = require("stream-buffers");
var UntilStream = require('../');
test("read until pattern", function (t) {
t.plan(2);
var us = new UntilStream({ pattern: 'World'});
us.once('readable', function() {
var data = us.read();
t.equal(data.toString(), 'Hello ');
data = us.read();
t.equal(data.toString(), 'World');
t.end();
});
us.write("Hello World");
});
test("multiple reads from after source stream has ended", function(t) {
var arr = [], times = 25;
t.plan(times * 2);
for (var i = 0; i < times; i++) {
arr.push("Hello World");
}
var sourceStream = new streamBuffers.ReadableStreamBuffer();
sourceStream.put(arr.join(''));
var us = new UntilStream({ pattern: 'World'});
us.on('finish', function () {
sourceStream.destroy();
});
sourceStream.pipe(us);
var intervalId;
sourceStream.once('close', function() {
intervalId = setInterval(function() {
var data = us.read();
t.equal(data.toString(), 'Hello ');
data = us.read();
t.equal(data.toString(), 'World');
}, 10);
});
us.on('end', function() {
clearInterval(intervalId);
t.end();
});
});
|
var test = require('tap').test;
var streamBuffers = require("stream-buffers");
var UntilStream = require('../');
test("read until pattern", function (t) {
t.plan(2);
var us = new UntilStream({ pattern: 'World'});
us.on('finish', function () {
sourceStream.destroy();
});
var sourceStream = new streamBuffers.ReadableStreamBuffer();
sourceStream.put("Hello World");
sourceStream.pipe(us);
us.once('readable', function() {
var data = us.read();
t.equal(data.toString(), 'Hello ');
data = us.read();
t.equal(data.toString(), 'World');
t.end();
});
});
test("multiple reads from after source stream has ended", function(t) {
var arr = [], times = 25;
t.plan(times * 2);
for (var i = 0; i < times; i++) {
arr.push("Hello World");
}
var sourceStream = new streamBuffers.ReadableStreamBuffer();
sourceStream.put(arr.join(''));
var us = new UntilStream({ pattern: 'World'});
us.on('finish', function () {
sourceStream.destroy();
});
sourceStream.pipe(us);
var intervalId;
sourceStream.once('close', function() {
intervalId = setInterval(function() {
var data = us.read();
t.equal(data.toString(), 'Hello ');
data = us.read();
t.equal(data.toString(), 'World');
}, 10);
});
us.on('end', function() {
clearInterval(intervalId);
t.end();
});
});
|
Update import for classproperty in django 3.1 and above
|
# coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from taggit.managers import TaggableManager
from translator.util import get_key
try:
# Django 3.1 and above
from django.utils.functional import classproperty
except ImportError:
from django.utils.decorators import classproperty
class TranslationBase(models.Model):
key = models.CharField(max_length=255, unique=True)
description = models.TextField()
tags = TaggableManager(blank=True)
class Meta:
abstract = True
def __unicode__(self):
return self.key
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
all_translation_keys = self.__class__.objects.all().values_list('key', flat=True)
for l in settings.LANGUAGES:
cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys])
return super().save(force_insert, force_update, using, update_fields)
@classproperty
def cache_key_prefix(self):
"""To separate cache keys, we need to specify a unique prefix per model."""
return self._meta.db_table
class Translation(TranslationBase):
pass
|
# coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.decorators import classproperty
from taggit.managers import TaggableManager
from translator.util import get_key
class TranslationBase(models.Model):
key = models.CharField(max_length=255, unique=True)
description = models.TextField()
tags = TaggableManager(blank=True)
class Meta:
abstract = True
def __unicode__(self):
return self.key
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
all_translation_keys = self.__class__.objects.all().values_list('key', flat=True)
for l in settings.LANGUAGES:
cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys])
return super().save(force_insert, force_update, using, update_fields)
@classproperty
def cache_key_prefix(self):
"""To separate cache keys, we need to specify a unique prefix per model."""
return self._meta.db_table
class Translation(TranslationBase):
pass
|
Use PSR-0 structure for the test too
|
<?php
namespace Test\Staq;
require_once( __DIR__ . '/../../../vendor/autoload.php' );
class Application_Test extends \PHPUnit_Framework_TestCase {
/*************************************************************************
ATTRIBUTES
*************************************************************************/
public $starter_namespaces = [ 'Staq\App\Starter', 'Staq\Core\Router', 'Staq\Core\Ground' ];
/*************************************************************************
TEST METHODS
*************************************************************************/
public function test_empty_project__extensions( ) {
$app = \Staq\Application::create( );
$this->assertEquals( $this->starter_namespaces, $app->get_extensions( 'namespace' ) );
}
public function test_empty_project__platform( ) {
$app = \Staq\Application::create( );
$this->assertEquals( 'prod', $app->get_platform( ) );
}
public function test_named_project__extensions( ) {
$project_namespace = 'Staq';
$app = \Staq\Application::create( $project_namespace );
$expected = $this->starter_namespaces;
array_unshift( $expected, $project_namespace );
$this->assertEquals( $expected, $app->get_extensions( 'namespace' ) );
}
}
|
<?php
namespace Test\Staq;
require_once( __DIR__ . '/../../vendor/autoload.php' );
class Application_Test extends \PHPUnit_Framework_TestCase {
/*************************************************************************
ATTRIBUTES
*************************************************************************/
public $starter_namespaces = [ 'Staq\App\Starter', 'Staq\Core\Router', 'Staq\Core\Ground' ];
/*************************************************************************
TEST METHODS
*************************************************************************/
public function test_empty_project__extensions( ) {
$app = \Staq\Application::create( );
$this->assertEquals( $this->starter_namespaces, $app->get_extensions( 'namespace' ) );
}
public function test_empty_project__platform( ) {
$app = \Staq\Application::create( );
$this->assertEquals( 'prod', $app->get_platform( ) );
}
public function test_named_project__extensions( ) {
$project_namespace = 'Staq';
$app = \Staq\Application::create( $project_namespace );
$expected = $this->starter_namespaces;
array_unshift( $expected, $project_namespace );
$this->assertEquals( $expected, $app->get_extensions( 'namespace' ) );
}
}
|
Add name to patterns in urlpatterns
- so tests can use reverse()
|
"""This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'apel_rest.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/',
include(admin.site.urls,)),
url(r'^api/v1/cloud/record$',
CloudRecordView.as_view(),
name='CloudRecordView'),
url(r'^api/v1/cloud/record/summary$',
CloudRecordSummaryView.as_view(),
name='CloudRecordSummaryView'))
|
"""This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'apel_rest.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/',
include(admin.site.urls)),
url(r'^api/v1/cloud/record$',
CloudRecordView.as_view()),
url(r'^api/v1/cloud/record/summary$',
CloudRecordSummaryView.as_view()))
|
Stop catching import errors to improve stack trace readability
|
import renpy
import os
import sys
import modinfo
import importlib
print('AWSW Mod Loader Init')
def get_mod_path():
"""Get the mod path
Returns:
The full path to the mods folder
"""
#TODO: Use a path combining function
return renpy.config.gamedir + "/mods/"
# By setting the import path to the mod folder, we can do something like `import mod`
# NOTE: To import files in the modloader/ folder, do `from modloader import ...`
# If we add the modloader to the path, the modlist would get reloaded again
sys.path.append(get_mod_path())
for mod in os.listdir(get_mod_path()):
# Some mods require resources to be recognized by renpy. If a folder exists, force renpy to load it
resource_dir = get_mod_path() + mod + "/resource"
if os.path.isdir(resource_dir):
renpy.config.searchpath.append(resource_dir)
# Try importing the mod. If all goes well, the mod is imported through the Mod class
print("Begin mod load: {}".format(mod))
#try:
importlib.import_module(mod)
# After all mods are loaded, call their respective mod_complete functions
for mod_name, mod in modinfo.get_mods().iteritems():
print("Completing mod {}".format(mod_name))
mod.mod_complete()
# force renpy to reindex all game files
renpy.loader.old_config_archives = None
|
import renpy
import os
import sys
import modinfo
import importlib
print('AWSW Mod Loader Init')
def get_mod_path():
"""Get the mod path
Returns:
The full path to the mods folder
"""
#TODO: Use a path combining function
return renpy.config.gamedir + "/mods/"
# By setting the import path to the mod folder, we can do something like `import mod`
# NOTE: To import files in the modloader/ folder, do `from modloader import ...`
# If we add the modloader to the path, the modlist would get reloaded again
sys.path.append(get_mod_path())
for mod in os.listdir(get_mod_path()):
# Some mods require resources to be recognized by renpy. If a folder exists, force renpy to load it
resource_dir = get_mod_path() + mod + "/resource"
if os.path.isdir(resource_dir):
renpy.config.searchpath.append(resource_dir)
# Try importing the mod. If all goes well, the mod is imported through the Mod class
print("Begin mod load: {}".format(mod))
try:
importlib.import_module(mod)
except Exception, e:
print("Exception while loading: {}".format(mod))
print(e)
raise e # Raise it again even though the stacktrace provides nothing useful
# After all mods are loaded, call their respective mod_complete functions
for mod_name, mod in modinfo.get_mods().iteritems():
print("Completing mod {}".format(mod_name))
mod.mod_complete()
# force renpy to reindex all game files
renpy.loader.old_config_archives = None
|
Check if process.env is defined
|
/* eslint-disable react/prop-types */
import React from "react"
import { shallowEqual } from "./utils/utils"
export const MobXProviderContext = React.createContext({})
export function Provider({ children, ...stores }) {
const parentValue = React.useContext(MobXProviderContext)
const value = React.useRef({
...parentValue,
...stores
}).current
if (process && typeof process.env !== "undefined" && process.env.NODE_ENV !== "production") {
const newValue = { ...value, ...stores } // spread in previous state for the context based stores
if (!shallowEqual(value, newValue)) {
throw new Error(
"MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error."
)
}
}
return <MobXProviderContext.Provider value={value}>{children}</MobXProviderContext.Provider>
}
Provider.displayName = "MobXProvider"
|
/* eslint-disable react/prop-types */
import React from "react"
import { shallowEqual } from "./utils/utils"
export const MobXProviderContext = React.createContext({})
export function Provider({ children, ...stores }) {
const parentValue = React.useContext(MobXProviderContext)
const value = React.useRef({
...parentValue,
...stores
}).current
if (process.env.NODE_ENV !== "production") {
const newValue = { ...value, ...stores } // spread in previous state for the context based stores
if (!shallowEqual(value, newValue)) {
throw new Error(
"MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error."
)
}
}
return <MobXProviderContext.Provider value={value}>{children}</MobXProviderContext.Provider>
}
Provider.displayName = "MobXProvider"
|
Change all expected variables to truthy values
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = "2";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(2);
});
});
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(false).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = FILL_ME_IN;
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(FILL_ME_IN);
});
});
|
Add event callback for no document found
|
import queryString from 'query-string'
import events from '../core/events'
import * as constants from '../constants'
import { actions } from '../store/actions'
import ReconnectingWebSocket from 'reconnectingwebsocket'
const {
setDocumentCaptured,
setToken,
setAuthenticated
} = actions
export default class Socket {
connect(jwt) {
const query = queryString.stringify({ jwt: jwt })
const url = `${constants.DEV_SOCKET_URL}?${query}`
const socket = new ReconnectingWebSocket(url)
socket.onopen = () => {
this.socket = socket
this.onMessage()
setToken(jwt)
setAuthenticated(true)
}
}
handleData(data) {
if (data.is_document) {
setDocumentCaptured(true)
} else if (!data.is_document) {
events.emit('noDocument')
}
}
onMessage() {
this.socket.onmessage = (e) => {
const data = JSON.parse(e.data)
this.handleData(data)
}
}
sendMessage(message) {
this.socket.send(message)
}
}
|
import queryString from 'query-string'
import events from '../core/events'
import * as constants from '../constants'
import { actions } from '../store/actions'
import ReconnectingWebSocket from 'reconnectingwebsocket'
const {
setDocumentCaptured,
setToken,
setAuthenticated
} = actions
export default class Socket {
connect(jwt) {
const query = queryString.stringify({ jwt: jwt })
const url = `${constants.DEV_SOCKET_URL}?${query}`
const socket = new ReconnectingWebSocket(url)
socket.onopen = () => {
this.socket = socket
this.onMessage()
setToken(jwt)
setAuthenticated(true)
}
}
handleData(data) {
if (data.is_document || data.has_passport) {
setDocumentCaptured(true)
}
}
onMessage() {
this.socket.onmessage = (e) => {
const data = JSON.parse(e.data)
this.handleData(data)
}
}
sendMessage(message) {
this.socket.send(message)
}
}
|
Use correct sound file name
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wge3.model.audio;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
/**
*
* @author Teemu
*/
public class DefaultGun implements MySound {
private Sound sound;
public DefaultGun() {
try {
sound = Gdx.audio.newSound(Gdx.files.internal("sounds/defaultGun.wav"));
} catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
@Override
public void play() {
sound.play();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wge3.model.audio;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
/**
*
* @author Teemu
*/
public class DefaultGun implements MySound {
private Sound sound;
public DefaultGun() {
try {
sound = Gdx.audio.newSound(Gdx.files.internal("sounds/defaultGun2-16.wav"));
} catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
@Override
public void play() {
sound.play();
}
}
|
Add a start and end method to MockRequest
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
|
Fix AttributeError on ListedColormap from_list method
|
import matplotlib.cm as cm
import matplotlib.colors as clr
import matplotlib.pyplot as plt
from ..palettes import SEABORN
def create_discrete_cmap(n):
"""Create an n-bin discrete colormap."""
if n <= len(SEABORN):
colors = list(SEABORN.values())[:n]
else:
base = plt.cm.get_cmap('Paired')
color_list = base([(i + 1) / (n + 1) for i in range(n)])
cmap_name = base.name + str(n)
return clr.LinearSegmentedColormap.from_list(cmap_name, color_list, n)
return clr.ListedColormap(colors)
def add_color_bar(ax, cmap, labels):
"""Add a colorbar to an axis.
Args:
ax (AxesSubplot)
cmap (Colormap): A prepaped colormap of size n.
labels (list of str): A list of strings of size n.
"""
norm = clr.BoundaryNorm(list(range(cmap.N+1)), cmap.N)
smap = cm.ScalarMappable(norm=norm, cmap=cmap)
smap.set_array([])
cbar = plt.colorbar(smap, ax=ax)
cbar.set_ticks([i + 0.5 for i in range(cmap.N)])
cbar.set_ticklabels(labels)
|
import matplotlib.cm as cm
import matplotlib.colors as clr
import matplotlib.pyplot as plt
from ..palettes import SEABORN
def create_discrete_cmap(n):
"""Create an n-bin discrete colormap."""
if n <= len(SEABORN):
colors = list(SEABORN.values())[:n]
else:
base = plt.cm.get_cmap('Paired')
color_list = base([(i + 1) / (n + 1) for i in range(n)])
cmap_name = base.name + str(n)
return base.from_list(cmap_name, color_list, n)
return clr.ListedColormap(colors)
def add_color_bar(ax, cmap, labels):
"""Add a colorbar to an axis.
Args:
ax (AxesSubplot)
cmap (Colormap): A prepaped colormap of size n.
labels (list of str): A list of strings of size n.
"""
norm = clr.BoundaryNorm(list(range(cmap.N+1)), cmap.N)
smap = cm.ScalarMappable(norm=norm, cmap=cmap)
smap.set_array([])
cbar = plt.colorbar(smap, ax=ax)
cbar.set_ticks([i + 0.5 for i in range(cmap.N)])
cbar.set_ticklabels(labels)
|
Fix Overscroll when we're using Mode.BOTH
|
package com.handmark.pulltorefresh.library;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
final class OverscrollHelper {
static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
}
|
package com.handmark.pulltorefresh.library;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
final class OverscrollHelper {
static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getCurrentMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
}
|
Reduce debug logging in more_like_this
|
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
# print(query.to_dict())
return query.execute()
|
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
print(query.to_dict())
x = query.execute()
print(x)
return x
|
Integrate the hashtable Unit testcases.
* tests/AllTests.java (suite): added HashtableTests
|
/**
* ====================================================================
* Copyright (c) 2000-2001 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
*
*/
import junit.framework.*;
/**
* JUnits tests for the Java subversion binding helper functions
*/
public class AllTests {
public static void main( String [] args )
{
junit.textui.TestRunner.run( suite() );
}
public static Test suite( )
{
TestSuite suite = new TestSuite(
"All JUnit tests for the Java Subversion binding");
//add tests here
//example:
//suite.addTest( new StatusTest() );
suite.addTestSuite( DateTests.class );
suite.addTestSuite( EntryTests.class );
suite.addTestSuite( VectorTests.class );
suite.addTestSuite( HashtableTests.class );
return suite;
}
}
|
/**
* ====================================================================
* Copyright (c) 2000-2001 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
*
*/
import junit.framework.*;
/**
* JUnits tests for the Java subversion binding helper functions
*/
public class AllTests {
public static void main( String [] args )
{
junit.textui.TestRunner.run( suite() );
}
public static Test suite( )
{
TestSuite suite = new TestSuite(
"All JUnit tests for the Java Subversion binding");
//add tests here
//example:
//suite.addTest( new StatusTest() );
suite.addTestSuite( DateTests.class );
suite.addTestSuite( EntryTests.class );
suite.addTestSuite( VectorTests.class );
return suite;
}
}
|
Fix typo causing fatal error.
|
<?php
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', function($routes) {
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
$routes->connect('/pages/*', ['controller', => 'pages', 'action' => 'display']);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
|
<?php
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', fnction($routes) {
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
$routes->connect('/pages/*', ['controller', => 'pages', 'action' => 'display']);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
|
Make SGML less chatty in normal operation
|
import logging
import os
import chryso.connection
import sepiida.config
import sepiida.log
import vanth.config
import vanth.server
import vanth.tables
LOGGER = logging.getLogger(__name__)
def create_db_connection(config):
engine = chryso.connection.Engine(config.db, vanth.tables)
chryso.connection.store(engine)
return engine
def create_application(config):
create_db_connection(config)
LOGGER.info("Starting up vanth version %s", vanth.version.VERSION)
application = vanth.server.create_app(config)
logging.getLogger('vanth.cors').setLevel(logging.WARNING)
return application
def setup_logging():
logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig()
sepiida.log.setup_logging()
logging.getLogger('vanth.sgml').setLevel(logging.INFO)
def get_config():
return sepiida.config.load('/etc/vanth.yaml', vanth.config.SPECIFICATION)
def main():
setup_logging()
config = get_config()
application = create_application(config)
try:
host = os.getenv('HOST', 'localhost')
port = int(os.getenv('PORT', 4545))
application.run(host, port)
except KeyboardInterrupt:
LOGGER.info('Shutting down')
|
import logging
import os
import chryso.connection
import sepiida.config
import sepiida.log
import vanth.config
import vanth.server
import vanth.tables
LOGGER = logging.getLogger(__name__)
def create_db_connection(config):
engine = chryso.connection.Engine(config.db, vanth.tables)
chryso.connection.store(engine)
return engine
def create_application(config):
create_db_connection(config)
LOGGER.info("Starting up vanth version %s", vanth.version.VERSION)
application = vanth.server.create_app(config)
logging.getLogger('vanth.cors').setLevel(logging.WARNING)
return application
def setup_logging():
logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig()
sepiida.log.setup_logging()
def get_config():
return sepiida.config.load('/etc/vanth.yaml', vanth.config.SPECIFICATION)
def main():
setup_logging()
config = get_config()
application = create_application(config)
try:
host = os.getenv('HOST', 'localhost')
port = int(os.getenv('PORT', 4545))
application.run(host, port)
except KeyboardInterrupt:
LOGGER.info('Shutting down')
|
Prepare for deploy to production.
|
package org.kefirsf.tk;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Signin servlet
*
* @author Vitalii Samolovskikh aka Kefir
*/
public class SigninServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
request.getSession().setAttribute("twitter", twitter);
try {
/*
String callbackUrl = new StringBuilder()
.append(ConfigurationHolder.getInstance().get("server.url"))
.append("/callback")
.toString();
RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
*/
RequestToken requestToken = twitter.getOAuthRequestToken();
request.getSession().setAttribute("requestToken", requestToken);
response.sendRedirect(requestToken.getAuthenticationURL());
} catch (TwitterException e) {
throw new ServletException(e);
}
}
}
|
package org.kefirsf.tk;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Signin servlet
*
* @author Vitalii Samolovskikh aka Kefir
*/
public class SigninServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
request.getSession().setAttribute("twitter", twitter);
try {
String callbackUrl = new StringBuilder()
.append(ConfigurationHolder.getInstance().get("server.url"))
.append("/callback")
.toString();
RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
request.getSession().setAttribute("requestToken", requestToken);
response.sendRedirect(requestToken.getAuthenticationURL());
} catch (TwitterException e) {
throw new ServletException(e);
}
}
}
|
Change the url when clicking on a kata group.
|
import React from 'react';
export default class KataGroups extends React.Component {
render() {
const {kataGroups} = this.props;
return (
<div id="nav" className="pure-u">
<a href="#" className="nav-menu-button">Menu</a>
<div className="nav-inner">
<div className="pure-menu">
<ul className="pure-menu-list">
<li className="pure-menu-heading">Kata groups</li>
<li className="pure-menu-item">
</li>
{kataGroups.map(kataGroup => <li className="pure-menu-item">
<a href={`#kataGroup=${encodeURIComponent(kataGroup.name)}`} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
</li>)}
</ul>
</div>
</div>
</div>
)
}
}
|
import React from 'react';
export default class KataGroups extends React.Component {
render() {
const {kataGroups} = this.props;
return (
<div id="nav" className="pure-u">
<a href="#" className="nav-menu-button">Menu</a>
<div className="nav-inner">
<div className="pure-menu">
<ul className="pure-menu-list">
<li className="pure-menu-heading">Kata groups</li>
<li className="pure-menu-item">
</li>
{kataGroups.map(kataGroup => <li className="pure-menu-item">
<a href="#" className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
</li>)}
</ul>
</div>
</div>
</div>
)
}
}
|
Remove unused import in HelloWorld sample
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.msf4j.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
/**
* Hello service resource class.
*/
@Path("/hello")
public class HelloService {
@GET
@Path("/{name}")
public String hello(@PathParam("name") String name) {
System.out.println("Hello");
return "Hello " + name;
}
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.msf4j.example;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
/**
* Hello service resource class.
*/
@Path("/hello")
public class HelloService {
@GET
@Path("/{name}")
public String hello(@PathParam("name") String name) {
System.out.println("Hello");
return "Hello " + name;
}
}
|
DOC: Fix unicode in citation (again)
|
"""
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@article{Bocklund2019ESPEI,
archivePrefix = {arXiv},
arxivId = {1902.01269},
author = {Bocklund, Brandon and Otis, Richard and Egorov, Aleksei and Obaied, Abdulmonem and Roslyakova, Irina and Liu, Zi-Kui},
doi = {10.1557/mrc.2019.59},
eprint = {1902.01269},
issn = {2159-6859},
journal = {MRS Communications},
month = {jun},
pages = {1--10},
title = {{ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg}},
year = {2019}
}
"""
|
"""
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@article{Bocklund2019ESPEI,
archivePrefix = {arXiv},
arxivId = {1902.01269},
author = {Bocklund, Brandon and Otis, Richard and Egorov, Aleksei and Obaied, Abdulmonem and Roslyakova, Irina and Liu, Zi-Kui},
doi = {10.1557/mrc.2019.59},
eprint = {1902.01269},
issn = {2159-6859},
journal = {MRS Communications},
month = {jun},
pages = {1--10},
title = {{ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu–Mg}},
year = {2019}
}
"""
|
Enable the ability for a tag attribute value to be an empty string and get set on the html tag
|
const singletonTags = [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
];
const tagsWithValueAttributes = [
'button',
'input',
'li',
'meter',
'option',
'param',
'progress'
];
module.exports = {
tag: {
render: (tagName, data) => {
const isValueTag = tagsWithValueAttributes.includes(tagName);
const attributes = Object.entries(data).reduce((attrs, [key, value]) => {
if ((value || typeof value === 'string') && ((key === 'value' && isValueTag) || !['content', 'value'].includes(key))) {
attrs += value === true
? ` ${key}`
: ` ${key}="${value}"`;
}
return attrs;
}, '');
const tag = `<${tagName}${attributes}>`;
const tagContent = data.content || (!isValueTag && data.value ? data.value : '');
return singletonTags.includes(tagName)
? tag
: `${tag}${tagContent}</${tagName}>`;
},
firstArgIsResolvedPath: false,
content: true
}
};
|
const singletonTags = [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
];
const tagsWithValueAttributes = [
'button',
'input',
'li',
'meter',
'option',
'param',
'progress'
];
module.exports = {
tag: {
render: (tagName, data) => {
const isValueTag = tagsWithValueAttributes.includes(tagName);
const attributes = Object.entries(data).reduce((attrs, [key, value]) => {
if (value && ((key === 'value' && isValueTag) || !['content', 'value'].includes(key))) {
attrs += value === true
? ` ${key}`
: ` ${key}="${value}"`;
}
return attrs;
}, '');
const tag = `<${tagName}${attributes}>`;
const tagContent = data.content || (!isValueTag && data.value ? data.value : '');
return singletonTags.includes(tagName)
? tag
: `${tag}${tagContent}</${tagName}>`;
},
firstArgIsResolvedPath: false,
content: true
}
};
|
Reset title of add uniform/texture fragment
Required if we're coming back from texture parameters for example.
|
package de.markusfisch.android.shadereditor.fragment;
import de.markusfisch.android.shadereditor.adapter.UniformPageAdapter;
import de.markusfisch.android.shadereditor.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class UniformPagesFragment extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle state) {
// reset title if we're coming back from another fragment
getActivity().setTitle(R.string.add_uniform);
View view = inflater.inflate(
R.layout.fragment_uniform_pages,
container,
false);
ViewPager viewPager = view.findViewById(R.id.pager);
viewPager.setAdapter(new UniformPageAdapter(
getActivity(),
getChildFragmentManager()));
return view;
}
}
|
package de.markusfisch.android.shadereditor.fragment;
import de.markusfisch.android.shadereditor.adapter.UniformPageAdapter;
import de.markusfisch.android.shadereditor.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class UniformPagesFragment extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle state) {
View view = inflater.inflate(
R.layout.fragment_uniform_pages,
container,
false);
ViewPager viewPager = view.findViewById(R.id.pager);
viewPager.setAdapter(new UniformPageAdapter(
getActivity(),
getChildFragmentManager()));
return view;
}
}
|
Change camera index, and fix the chessboard preview.
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Capture calibration chessboard
#
# External dependencies
import time
import cv2
import numpy as np
import Calibration
# Calibration pattern size
pattern_size = ( 9, 6 )
# Get the camera
camera = cv2.VideoCapture( 0 )
# Acquisition loop
while( True ) :
# Capture image-by-image
_, image = camera.read()
# Copy the image for display
chessboard = np.copy( image )
# Display the chessboard on the image
Calibration.PreviewChessboard( chessboard, pattern_size )
# Display the resulting image
cv2.imshow( 'USB Camera', chessboard )
# Keyboard interruption
key = cv2.waitKey( 1 ) & 0xFF
# Escape : quit the application
if key == 27 : break
# Space : save the image
elif key == 32 :
current_time = time.strftime( '%Y%m%d_%H%M%S' )
print( 'Save image {} to disk...'.format( current_time ) )
cv2.imwrite( 'image-{}.png'.format( current_time ), image )
# Release the camera
camera.release()
# Close OpenCV windows
cv2.destroyAllWindows()
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Capture calibration chessboard
#
# External dependencies
import time
import cv2
import Calibration
# Calibration pattern size
pattern_size = ( 9, 6 )
# Get the camera
camera = cv2.VideoCapture( 1 )
# Acquisition loop
while( True ) :
# Capture image-by-image
_, image = camera.read()
# Display the chessboard on the image
chessboard = Calibration.PreviewChessboard( image, pattern_size )
# Display the resulting image
cv2.imshow( 'USB Camera', chessboard )
# Keyboard interruption
key = cv2.waitKey( 1 ) & 0xFF
# Escape : quit the application
if key == 27 : break
# Space : save the image
elif key == 32 :
current_time = time.strftime( '%Y%m%d_%H%M%S' )
print( 'Save image {} to disk...'.format( current_time ) )
cv2.imwrite( 'image-{}.png'.format( current_time ), image )
# Release the camera
camera.release()
# Close OpenCV windows
cv2.destroyAllWindows()
|
Refactor logic out into smaller methods
|
<?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
[new RoutedApplication(
[['POST', '/form', $html]])]);
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
private function crawler($html)
{
return new Crawler($html);
}
private function filterNotEmpty($crawler, $filter)
{
return $crawler->filter($filter)->count() > 0;
}
private function responseBodyHasClass($response, $class)
{
return $this->filterNotEmpty($this->crawler($response['body']), $class);
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
}
}
|
<?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function crawler($html)
{
return new Crawler($html);
}
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
[new RoutedApplication(
[['POST', '/form', $html]])]);
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$crawler = $this->crawler($response['body']);
$this->assertSame(1, $crawler->filter('h1.success')->count());
}
}
|
Add pagination to bottom of page too
|
const m = require('mithril');
const Pagination = require('../components/pagination');
const Datatable = require('../components/datatable');
const Datadisplay = module.exports = {};
Datadisplay.controller = function () {
let ctrl = this;
ctrl.currentPage = m.prop(m.route.param('page') || 1);
ctrl.itemsPerPage = m.prop(10);
ctrl.maxPage = m.prop(1);
ctrl.setMaxPage = function (items) {
ctrl.maxPage(Math.floor(items.length / ctrl.itemsPerPage() + 1));
return items;
};
ctrl.paginate = function (items) {
let count = parseInt(ctrl.itemsPerPage());
let from = (parseInt(ctrl.currentPage()) - 1) * count;
let to = from + count;
return items.slice(from, to);
};
};
Datadisplay.view = function (ctrl, args) {
let data = args.data.then(ctrl.setMaxPage).then(ctrl.paginate);
return m('div', [
m.component(Pagination, {
maxPage: ctrl.maxPage,
currentPage: ctrl.currentPage
}),
m.component(Datatable, {
columns: args.columns,
names: args.names,
data: data()
}),
m.component(Pagination, {
maxPage: ctrl.maxPage,
currentPage: ctrl.currentPage
})
]);
};
|
const m = require('mithril');
const Pagination = require('../components/pagination');
const Datatable = require('../components/datatable');
const Datadisplay = module.exports = {};
Datadisplay.controller = function () {
let ctrl = this;
ctrl.currentPage = m.prop(m.route.param('page') || 1);
ctrl.itemsPerPage = m.prop(10);
ctrl.maxPage = m.prop(1);
ctrl.setMaxPage = function (items) {
ctrl.maxPage(Math.floor(items.length / ctrl.itemsPerPage() + 1));
return items;
};
ctrl.paginate = function (items) {
let count = parseInt(ctrl.itemsPerPage());
let from = (parseInt(ctrl.currentPage()) - 1) * count;
let to = from + count;
return items.slice(from, to);
};
};
Datadisplay.view = function (ctrl, args) {
let data = args.data.then(ctrl.setMaxPage).then(ctrl.paginate);
return m('div', [
m.component(Pagination, {
maxPage: ctrl.maxPage,
currentPage: ctrl.currentPage
}),
m.component(Datatable, {
columns: args.columns,
names: args.names,
data: data()
})
]);
};
|
Fix version (0.2.2 never made it to PyPI)
|
#!/usr/bin/env python
# coding: utf8
# Copyright 2014-2015 Vincent Jacques <vincent@vincent-jacques.net>
import contextlib
import os
import setuptools
import setuptools.command.test
version = "0.2.3"
setuptools.setup(
name="LowVoltage",
version=version,
description="Standalone DynamoDB client not hiding any feature",
author="Vincent Jacques",
author_email="vincent@vincent-jacques.net",
url="http://jacquev6.github.io/LowVoltage",
packages=sorted(dirpath.replace("/", ".") for dirpath, dirnames, filenames in os.walk("LowVoltage") if "__init__.py" in filenames),
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Environment :: Web Environment",
],
test_suite="LowVoltage.tests" if "AWS_ACCESS_KEY_ID" in os.environ else "LowVoltage.tests.local",
test_loader="testresources:TestLoader",
use_2to3=True,
)
|
#!/usr/bin/env python
# coding: utf8
# Copyright 2014-2015 Vincent Jacques <vincent@vincent-jacques.net>
import contextlib
import os
import setuptools
import setuptools.command.test
version = "0.2.1"
setuptools.setup(
name="LowVoltage",
version=version,
description="Standalone DynamoDB client not hiding any feature",
author="Vincent Jacques",
author_email="vincent@vincent-jacques.net",
url="http://jacquev6.github.io/LowVoltage",
packages=sorted(dirpath.replace("/", ".") for dirpath, dirnames, filenames in os.walk("LowVoltage") if "__init__.py" in filenames),
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Environment :: Web Environment",
],
test_suite="LowVoltage.tests" if "AWS_ACCESS_KEY_ID" in os.environ else "LowVoltage.tests.local",
test_loader="testresources:TestLoader",
use_2to3=True,
)
|
Fix bugs in example codes.
|
package main
import (
"gearman"
"log"
)
func main() {
client := gearman.NewClient()
defer client.Close()
if err := client.AddServer("127.0.0.1:4730"); err != nil {
log.Fatalln(err)
}
echo := []byte("Hello\x00 world")
if data, err := client.Echo(echo); err != nil {
log.Fatalln(string(data))
}
handle, err := client.Do("ToUpper", echo, gearman.JOB_NORMAL)
if err != nil {
log.Fatalln(err)
} else {
log.Println(handle)
/*job := <-client.JobQueue
if data, err := job.Result(); err != nil {
log.Fatalln(err)
} else {
log.Println(string(data))
}*/
}
known, running, numerator, denominator, err := client.Status(handle)
if err != nil {
log.Fatalln(err)
}
if !known {
log.Println("Unknown")
}
if running {
log.Printf("%g%%\n", float32(numerator)*100/float32(denominator))
} else {
log.Println("Not running")
}
}
|
package main
import (
"gearman"
"log"
)
func main() {
client := gearman.NewClient()
defer client.Close()
client.AddServer("127.0.0.1:4730")
echo := []byte("Hello\x00 world")
if data, err := client.Echo(echo); err != nil {
log.Println(string(data))
}
handle, err := client.Do("ToUpper", echo, gearman.JOB_NORMAL)
if err != nil {
log.Println(err)
} else {
log.Println(handle)
job := <-client.JobQueue
if data, err := job.Result(); err != nil {
log.Println(err)
} else {
log.Println(string(data))
}
}
known, running, numerator, denominator, err := client.Status(handle)
if err != nil {
log.Println(err)
}
if !known {
log.Println("Unknown")
}
if running {
log.Printf("%g%%\n", float32(numerator)*100/float32(denominator))
} else {
log.Println("Not running")
}
}
|
Move eye down a bit
|
from django import template
from metabotnik.models import project_status_choices
register = template.Library()
@register.filter
def nicestatus(dbval):
'Converts a db status choice into a more user-friendly version'
for val, stat in project_status_choices:
if dbval == val:
return stat
return dbval
@register.simple_tag
def json_to_overlay(datadict):
buf = []
width, height = float(datadict['width']), float(datadict['height'])
for i,obj in enumerate(datadict.get('images', [])):
if 'LINK' in obj.get('metadata', {}):
tmp = (obj['pk'], obj['x']+10, obj['y']+100)
buf.append(u"{id: 'overlay%s', px:%s, py:%s}" % tmp)
return u'\n,'.join(buf)
|
from django import template
from metabotnik.models import project_status_choices
register = template.Library()
@register.filter
def nicestatus(dbval):
'Converts a db status choice into a more user-friendly version'
for val, stat in project_status_choices:
if dbval == val:
return stat
return dbval
@register.simple_tag
def json_to_overlay(datadict):
buf = []
width, height = float(datadict['width']), float(datadict['height'])
for i,obj in enumerate(datadict.get('images', [])):
if 'LINK' in obj.get('metadata', {}):
tmp = (obj['pk'], obj['x'], obj['y'])
buf.append(u"{id: 'overlay%s', px:%s, py:%s}" % tmp)
return u'\n,'.join(buf)
|
Use __dirname for source dir
|
module.exports = {
entry: {
app: __dirname + '/src/init.js'
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: { presets: [ 'es2015', 'react' ] }
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}]
},
devtool: 'source-map'
};
|
module.exports = {
entry: {
app: './src/init.js'
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: { presets: [ 'es2015', 'react' ] }
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}]
},
devtool: 'source-map'
};
|
Make it clear that you can set 'pathPrefix'
|
import rc from 'rc'
export default rc('david', {
brains: {
cacheTime: 86400000
},
github: {
api: {
version: '3.0.0',
protocol: 'https',
host: 'api.github.com',
pathPrefix: null,
timeout: 5000,
caFile: null
},
protocol: 'https',
host: 'github.com',
oauth: {
clientId: null,
secret: null
},
token: null
},
npm: {
hostname: 'https://www.npmjs.com',
options: {
registry: 'http://registry.npmjs.org'
},
feed: 'https://skimdb.npmjs.com/registry'
},
site: {
hostname: 'http://localhost:1337'
},
db: {
path: 'data'
},
nsp: {
syncAdvisoriesInterval: 3600000
},
public: {
siteUrl: 'http://localhost:1337',
apiUrl: 'http://localhost:1337',
githubUrl: 'https://github.com',
github: {
protocol: 'https',
host: 'github.com',
oauth: {
clientId: null
}
},
google: {
trackingId: ''
}
}
})
|
import rc from 'rc'
export default rc('david', {
brains: {
cacheTime: 86400000
},
github: {
api: {
version: '3.0.0',
protocol: 'https',
host: 'api.github.com',
timeout: 5000,
caFile: null
},
protocol: 'https',
host: 'github.com',
oauth: {
clientId: null,
secret: null
},
token: null
},
npm: {
hostname: 'https://www.npmjs.com',
options: {
registry: 'http://registry.npmjs.org'
},
feed: 'https://skimdb.npmjs.com/registry'
},
site: {
hostname: 'http://localhost:1337'
},
db: {
path: 'data'
},
nsp: {
syncAdvisoriesInterval: 3600000
},
public: {
siteUrl: 'http://localhost:1337',
apiUrl: 'http://localhost:1337',
githubUrl: 'https://github.com',
github: {
protocol: 'https',
host: 'github.com',
oauth: {
clientId: null
}
},
google: {
trackingId: ''
}
}
})
|
Make running FTs against staging a bit less verbose
|
# -*- coding: utf-8 -*-
from unipath import Path
import subprocess
THIS_FOLDER = Path(__file__).parent
def reset_database(host):
subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host),
'--hide=everything,status'],
cwd=THIS_FOLDER)
def create_user(host, user, email, password):
subprocess.check_call(['fab', 'create_user:user={},password={},email={}' \
.format(user, password, email), '--host={}'.format(host),
'--hide=everything,status'],
cwd=THIS_FOLDER)
def get_sitename(host):
return subprocess.check_output(['fab', 'get_sitename',
'--host={}'.format(host), '--hide=everything,status'],
cwd=THIS_FOLDER).decode().strip()
def create_project(host, user, name, description=''):
return subprocess.check_output(['fab',
'create_project:user={},name={},description={}'.format(user, name,
description), '--host={}'.format(host)], cwd=THIS_FOLDER)
def create_action(host, user, text, project=''):
return subprocess.check_output(['fab',
'create_action:user={},text={},project={}'.format(user, text, project),
'--host={}'.format(host)], cwd=THIS_FOLDER)
|
# -*- coding: utf-8 -*-
from unipath import Path
import subprocess
THIS_FOLDER = Path(__file__).parent
def reset_database(host):
subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host)],
cwd=THIS_FOLDER)
def create_user(host, user, email, password):
subprocess.check_call(['fab', 'create_user:user={},password={},email={}' \
.format(user, password, email), '--host={}'.format(host)],
cwd=THIS_FOLDER)
def get_sitename(host):
return subprocess.check_output(['fab', 'get_sitename',
'--host={}'.format(host), '--hide=everything,status'],
cwd=THIS_FOLDER).decode().strip()
def create_project(host, user, name, description=''):
return subprocess.check_output(['fab',
'create_project:user={},name={},description={}'.format(user, name,
description), '--host={}'.format(host)], cwd=THIS_FOLDER)
def create_action(host, user, text, project=''):
return subprocess.check_output(['fab',
'create_action:user={},text={},project={}'.format(user, text, project),
'--host={}'.format(host)], cwd=THIS_FOLDER)
|
Fix setting locale to the proper variable
|
import Ember from 'ember';
import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
i18n: Ember.inject.service(),
afterModel: function() {
const availableLocales = this.get('i18n.locales').toArray();
let locale;
// Works in Chrome and Firefox (editable in settings)
if (navigator.languages && navigator.languages.length) {
for (let lang of navigator.languages) {
if (availableLocales.contains(lang)) {
locale = lang;
break;
}
}
}
// Backup for Safari (uses system settings)
else if (navigator.language && availableLocales.contains(navigator.language)) {
locale = navigator.language;
}
if (locale)
this.set('i18n.locale', locale);
}
});
|
import Ember from 'ember';
import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
i18n: Ember.inject.service(),
afterModel: function() {
const availableLocales = this.get('i18n.locales').toArray();
let locale;
// Works in Chrome and Firefox (editable in settings)
if (navigator.languages && navigator.languages.length) {
for (let lang of navigator.languages) {
if (availableLocales.contains(lang)) {
locale = lang;
break;
}
}
}
// Backup for Safari (uses system settings)
else if (navigator.language && availableLocales.contains(navigator.language)) {
locale = navigator.language;
}
if (locale)
this.set('i18n.locale', navigator.language);
}
});
|
Watch on test files to automatically run tests task
|
var gulp = require("gulp");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var mocha = require("gulp-mocha");
var istanbul = require("gulp-istanbul");
var PATH_TO_SRC = "jquery.liteuploader.js";
var MINIFIED_FILE_NAME = "jquery.liteuploader.min.js";
gulp.task("default", ["watch", "tests"]);
gulp.task("watch", function () {
gulp.watch(["test/*.js", PATH_TO_SRC], ["minify", "tests"]);
});
gulp.task("minify", function() {
return gulp.src(PATH_TO_SRC)
.pipe(uglify({preserveComments: "license"}))
.pipe(rename(MINIFIED_FILE_NAME))
.pipe(gulp.dest("./"));
});
gulp.task("coverage", function () {
return gulp.src(PATH_TO_SRC)
.pipe(istanbul())
.pipe(istanbul.hookRequire());
});
gulp.task("tests", ["coverage"], function () {
return gulp.src(["test/*.js"])
.pipe(mocha())
.pipe(istanbul.writeReports())
.on("finish", function () {
console.log("Breakdown: file://" + __dirname + "/coverage/index.html");
});
});
|
var gulp = require("gulp");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var mocha = require("gulp-mocha");
var istanbul = require("gulp-istanbul");
var PATH_TO_SRC = "jquery.liteuploader.js";
var MINIFIED_FILE_NAME = "jquery.liteuploader.min.js";
gulp.task("default", ["watch", "tests"]);
gulp.task("watch", function () {
gulp.watch(PATH_TO_SRC, ["minify"]);
});
gulp.task("minify", function() {
return gulp.src(PATH_TO_SRC)
.pipe(uglify({preserveComments: "license"}))
.pipe(rename(MINIFIED_FILE_NAME))
.pipe(gulp.dest("./"));
});
gulp.task("coverage", function () {
return gulp.src(PATH_TO_SRC)
.pipe(istanbul())
.pipe(istanbul.hookRequire());
});
gulp.task("tests", ["coverage"], function () {
return gulp.src(["test/*.js"])
.pipe(mocha())
.pipe(istanbul.writeReports())
.on("finish", function () {
console.log("Breakdown: file://" + __dirname + "/coverage/index.html");
});
});
|
Fix a bug if mongoose path does not exist
|
var path = require('path');
var fs = require('extfs');
var mongoose = require('mongoose');
import { AbstractDB } from './AbstractDB';
import { Core } from '../Core/Core';
export class Mongo extends AbstractDB {
constructor(uri, options) {
super(uri, options);
}
/**
* Connect to mongodb
*
* @return {Promise}
*/
connect() {
this._linkMongoose();
return new Promise((resolve, reject) => {
mongoose.connect(this.uri, this.options);
this.connection = mongoose.connection;
this.connection.on('connected', () => {
this.isOpen = true;
resolve(this.connection)
});
this.connection.on('error', reject);
});
}
/**
* Close connection with mongodb
*/
close() {
this.isOpen = false;
return this.connection.close();
}
/**
* If the app has mongoose installed, replace its mongoose module with the mongoose module of rode
*
* @private
*/
_linkMongoose() {
var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose');
var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose');
if (fs.existsSync(mongoosePath) && fs.existsSync(appMongoosePath)) {
fs.removeSync(appMongoosePath);
fs.symlinkSync(mongoosePath, appMongoosePath);
}
}
}
|
var path = require('path');
var fs = require('extfs');
var mongoose = require('mongoose');
import { AbstractDB } from './AbstractDB';
import { Core } from '../Core/Core';
export class Mongo extends AbstractDB {
constructor(uri, options) {
super(uri, options);
}
/**
* Connect to mongodb
*
* @return {Promise}
*/
connect() {
this._linkMongoose();
return new Promise((resolve, reject) => {
mongoose.connect(this.uri, this.options);
this.connection = mongoose.connection;
this.connection.on('connected', () => {
this.isOpen = true;
resolve(this.connection)
});
this.connection.on('error', reject);
});
}
/**
* Close connection with mongodb
*/
close() {
this.isOpen = false;
return this.connection.close();
}
/**
* If the app has mongoose installed, replace its mongoose module with the mongoose module of rode
*
* @private
*/
_linkMongoose() {
var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose');
var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose');
if (fs.existsSync(appMongoosePath)) {
fs.removeSync(appMongoosePath);
fs.symlinkSync(mongoosePath, appMongoosePath);
}
}
}
|
Remove superfluous import by using the exception from the namespace.
|
import contextlib
import functools
import pluggy
import keyring.errors
hookimpl = pluggy.HookimplMarker("devpiclient")
# https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205
suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {})
def restore_signature(func):
# workaround for pytest-dev/pluggy#358
@functools.wraps(func)
def wrapper(url, username):
return func(url, username)
return wrapper
@hookimpl()
@restore_signature
@suppress(keyring.errors.KeyringError)
def devpiclient_get_password(url, username):
"""
>>> pluggy._hooks.varnames(devpiclient_get_password)
(('url', 'username'), ())
>>>
"""
return keyring.get_password(url, username)
|
import contextlib
import functools
import pluggy
import keyring
from keyring.errors import KeyringError
hookimpl = pluggy.HookimplMarker("devpiclient")
# https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205
suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {})
def restore_signature(func):
# workaround for pytest-dev/pluggy#358
@functools.wraps(func)
def wrapper(url, username):
return func(url, username)
return wrapper
@hookimpl()
@restore_signature
@suppress(KeyringError)
def devpiclient_get_password(url, username):
"""
>>> pluggy._hooks.varnames(devpiclient_get_password)
(('url', 'username'), ())
>>>
"""
return keyring.get_password(url, username)
|
Correct return type for removal of attribute
|
<?php
namespace Gt\Dom;
use DOMNode;
/**
* Represents an attribute on an Element object.
*
* In most DOM methods, you will probably directly retrieve the attribute as a
* string (e.g., Element::getAttribute()), but certain functions (e.g.,
* Element::getAttributeNode()) or means of iterating give Attr types.
*
* @property-read Element $ownerElement
* @property-read Element $parentNode
* @property-read Node|Element|null $firstChild
* @property-read Node|Element|null $lastChild
* @property-read Node|Element|null $previousSibling
* @property-read Node|Element|null $nextSibling
* @property-read Document $ownerDocument
*
* @method Element appendChild(DOMNode $newnode)
* @method Element cloneNode(bool $deep = false)
* @method Element insertBefore(DOMNode $newnode, DOMNode $refnode = null)
* @method Element removeChild(DOMNode $oldnode)
* @method Element replaceChild(DOMNode $newnode, DOMNode $oldnode)
*/
class Attr extends \DOMAttr {
public function remove():self {
$this->ownerElement->removeAttributeNode($this);
return $this;
}
}
|
<?php
namespace Gt\Dom;
use DOMNode;
/**
* Represents an attribute on an Element object.
*
* In most DOM methods, you will probably directly retrieve the attribute as a
* string (e.g., Element::getAttribute()), but certain functions (e.g.,
* Element::getAttributeNode()) or means of iterating give Attr types.
*
* @property-read Element $ownerElement
* @property-read Element $parentNode
* @property-read Node|Element|null $firstChild
* @property-read Node|Element|null $lastChild
* @property-read Node|Element|null $previousSibling
* @property-read Node|Element|null $nextSibling
* @property-read Document $ownerDocument
*
* @method Element appendChild(DOMNode $newnode)
* @method Element cloneNode(bool $deep = false)
* @method Element insertBefore(DOMNode $newnode, DOMNode $refnode = null)
* @method Element removeChild(DOMNode $oldnode)
* @method Element replaceChild(DOMNode $newnode, DOMNode $oldnode)
*/
class Attr extends \DOMAttr {
public function remove():self {
return $this->ownerElement->removeAttributeNode($this);
}
}
|
Fix missing card instance before extracting code for filenames
|
"""Implementation of packing and unpacking functions."""
import yaml
from glob import glob
from os.path import join as pjoin
import os
from librarian.card import Card
from librarian.library import Library
def pack(library, carddir):
"""Pack all ``.crd`` card files in the carddir into the given library."""
if os.path.exists(library):
os.remove(library)
lib = Library(library)
lib.create_db()
for cardpath in glob(pjoin(carddir, "*.crd")):
# Open card file and load it with yaml
with open(cardpath) as cardfile:
carddict = yaml.safe_load(cardfile)
# Load the card dict from file into a card object
card = Card().load(carddict)
# Save the card object to the library
lib.save_card(card)
def unpack(library, carddir):
"""Unpack all cards from the given library into carddir as .crd files."""
if not os.path.exists(carddir) or not os.path.isdir(carddir):
os.makedirs(carddir)
lib = Library(library)
cardpath = pjoin(carddir, "{0}.crd")
for card in lib.retrieve_all():
with open(cardpath.format(card.code), 'w') as cardfile:
yaml.dump(card.save(), cardfile, default_flow_style=False)
|
"""Implementation of packing and unpacking functions."""
import yaml
from glob import glob
from os.path import join as pjoin
import os
from librarian.card import Card
from librarian.library import Library
def pack(library, carddir):
"""Pack all ``.crd`` card files in the carddir into the given library."""
if os.path.exists(library):
os.remove(library)
lib = Library(library)
lib.create_db()
for cardpath in glob(pjoin(carddir, "*.crd")):
# Open card file and load it with yaml
with open(cardpath) as cardfile:
carddict = yaml.safe_load(cardfile)
# Load the card dict from file into a card object
card = Card().load(carddict)
# Save the card object to the library
lib.save_card(card)
def unpack(library, carddir):
"""Unpack all cards from the given library into carddir as .crd files."""
if not os.path.exists(carddir) or not os.path.isdir(carddir):
os.makedirs(carddir)
lib = Library(library)
cardpath = pjoin(carddir, "{0}.crd")
for card in lib.retrieve_all():
with open(cardpath.format(code), 'w') as cardfile:
yaml.dump(card.save(), cardfile, default_flow_style=False)
|
Add real code to demo
|
/*
* Copyright 2017 michael-simons.eu.
*
* 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 ac.simons.spring.boot.singleuser.demo;
import java.security.Principal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Simple demo application for this starter.
*
* @author Michael J. Simons, 2017-10-13
*/
@SpringBootApplication
public class Application {
@RestController
static class HelloWorldController {
@RequestMapping("/hello")
public String hello(Principal principal) {
return "Hello, " + principal.getName() + "\n";
}
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
/*
* Copyright 2017 michael-simons.eu.
*
* 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 ac.simons.spring.boot.singleuser.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Simple demo application for this starter.
*
* @author Michael J. Simons, 2017-10-13
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
[Fix] Check if database connexion is defined
|
'use strict';
/*global app,Sequelize,appdir */
global.Sequelize = require('sequelize');
var console = app.logger(app.config('core.log.prefix') + ':db');
var each = require('lodash/each');
var includeAll = require('include-all');
var setAssociation = function setAssociation(modelDef, modelName) {
/* istanbul ignore else*/
if (modelDef.associate !== null && typeof modelDef.associate === 'function') {
modelDef.associate();
console.debug('associate ' + modelName);
}
};
if (app.config('database.connections')) {
if (app.config('database.connections.options.logging')) {
app.config().set('database.connections.options.logging', console.debug);
console.log('query debug');
}
app.db = new Sequelize(
app.config('database.connections')
);
app.models = includeAll({
dirname: appdir + '/Models',
filter: /(.+)\.js$/
});
each(app.models, function eachModels(modelDef, modelName) {
global[modelName] = app.db.define(modelName, modelDef.attributes, modelDef.options);
console.debug('define ' + modelName);
});
each(app.models, setAssociation);
}
|
'use strict';
/*global app,Sequelize,appdir */
global.Sequelize = require('sequelize');
var console = app.logger(app.config('core.log.prefix') + ':db');
var each = require('lodash/each');
var includeAll = require('include-all');
var setAssociation = function setAssociation(modelDef, modelName) {
/* istanbul ignore else*/
if (modelDef.associate !== null && typeof modelDef.associate === 'function') {
modelDef.associate();
console.debug('associate ' + modelName);
}
};
if (app.config('database')) {
if (app.config('database.connections.options.logging')) {
app.config().set('database.connections.options.logging', console.debug);
console.log('query debug');
}
app.db = new Sequelize(
app.config('database.connections')
);
app.models = includeAll({
dirname: appdir + '/Models',
filter: /(.+)\.js$/
});
each(app.models, function eachModels(modelDef, modelName) {
global[modelName] = app.db.define(modelName, modelDef.attributes, modelDef.options);
console.debug('define ' + modelName);
});
each(app.models, setAssociation);
}
|
Print the stack info more clearly, when holding the global lock for too long
|
import threading
import contextlib
import time
import traceback
import logging
_lock = threading.Lock()
def prettyStack():
return "\n".join([line.strip() for line in traceback.format_stack()])
@contextlib.contextmanager
def lock():
before = time.time()
with _lock:
acquired = time.time()
took = acquired - before
if took > 0.1:
logging.error(
"Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict(
took=took, stack=prettyStack()))
yield
released = time.time()
took = released - acquired
if took > 0.3:
logging.error(
"Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict(
took=took, stack=prettyStack()))
def assertLocked():
assert not _lock.acquire(False)
return True
|
import threading
import contextlib
import time
import traceback
import logging
_lock = threading.Lock()
@contextlib.contextmanager
def lock():
before = time.time()
with _lock:
acquired = time.time()
took = acquired - before
if took > 0.1:
logging.error(
"Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict(
took=took, stack=traceback.format_stack()))
yield
released = time.time()
took = released - acquired
if took > 0.3:
logging.error(
"Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict(
took=took, stack=traceback.format_stack()))
def assertLocked():
assert not _lock.acquire(False)
return True
|
Change time_amount type,now handle float values
|
import os.path
from srtmod.srtmod import SrtMod
import argparse
def main():
parser = argparse.ArgumentParser(prog='SrtModPy',
description='Just adjusts the timing of subtitle files')
parser.add_argument('file_name', help='the subtitle to be modified')
parser.add_argument('time_amount', metavar='time_amount', type=float,
help='the amount of time to be added or subtracted to subtitle')
parser.add_argument('time_part',
help='it\'s the part of time to be modified', choices=['S', 'M'])
parser.add_argument('operation',
help='add or discount time to subtitle', choices=['/A', '/D'])
r = parser.parse_args()
time_amount = r.time_amount
file_name = r.file_name
time_part = r.time_part
operation = r.operation
try:
srt = SrtMod(file_name, time_amount, time_part, operation)
if srt.process():
print 'subtitle file was created successfully'
print 'file saved at :' + os.path.splitext(file_name)[0] \
+ '(modified).srt'
else:
print '\nsubtitle can not be processed'
except OverflowError:
print 'Exception: Invalid time amount for this operation'
if __name__ == '__main__':
main()
|
import os.path
from srtmod.srtmod import SrtMod
import argparse
def main():
parser = argparse.ArgumentParser(prog='SrtModPy',
description='Just adjusts the timing of subtitle files')
parser.add_argument('file_name', help='the subtitle to be modified')
parser.add_argument('time_amount', metavar='time_amount', type=int,
help='the amount of time to be added or subtracted to subtitle')
parser.add_argument('time_part',
help='it\'s the part of time to be modified', choices=['S', 'M'])
parser.add_argument('operation',
help='add or discount time to subtitle', choices=['/A', '/D'])
r = parser.parse_args()
time_amount = r.time_amount
file_name = r.file_name
time_part = r.time_part
operation = r.operation
try:
srt = SrtMod(file_name, time_amount, time_part, operation)
if srt.process():
print '\nsubtitle file was created successfully'
print 'file saved at :' + os.path.splitext(file_name)[0] \
+ '(modified).srt'
else:
print '\nsubtitle can not be processed'
except OverflowError:
print 'Exception: Invalid time amount for this operation'
if __name__ == '__main__':
main()
|
Fix test for nodejs v11 or higher
Fix test for nodejs v11 or higher
|
'use strict';
const rewire = require('rewire');
const sinon = require('sinon');
describe('debug', () => {
const debug = require('../../../lib/plugins/helper/debug');
const debugModule = rewire('../../../lib/plugins/helper/debug');
const inspect = require('util').inspect;
it('inspect simple object', () => {
const obj = { foo: 'bar' };
debug.inspectObject(obj).should.eql(inspect(obj));
});
it('inspect circular object', () => {
const obj = { foo: 'bar' };
obj.circular = obj;
debug.inspectObject(obj).should.eql(inspect(obj));
});
it('inspect deep object', () => {
const obj = { baz: { thud: 'narf', dur: { foo: 'bar', baz: { bang: 'zoom' } } } };
debug.inspectObject(obj, {depth: 2}).should.not.eql(inspect(obj, {depth: 5}));
debug.inspectObject(obj, {depth: 5}).should.eql(inspect(obj, {depth: 5}));
});
it('log should print to console', () => {
const spy = sinon.spy();
debugModule.__with__({
console: {
log: spy
}
})(() => {
debugModule.log('Hello %s from debug.log()!', 'World');
});
spy.args[0].should.eql(['Hello %s from debug.log()!', 'World']);
});
});
|
'use strict';
const rewire = require('rewire');
const sinon = require('sinon');
describe('debug', () => {
const debug = require('../../../lib/plugins/helper/debug');
const debugModule = rewire('../../../lib/plugins/helper/debug');
const inspect = require('util').inspect;
it('inspect simple object', () => {
const obj = { foo: 'bar' };
debug.inspectObject(obj).should.eql(inspect(obj));
});
it('inspect circular object', () => {
const obj = { foo: 'bar' };
obj.circular = obj;
debug.inspectObject(obj).should.eql(inspect(obj));
});
it('inspect deep object', () => {
const obj = { baz: { thud: 'narf', dur: { foo: 'bar', baz: { bang: 'zoom' } } } };
debug.inspectObject(obj).should.not.eql(inspect(obj, {depth: 5}));
debug.inspectObject(obj, {depth: 5}).should.eql(inspect(obj, {depth: 5}));
});
it('log should print to console', () => {
const spy = sinon.spy();
debugModule.__with__({
console: {
log: spy
}
})(() => {
debugModule.log('Hello %s from debug.log()!', 'World');
});
spy.args[0].should.eql(['Hello %s from debug.log()!', 'World']);
});
});
|
Set root view depending on what views are enabled
|
"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
Remove type parameters from IterableSubject, MultisetSubject, and MultimapSubject.
See https://github.com/google/truth/issues/192
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=109722143
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster.testdata.template;
import com.google.common.truth.IterableSubject;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.util.Collection;
/**
* Tests for {@code UFreeIdent} accepting two references to the same wildcard.
*
* @author Kurt Alfred Kluever
*/
public class WildcardUnificationTemplate {
@BeforeTemplate
static void containsAllOf(IterableSubject subject, Collection<?> expected) {
subject.hasSize(expected.size());
subject.containsAllIn(expected);
}
@AfterTemplate
static void containsExactly(IterableSubject subject, Collection<?> expected) {
subject.containsExactlyElementsIn(expected);
}
}
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster.testdata.template;
import com.google.common.truth.IterableSubject;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.util.Collection;
/**
* Tests for {@code UFreeIdent} accepting two references to the same wildcard.
*
* @author kak@google.com (Kurt Kluever)
*/
public class WildcardUnificationTemplate {
@BeforeTemplate
static void containsAllOf(IterableSubject<?, ?, ?> subject, Collection<?> expected) {
subject.hasSize(expected.size());
subject.containsAllIn(expected);
}
@AfterTemplate
static void containsExactly(IterableSubject<?, ?, ?> subject, Collection<?> expected) {
subject.containsExactlyElementsIn(expected);
}
}
|
Switch phase tag to BETA
|
from django.conf import settings
from django.utils.translation import ugettext as _, get_language
from django.utils.safestring import mark_safe
def globals(request):
return {
# Application Title (Populates <title>)
'app_title': _('Make a Plea: Traffic offences') + ' - GOV.UK',
# Proposition Title (Populates proposition header)
'proposition_title': _('Make a Plea: Traffic offences'),
# Current Phase (Sets the current phase and the colour of phase tags). Presumed values: alpha, beta, live
'phase': 'beta',
# Product Type (Adds class to body based on service type). Presumed values: information, service
'product_type': 'service',
# Google Analytics ID (Tracking ID for the service)
'ga_id': 'UA-53811587-1',
# Version number
'version': settings.VERSION,
'html_lang': get_language,
'skip_link_message': _('Skip to main content'),
'logo_link_title': _('Go to the GOV.UK homepage'),
'crown_copyright_message': mark_safe(_('© Crown copyright'))
}
|
from django.conf import settings
from django.utils.translation import ugettext as _, get_language
from django.utils.safestring import mark_safe
def globals(request):
return {
# Application Title (Populates <title>)
'app_title': _('Make a Plea: Traffic offences') + ' - GOV.UK',
# Proposition Title (Populates proposition header)
'proposition_title': _('Make a Plea: Traffic offences'),
# Current Phase (Sets the current phase and the colour of phase tags). Presumed values: alpha, beta, live
'phase': 'alpha',
# Product Type (Adds class to body based on service type). Presumed values: information, service
'product_type': 'service',
# Google Analytics ID (Tracking ID for the service)
'ga_id': 'UA-53811587-1',
# Version number
'version': settings.VERSION,
'html_lang': get_language,
'skip_link_message': _('Skip to main content'),
'logo_link_title': _('Go to the GOV.UK homepage'),
'crown_copyright_message': mark_safe(_('© Crown copyright'))
}
|
Change check to check for Game.cpu.tickLimit
|
'use strict';
require('require');
require('prototype_creep_startup_tasks');
require('prototype_creep_move');
require('prototype_roomPosition');
require('prototype_room_init');
require('prototype_room_costmatrix');
require('visualizer');
require('screepsplus');
if (config.profiler.enabled) {
try {
var profiler = require('screeps-profiler');
profiler.enable();
} catch (e) {
console.log('screeps-profiler not found');
config.profiler.enabled = false;
}
}
brain.stats.init();
var main = function() {
if (Game.cpu.bucket < Game.cpu.tickLimit) {
console.log('Skipping tick ' + Game.time + ' due to lack of CPU.');
return;
}
brain.prepareMemory();
brain.handleNextroom();
brain.handleSquadmanager();
brain.handleIncomingTransactions();
brain.stats.addRoot();
Memory.myRooms = _.map(_.filter(Game.rooms, r => r.execute()), r => r.name);
if (config.visualizer.enabled && config.visualizer.refresh) {
visualizer.render();
}
brain.stats.add(['cpu'], {
used: Game.cpu.getUsed()
});
};
module.exports.loop = function() {
if (config.profiler.enabled) {
profiler.wrap(function() {
main();
});
} else {
main();
}
};
|
'use strict';
require('require');
require('prototype_creep_startup_tasks');
require('prototype_creep_move');
require('prototype_roomPosition');
require('prototype_room_init');
require('prototype_room_costmatrix');
require('visualizer');
require('screepsplus');
if (config.profiler.enabled) {
try {
var profiler = require('screeps-profiler');
profiler.enable();
} catch (e) {
console.log('screeps-profiler not found');
config.profiler.enabled = false;
}
}
brain.stats.init();
var main = function() {
if (Game.cpu.bucket < Game.cpu.tickLimit * 2) {
console.log('Skipping tick ' + Game.time + ' due to lack of CPU.');
return;
}
brain.prepareMemory();
brain.handleNextroom();
brain.handleSquadmanager();
brain.handleIncomingTransactions();
brain.stats.addRoot();
Memory.myRooms = _.map(_.filter(Game.rooms, r => r.execute()), r => r.name);
if (config.visualizer.enabled && config.visualizer.refresh) {
visualizer.render();
}
brain.stats.add(['cpu'], {
used: Game.cpu.getUsed()
});
};
module.exports.loop = function() {
if (config.profiler.enabled) {
profiler.wrap(function() {
main();
});
} else {
main();
}
};
|
Fix is new check in User.save()
|
# -*- coding: utf8 -*-
from django.contrib.auth.models import AbstractUser
from django.utils.functional import cached_property
from social.apps.django_app.default.models import UserSocialAuth
from frigg.helpers import github
class User(AbstractUser):
@cached_property
def github_token(self):
try:
return self.social_auth.get(provider='github').extra_data['access_token']
except UserSocialAuth.DoesNotExist:
return
def save(self, *args, **kwargs):
create = self.pk is None
super(User, self).save(*args, **kwargs)
if create:
self.update_repo_permissions()
def update_repo_permissions(self):
if self.github_token:
github.update_repo_permissions(self)
|
# -*- coding: utf8 -*-
from django.contrib.auth.models import AbstractUser
from django.utils.functional import cached_property
from social.apps.django_app.default.models import UserSocialAuth
from frigg.helpers import github
class User(AbstractUser):
@cached_property
def github_token(self):
try:
return self.social_auth.get(provider='github').extra_data['access_token']
except UserSocialAuth.DoesNotExist:
return
def save(self, *args, **kwargs):
create = not hasattr(self, 'id')
super(User, self).save(*args, **kwargs)
if create:
self.update_repo_permissions()
def update_repo_permissions(self):
if self.github_token:
github.update_repo_permissions(self)
|
Update some documentation for the interface
[ci skip]
|
<?php
/**
* @copyright 2018 Vladimir Jimenez
* @license https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
*/
namespace allejo\stakx\MarkupEngine;
/**
* This interface defines the markup engines stakx will know how to parse as ContentItems and as regular text within
* Twig by registering custom tags and filters.
*
* @since 0.2.0
*/
interface MarkupEngine
{
const CONTAINER_TAG = 'stakx.markup_engine';
/**
* Get the custom tag and filter to register with our templating engine.
*
* For the Markdown engine, we'd be registering a tag called 'markdown' and a filter called 'markdown' to support
* the following example.
*
* ```twig
* {% markdown %}my content{% endmarkdown %}
*
* {{ 'my content' | markdown }}
* ```
*
* @since 0.2.0
*
* @return null|string If null, then no tag or filter will be registered.
*/
public function getTemplateTag();
/**
* List of file extensions this engine will be charged with parsing.
*
* @since 0.2.0
*
* @return string[]
*/
public function getExtensions();
/**
* Parse a given string using this engine.
*
* @param string $content
*
* @since 0.2.0
*
* @return string
*/
public function parse($content);
}
|
<?php
/**
* @copyright 2018 Vladimir Jimenez
* @license https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
*/
namespace allejo\stakx\MarkupEngine;
interface MarkupEngine
{
const CONTAINER_TAG = 'stakx.markup_engine';
/**
* Get the custom tag and filter to register with our templating engine.
*
* For the Markdown engine, we'd be registering a tag called 'markdown' and a filter called 'markdown' to support
* the following example.
*
* ```twig
* {% markdown %}{% endmarkdown %}
*
* {{ 'my content' | markdown }}
* ```
*
* @return null|string If null, then no tag or filter will be registered.
*/
public function getTemplateTag();
/**
* List of extensions this engine will accept and parse.
*
* @return string[]
*/
public function getExtensions();
/**
* Parse a given string using this engine.
*
* @param string $content
*
* @return string
*/
public function parse($content);
}
|
Remove empty lines in comments.
|
import unittest
import numpy
import chainer.functions as F
from chainer import testing
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.unary_math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
|
import unittest
import numpy
import chainer.functions as F
from chainer import testing
#
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.unary_math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
|
Fix typo in the Discord plugin.
|
from plumeria.command import commands, channel_only
from plumeria.message import Response
@commands.register('roles', category='Discord')
@channel_only
async def roles(message):
"""
Gets the roles in the current server, including their name and ID. Intended for development purposes.
Example::
/roles
Response::
bot (160143463784458624), admin (160143463784458624)
"""
roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles)
return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles]))
@commands.register('user id', 'userid', category='Discord')
async def userid(message):
"""
Gets your own Discord user ID for development purposes.
Example::
/userid
Response::
43463109290000434
"""
return Response(message.author.id)
|
from plumeria.command import commands, channel_only
from plumeria.message import Response
@commands.register('roles', category='Discord')
@channel_only
async def roles(message):
"""
Gets the roles in the current server, including their name and ID. Intended for development purposes.
Example::
/roles
Response::
bot (160143463784458624), admin (160143463784458624)
"""
roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles)
return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles]))
@commands.register('user id', ''userid', category='Discord')
async def userid(message):
"""
Gets your own Discord user ID for development purposes.
Example::
/userid
Response::
43463109290000434
"""
return Response(message.author.id)
|
Fix the HHVM fail as it converts html entities to codes instead of abreviations.
|
<?php
/**
* This file is part of slick/filter package
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Slick\Tests\Filter;
use PHPUnit_Framework_TestCase as TestCase;
use Slick\Filter\HtmlEntities;
/**
* Html Entities filter test case
*
* @package Slick\Tests\Filter
* @author Filipe Silva <silvam.filipe@gmail.com>
*/
class HtmlEntitiesTest extends TestCase
{
/**
* @var HtmlEntities
*/
protected $filter;
/**
* Create the SUT html entities filter object
*/
protected function setUp()
{
parent::setUp();
$this->filter = new HtmlEntities();
}
/**
* Should convert special characters tho html entities
* @test
*/
public function filterHtmlEntities()
{
$values = '&';
$expected = '&';
try {
$this->assertEquals($expected, $this->filter->filter($values));
} catch (\Exception $caught) {
$this->assertEquals('&', $this->filter->filter($values));
}
}
}
|
<?php
/**
* This file is part of slick/filter package
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Slick\Tests\Filter;
use PHPUnit_Framework_TestCase as TestCase;
use Slick\Filter\HtmlEntities;
/**
* Html Entities filter test case
*
* @package Slick\Tests\Filter
* @author Filipe Silva <silvam.filipe@gmail.com>
*/
class HtmlEntitiesTest extends TestCase
{
/**
* @var HtmlEntities
*/
protected $filter;
/**
* Create the SUT html entities filter object
*/
protected function setUp()
{
parent::setUp();
$this->filter = new HtmlEntities();
}
/**
* Should convert special characters tho html entities
* @test
*/
public function filterHtmlEntities()
{
$values = '&';
$expected = '&';
$this->assertEquals($expected, $this->filter->filter($values));
}
}
|
Set timeout for loader to 5000
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree
//= require d3
$(function(){ $(document).foundation(); });
var loader = document.getElementById('loader');
startLoading();
finishedLoading();
function startLoading() {
loader.className = '';
}
function finishedLoading() {
loader.className = 'done';
setTimeout(function() {
loader.className = 'hide';
}, 5000);
}
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree
//= require d3
$(function(){ $(document).foundation(); });
var loader = document.getElementById('loader');
startLoading();
finishedLoading();
function startLoading() {
loader.className = '';
}
function finishedLoading() {
loader.className = 'done';
setTimeout(function() {
loader.className = 'hide';
}, 1000);
}
|
Update to load dynamically the module selected by user.
|
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
|
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
|
Add browser test case for applyAll
|
'use strict';
/*
load('rgb8.png').then(function (a) {
var b = a.clone().invert();
setLeft(a);
setRight(b);
});
*/
/*load('rgb8.png').then(function (a) {
setLeft(a);
setInterval(move, 25);
var x = 0;
function move() {
setRight(a.crop({x: x++, width: 200, height:200}));
}
});
*/
load('cells.jpg').then(function (img) {
//setLeft(a);
console.time("invertGetSet");
for (var i=0; i<20; i++) {
img.invertGetSet();
}
console.timeEnd("invertGetSet");
console.time("invertApply");
for (var i=0; i<20; i++) {
img.invertApply();
}
console.timeEnd("invertApply");
console.time("invertApplyAll");
for (var i=0; i<20; i++) {
img.invertApplyAll();
}
console.timeEnd("invertApplyAll");
console.time("invertOneLoop");
for (var i=0; i<20; i++) {
img.invertOneLoop();
}
console.timeEnd("invertOneLoop");
// setRight(a);
});
|
'use strict';
/*
load('rgb8.png').then(function (a) {
var b = a.clone().invert();
setLeft(a);
setRight(b);
});
*/
/*load('rgb8.png').then(function (a) {
setLeft(a);
setInterval(move, 25);
var x = 0;
function move() {
setRight(a.crop({x: x++, width: 200, height:200}));
}
});
*/
load('cells.jpg').then(function (img) {
//setLeft(a);
console.time("invert");
for (var i=0; i<20; i++) {
img.invert();
}
console.timeEnd("invert");
console.time("invertApply");
for (var i=0; i<20; i++) {
img.invertApply();
}
console.timeEnd("invertApply");
console.time("invertApplyAll");
for (var i=0; i<20; i++) {
img.invertApplyAll();
}
console.timeEnd("invertApplyAll");
console.time("invertOneLoop");
for (var i=0; i<20; i++) {
img.invertOneLoop();
}
console.timeEnd("invertOneLoop");
// setRight(a);
});
|
Fix load_plugin loop loading only one plugin
|
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
tmp_path = path
if os.path.isdir(os.path.join(tmp_path, filename)) and os.path.isfile(os.path.join(tmp_path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [tmp_path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
if os.path.isdir(os.path.join(path, filename)) and os.path.isfile(os.path.join(path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
Add extend method to carpenter contract
|
<?php
namespace Michaeljennings\Carpenter\Contracts;
use Closure;
interface Carpenter
{
/**
* Add a table closure into the table collection
*
* @param string $name
* @param callable|string $table
*/
public function add($name, $table);
/**
* Retrieve a table from the table collection and run the closure
*
* @param string $name
* @return Table
* @throws CarpenterCollectionException
*/
public function get($name);
/**
* Create a new table without using the table collection.
*
* @param string $name
* @param callable $callback
* @return Table
*/
public function make($name, Closure $callback);
/**
* Set a manager extension.
*
* @param string $manager
* @param string $key
* @param string|Closure $extension
* @return $this
*/
public function extend($manager, $key, $extension);
}
|
<?php
namespace Michaeljennings\Carpenter\Contracts;
use Closure;
interface Carpenter
{
/**
* Add a table closure into the table collection
*
* @param string $name
* @param callable|string $table
*/
public function add($name, $table);
/**
* Retrieve a table from the table collection and run the closure
*
* @param string $name
* @return Table
* @throws CarpenterCollectionException
*/
public function get($name);
/**
* Create a new table without using the table collection.
*
* @param string $name
* @param callable $callback
* @return Table
*/
public function make($name, Closure $callback);
}
|
Use Hamming distance for efficiency
Hamming distance is faster when strings are of same length (Hamming is a
special case of Levenshtein).
|
# Open list of correcly-spelled words.
wordFile = open("words.txt")
threshold = 8
listOfWords = input().split()
index = 0
# Compute Levenshtein distance
def lev(a, b):
if min(len(a), len(b)) == 0:
return max(len(a), len(b))
elif len(a) == len(b):
# Use Hamming Distance (special case)
return sum(x != y for x, y in zip(a, b))
else:
return min(lev(a[:-1], b) + 1, lev(a, b[:-1]) + 1,
lev(a[:-1], b[:-1]) + int(not a[-1] == b[-1]))
for x in listOfWords:
replacement = (x, threshold + 1)
for word in wordFile:
x = x.lower()
word = word[:-1].lower()
if x == word:
replacement = (x, 0)
break # Some words may actually be spelled correctly!
d = lev(x, word)
if (d < threshold) and (replacement[1] > d):
replacement = (word, d)
listOfWords[index] = replacement[0]
index += 1
wordFile.seek(0)
print(*listOfWords)
|
# Open list of correcly-spelled words.
wordFile = open("words.txt")
threshold = 8
listOfWords = input().split()
index = 0
def lev(a, b):
if min(len(a), len(b)) == 0:
return max(len(a), len(b))
else:
return min(lev(a[:-1], b) + 1, lev(a, b[:-1]) + 1,
lev(a[:-1], b[:-1]) + int(not a == b))
for x in listOfWords:
replacement = (x, threshold + 1)
for word in wordFile:
x = x.lower()
word = word[:-1].lower()
if x == word:
replacement = (x, 0)
break # Some words may actually be spelled correctly!
d = lev(x, word)
if (d < threshold) and (replacement[1] > d):
replacement = (word, d)
listOfWords[index] = replacement[0]
index += 1
print(*listOfWords)
|
Fix parameters in task call
|
import os
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR,
DJ_EXPERIMENT_DATA_DIR)
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
# sleep 10 seconds to ensure the task has been finished
time.sleep(10)
# now the task should be finished and ready method will return True
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
rcmdatadir = os.path.join(DJ_EXPERIMENT_BASE_DATA_DIR,
DJ_EXPERIMENT_DATA_DIR)
result1 = netcdf_save.delay(14, rcmdatadir)
print 'Task netcdf finished? ', result1.ready()
print 'Task result1: ', result1.result
time.sleep(10)
print 'Task netcdf finished? ', result1.ready()
print 'Task result1: ', result1.result
|
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
# sleep 10 seconds to ensure the task has been finished
time.sleep(10)
# now the task should be finished and ready method will return True
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
result1 = netcdf_save.delay(14, '')
print 'Task netcdf finished? ', result1.ready()
print 'Task result1: ', result1.result
time.sleep(10)
print 'Task netcdf finished? ', result1.ready()
print 'Task result1: ', result1.result
|
Use dotenv to access env vars with process env
|
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const uri = `mongodb://${process.env.MONGO_USERNAME}:${process.env
.MONGO_PASSWORD}@${process.env.MONGO_ADDRESS}`;
mongoose.Promise = global.Promise;
mongoose.connect(uri, { useMongoClient: true, reconnectTries: 30 });
mongoose.connection.on('connecting', () => {
console.dir({ Mongo: 'connecting..' }, { colors: true });
});
mongoose.connection.on('connected', () => {
console.dir({ Mongo: 'connected' }, { colors: true });
});
mongoose.connection.on('reconnected', () => {
console.dir({ Mongo: 'reconnected' }, { colors: true });
});
mongoose.connection.on('disconnected', () => {
console.dir({ Mongo: 'disconnected' }, { colors: true });
});
mongoose.connection.on('error', err => {
console.log('Mongoose failed to connect: ', err);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('DB disconnected through terminal');
process.exit(0);
});
});
export default mongoose;
|
import mongoose from 'mongoose';
const uri = `mongodb://${process.env.MONGO_USERNAME}:${process.env
.MONGO_PASSWORD}@${process.env.MONGO_ADDRESS}`;
mongoose.Promise = global.Promise;
mongoose.connect(uri, { useMongoClient: true, reconnectTries: 30 });
mongoose.connection.on('connecting', () => {
console.dir({ Mongo: 'connecting..' }, { colors: true });
});
mongoose.connection.on('connected', () => {
console.dir({ Mongo: 'connected' }, { colors: true });
});
mongoose.connection.on('reconnected', () => {
console.dir({ Mongo: 'reconnected' }, { colors: true });
});
mongoose.connection.on('disconnected', () => {
console.dir({ Mongo: 'disconnected' }, { colors: true });
});
mongoose.connection.on('error', err => {
console.log('Mongoose failed to connect: ', err);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('DB disconnected through terminal');
process.exit(0);
});
});
export default mongoose;
|
Remove watch-statement from default builds
|
var gulp = require('gulp')
, compass = require('gulp-compass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(compass({
style: 'compressed',
css: 'css',
sass: 'sass'
}))
.on('success', function (msg) {
console.log('Compiled '+msg);
})
.on('error', function (err) {
console.log('Carp! An error occured: '+err);
});
});
gulp.task('watch', function () {
gulp.watch('sass/**/*.scss', ['sass']);
});
watcher.on('change', function (evt) {
console.log('[watcher] File '+evt.path.replace(/.*(?=sass)/,'')+' was '+evt.type+', compiling...');
});
gulp.task('ci', ['sass']);
gulp.task('default', ['sass']);
|
var gulp = require('gulp')
, compass = require('gulp-compass')
, watcher = gulp.watch('sass/**/*.scss', ['sass']);
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(compass({
style: 'compressed',
css: 'css',
sass: 'sass'
}))
.on('success', function (msg) {
console.log('Compiled '+msg);
})
.on('error', function (err) {
console.log('Carp! An error occured: '+err);
});
});
watcher.on('change', function (evt) {
console.log('[watcher] File '+evt.path.replace(/.*(?=sass)/,'')+' was '+evt.type+', compiling...');
});
gulp.task('ci', ['sass']);
gulp.task('default', ['sass']);
|
Add build package.json to blacklist
|
// @flow
const path = require('path');
/**
* This list is basically copy pasted from Metro Bundler but the tests
* folders are excluded so we can execute tests in the Playground.
*
* TODO: do this only in the "playground" environment (not in production)
*
* See: https://github.com/facebook/metro/blob/01ab028d4fb3600c89438b0b7916ec8350f8f71a/packages/metro/src/blacklist.js#L17
*/
const sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/\.build[/\\].*/,
// /.*\/__tests__\/.*/,
];
const config = {
getBlacklistRE() {
return new RegExp(
'(' +
sharedBlacklist
.map(regexp => regexp.source.replace(/\//g, path.sep))
.join('|') +
')$',
);
},
};
module.exports = config;
|
// @flow
const path = require('path');
/**
* This list is basically copy pasted from Metro Bundler but the tests
* folders are excluded so we can execute tests in the Playground.
*
* TODO: do this only in the "playground" environment (not in production)
*
* See: https://github.com/facebook/metro/blob/01ab028d4fb3600c89438b0b7916ec8350f8f71a/packages/metro/src/blacklist.js#L17
*/
const sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
// /.*\/__tests__\/.*/,
];
const config = {
getBlacklistRE() {
return new RegExp(
'(' +
sharedBlacklist
.map(regexp => regexp.source.replace(/\//g, path.sep))
.join('|') +
')$',
);
},
};
module.exports = config;
|
Add optional dependency on arpy
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
"ar": ["arpy==1.1.1"],
}
)
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
}
)
|
Add tests for dependency injection
|
<?php
/**
* This file belongs to Kreta.
* The source code of application includes a LICENSE file
* with all information about license.
*
* @author benatespina <benatespina@gmail.com>
* @author gorkalaucirica <gorka.lauzirika@gmail.com>
*/
namespace spec\Kreta\Bundle\CommentBundle\DependencyInjection;
use PhpSpec\ObjectBehavior;
/**
* Class KretaCommentExtensionSpec.
*
* @package spec\Kreta\Bundle\CommentBundle\DependencyInjection
*/
class KretaCommentExtensionSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Kreta\Bundle\CommentBundle\DependencyInjection\KretaCommentExtension');
}
function it_extends_kreta_extension()
{
$this->shouldHaveType('Kreta\Bundle\CoreBundle\DependencyInjection\Extension');
}
}
|
<?php
/**
* This file belongs to Kreta.
* The source code of application includes a LICENSE file
* with all information about license.
*
* @author benatespina <benatespina@gmail.com>
* @author gorkalaucirica <gorka.lauzirika@gmail.com>
*/
namespace spec\Kreta\Bundle\CommentBundle\DependencyInjection;
use PhpSpec\ObjectBehavior;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class KretaCommentExtensionSpec.
*
* @package spec\Kreta\Bundle\CommentBundle\DependencyInjection
*/
class KretaCommentExtensionSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Kreta\Bundle\CommentBundle\DependencyInjection\KretaCommentExtension');
}
function it_loads(ContainerBuilder $container)
{
$this->load([], $container);
}
}
|
Put the notice fade back in
|
//document.observe("dom:loaded", function(){
// if ($('flash_notice')){
// Element.fade.delay(4,'flash_notice');
// }
// if ($('q')) {
// $('q').activate();
// if ($('search_extended')) {
// $('search_extended').observe("click", function(event){
// $('search_form').submit();
// })
// }
// }
//$('person_photo').down('img').observe("load", function(event){
// event.findElement('img').appear();
//)
// $('person_photo').down('img').observe("mouseover", function(event){
// event.findElement('img').shake({distance : 2});
// })
// $$('.timetable_event').each(function(e){
// e.observe('mouseover', function(event){
// event.findElement('.timetable_event').addClassName('extended')
// })
// e.observe('mouseout', function(event){
// event.findElement('.timetable_event').removeClassName('extended')
// })
// })
//})
$(document).ready(function(){
$('#flash_notice').delay(4000).fadeOut()
})
|
//document.observe("dom:loaded", function(){
// if ($('flash_notice')){
// Element.fade.delay(4,'flash_notice');
// }
// if ($('q')) {
// $('q').activate();
// if ($('search_extended')) {
// $('search_extended').observe("click", function(event){
// $('search_form').submit();
// })
// }
// }
//$('person_photo').down('img').observe("load", function(event){
// event.findElement('img').appear();
//)
// $('person_photo').down('img').observe("mouseover", function(event){
// event.findElement('img').shake({distance : 2});
// })
// $$('.timetable_event').each(function(e){
// e.observe('mouseover', function(event){
// event.findElement('.timetable_event').addClassName('extended')
// })
// e.observe('mouseout', function(event){
// event.findElement('.timetable_event').removeClassName('extended')
// })
// })
//})
$(document).ready(function(){
$('#person_photo').mouseenter(function(){
$('#person_photo img').fadeOut()
})
$('#person_photo').mouseenter(function(){
$('#person_photo img').fadeIn()
})
})
|
Set search area circle size to 0 on reset.
|
function clearEOIMarkers(scope) {
// Remove existing markers.
scope.placesOfInterestMarkers.forEach(function (markerObj) {
scope.map.removeLayer(markerObj.marker);
});
scope.placesOfInterestMarkers = [];
}
function clampWithinBounds(value, lowerBound, upperBound) {
value = Math.max(value, lowerBound);
value = Math.min(value, upperBound);
return value;
}
function createPoiPopupContent(poiAndMarkerObj, scope, compile) {
var content = compile(angular.element('<span>{{poi.DisplayName}}<br>'
+ '<a href="" ng-click="removePlaceOfInterest(poi)">'
+ 'Remove</a>'
+ '</span>'));
var tempScope = scope.$new();
tempScope.poi = poiAndMarkerObj.poi;
return content(tempScope)[0];
}
function updateOrigin(latlng, scope) {
scope.originMarker.setLatLng(latlng).update();
// If have already drawn radius circle then remove it and re-set radius.
if (scope.map.hasLayer(scope.circleOverlay)) {
scope.map.removeLayer(scope.circleOverlay);
scope.radius = 0;
scope.circleOverlay.setRadius(0);
scope.$root.$broadcast('searchAreaCleared');
}
}
|
function clearEOIMarkers(scope) {
// Remove existing markers.
scope.placesOfInterestMarkers.forEach(function (markerObj) {
scope.map.removeLayer(markerObj.marker);
});
scope.placesOfInterestMarkers = [];
}
function clampWithinBounds(value, lowerBound, upperBound) {
value = Math.max(value, lowerBound);
value = Math.min(value, upperBound);
return value;
}
function createPoiPopupContent(poiAndMarkerObj, scope, compile) {
var content = compile(angular.element('<span>{{poi.DisplayName}}<br>'
+ '<a href="" ng-click="removePlaceOfInterest(poi)">'
+ 'Remove</a>'
+ '</span>'));
var tempScope = scope.$new();
tempScope.poi = poiAndMarkerObj.poi;
return content(tempScope)[0];
}
function updateOrigin(latlng, scope) {
scope.originMarker.setLatLng(latlng).update();
// If have already drawn radius circle then remove it and re-set radius.
if (scope.map.hasLayer(scope.circleOverlay)) {
scope.map.removeLayer(scope.circleOverlay);
scope.radius = 0;
scope.$root.$broadcast('searchAreaCleared');
}
}
|
Add source and dest to packages
|
#!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://github.com/uiureo/demae',
packages=[
'demae',
'demae.source',
'demae.dest',
],
package_dir={'demae':
'demae'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='demae',
classifiers=[
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
|
#!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://github.com/uiureo/demae',
packages=[
'demae',
],
package_dir={'demae':
'demae'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='demae',
classifiers=[
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
|
Revert back namespace change for dompdf.
Changing the namespace meant one needed to use dompdf 0.7beta.
Such a change should not have been done in a bugfix release.
|
<?php
namespace CakePdf\Pdf\Engine;
use CakePdf\Pdf\CakePdf;
class DomPdfEngine extends AbstractPdfEngine
{
/**
* Constructor
*
* @param CakePdf $Pdf CakePdf instance
*/
public function __construct(CakePdf $Pdf)
{
parent::__construct($Pdf);
if (!defined('DOMPDF_FONT_CACHE')) {
define('DOMPDF_FONT_CACHE', TMP);
}
if (!defined('DOMPDF_TEMP_DIR')) {
define('DOMPDF_TEMP_DIR', TMP);
}
}
/**
* Generates Pdf from html
*
* @return string raw pdf data
*/
public function output()
{
$DomPDF = new \DOMPDF();
$DomPDF->set_paper($this->_Pdf->pageSize(), $this->_Pdf->orientation());
$DomPDF->load_html($this->_Pdf->html());
$DomPDF->render();
return $DomPDF->output();
}
}
|
<?php
namespace CakePdf\Pdf\Engine;
use CakePdf\Pdf\CakePdf;
use Dompdf\Dompdf;
class DomPdfEngine extends AbstractPdfEngine
{
/**
* Constructor
*
* @param CakePdf $Pdf CakePdf instance
*/
public function __construct(CakePdf $Pdf)
{
parent::__construct($Pdf);
if (!defined('DOMPDF_FONT_CACHE')) {
define('DOMPDF_FONT_CACHE', TMP);
}
if (!defined('DOMPDF_TEMP_DIR')) {
define('DOMPDF_TEMP_DIR', TMP);
}
}
/**
* Generates Pdf from html
*
* @return string raw pdf data
*/
public function output()
{
$DomPDF = new Dompdf();
$DomPDF->set_paper($this->_Pdf->pageSize(), $this->_Pdf->orientation());
$DomPDF->load_html($this->_Pdf->html());
$DomPDF->render();
return $DomPDF->output();
}
}
|
Fix navbar transparent on page load
|
import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
// import socket from "./socket"
import "jquery";
import * as particles from "./app/particles.js";
import * as navbar from "./app/navbar.js";
function navbarScroll() {
var navbar = document.getElementsByClassName("navbar is-fixed-top")[0];
if (navbar && (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50)) {
navbar.classList.remove("is-transparent");
} else {
navbar.classList.add("is-transparent");
}
}
document.addEventListener("DOMContentLoaded", function () {
window.onscroll = navbarScroll;
particles.initParticles();
navbar.initNavbar();
navbarScroll();
$(".offer-new form button#preview").click(function (evt) {
evt.preventDefault();
var form = $(this).closest("form"),
form_data = $(form).serialize(),
$preview_div = $(".offer-new .offer-preview");
$.post($(this).data("url"), form_data, function (res) {
$preview_div.show();
$preview_div.html(res);
$('html, body').animate({
scrollTop: $preview_div.offset().top
}, 'slow');
});
});
});
|
import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
// import socket from "./socket"
import "jquery";
import * as particles from "./app/particles.js";
import * as navbar from "./app/navbar.js";
function navbarScroll() {
var navbar = document.getElementsByClassName("navbar is-fixed-top")[0];
if (navbar && (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50)) {
navbar.classList.remove("is-transparent");
} else {
navbar.classList.add("is-transparent");
}
}
document.addEventListener("DOMContentLoaded", function () {
window.onscroll = navbarScroll;
particles.initParticles();
navbar.initNavbar();
$(".offer-new form button#preview").click(function (evt) {
evt.preventDefault();
var form = $(this).closest("form"),
form_data = $(form).serialize(),
$preview_div = $(".offer-new .offer-preview");
$.post($(this).data("url"), form_data, function (res) {
$preview_div.show();
$preview_div.html(res);
$('html, body').animate({
scrollTop: $preview_div.offset().top
}, 'slow');
});
});
});
|
Rewrite example to use preferred way of creating a new repository
|
package org.dstadler.jgit;
/*
Copyright 2013, 2014 Dominik Stadler
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 java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
/**
* Simple snippet which shows how to create a new repository
*
* @author dominik.stadler at gmx.at
*/
public class CreateNewRepository {
public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException {
// prepare a new folder
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
// create the directory
Git git = Git.init().setDirectory(localPath).call();
System.out.println("Having repository: " + git.getRepository().getDirectory());
git.close();
FileUtils.deleteDirectory(localPath);
}
}
|
package org.dstadler.jgit;
/*
Copyright 2013, 2014 Dominik Stadler
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 java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
/**
* Simple snippet which shows how to create a new repository
*
* @author dominik.stadler at gmx.at
*/
public class CreateNewRepository {
public static void main(String[] args) throws IOException {
// prepare a new folder
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
// create the directory
Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
repository.create();
System.out.println("Having repository: " + repository.getDirectory());
repository.close();
FileUtils.deleteDirectory(localPath);
}
}
|
Fix charset default to UTF-8
|
# coding: utf-8
class Config(object):
BASE_URL = "https://ws.pagseguro.uol.com.br"
VERSION = "/v2/"
CHECKOUT_SUFFIX = VERSION + "checkout"
CHARSET = "UTF-8" # ISO-8859-1
NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s"
TRANSACTION_SUFFIX = VERSION + "transactions/"
CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX
NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX
TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX
CURRENCY = "BRL"
HEADERS = {
"Content-Type": "application/x-www-form-urlencoded; charset={}".format(CHARSET)
}
REFERENCE_PREFIX = "REF%s"
PAYMENT_HOST = "https://pagseguro.uol.com.br"
PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s"
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
|
# coding: utf-8
class Config(object):
BASE_URL = "https://ws.pagseguro.uol.com.br"
VERSION = "/v2/"
CHECKOUT_SUFFIX = VERSION + "checkout"
NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s"
TRANSACTION_SUFFIX = VERSION + "transactions/"
CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX
NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX
TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX
CURRENCY = "BRL"
HEADERS = {
"Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1"
}
REFERENCE_PREFIX = "REF%s"
PAYMENT_HOST = "https://pagseguro.uol.com.br"
PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s"
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
|
Fix path for xsce logo
|
<header class="banner navbar navbar-default navbar-static-top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="navbar-brand" src=" wp-content/themes/<?php echo get_template(); ?>/assets/img/xsce-draft-icon.png" style="padding-bottom: 20px; padding-top: 22px;"/>
<a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(array('theme_location' => 'primary_navigation', 'walker' => new Roots_Nav_Walker(), 'menu_class' => 'nav navbar-nav navbar-right'));
endif;
?>
</nav>
</div>
</header>
|
<header class="banner navbar navbar-default navbar-static-top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="navbar-brand" src="wp-content/themes/roots-master/assets/img/xsce-draft-icon.png" style="padding-bottom: 20px; padding-top: 22px;"/>
<a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(array('theme_location' => 'primary_navigation', 'walker' => new Roots_Nav_Walker(), 'menu_class' => 'nav navbar-nav navbar-right'));
endif;
?>
</nav>
</div>
</header>
|
Add documentation on NewLazyFunction and NewStrictFunction
|
package core
type functionType struct {
signature Signature
function func(...*Thunk) Value
}
func (f functionType) call(args Arguments) Value {
ts, err := f.signature.Bind(args)
if err != nil {
return err
}
return f.function(ts...)
}
// NewLazyFunction creates a function whose arguments are evaluated lazily.
func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk {
return Normal(functionType{
signature: s,
function: f,
})
}
// NewStrictFunction creates a function whose arguments are evaluated strictly.
func NewStrictFunction(s Signature, f func(...Value) Value) *Thunk {
return NewLazyFunction(s, func(ts ...*Thunk) Value {
for _, t := range ts {
go t.Eval()
}
vs := make([]Value, len(ts))
for i, t := range ts {
vs[i] = t.Eval()
if err, ok := vs[i].(ErrorType); ok {
return err
}
}
return f(vs...)
})
}
func (f functionType) string() Value {
return StringType("<function>")
}
|
package core
type functionType struct {
signature Signature
function func(...*Thunk) Value
}
func (f functionType) call(args Arguments) Value {
ts, err := f.signature.Bind(args)
if err != nil {
return err
}
return f.function(ts...)
}
func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk {
return Normal(functionType{
signature: s,
function: f,
})
}
func NewStrictFunction(s Signature, f func(...Value) Value) *Thunk {
return NewLazyFunction(s, func(ts ...*Thunk) Value {
for _, t := range ts {
go t.Eval()
}
vs := make([]Value, len(ts))
for i, t := range ts {
vs[i] = t.Eval()
if err, ok := vs[i].(ErrorType); ok {
return err
}
}
return f(vs...)
})
}
func (f functionType) string() Value {
return StringType("<function>")
}
|
Add reminder to detect Safari since it doesn't use embed
|
$(document).on('ready', function() {
$.ajax({
cache: false,
url: "/partial-index.html"
}).done(function(response) {
$('.main-container').html(response);
});
// Use navigator to detect Safari and render old resume partial instead
$('nav a').on('click', function(event) {
event.preventDefault();
var targetURI = event.currentTarget.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
$('.main-container').on('click', 'a.blog-link, a.home-link', function(event) {
event.preventDefault();
var targetURI = event.target.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
});
|
$(document).on('ready', function() {
$.ajax({
cache: false,
url: "/partial-index.html"
}).done(function(response) {
$('.main-container').html(response);
});
$('nav a').on('click', function(event) {
event.preventDefault();
var targetURI = event.currentTarget.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
$('.main-container').on('click', 'a.blog-link, a.home-link', function(event) {
event.preventDefault();
var targetURI = event.target.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
});
|
Use referer to detect where to take the user after login
|
package fi.nls.oskari.spring.security.database;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.spring.security.OskariUserHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Hooks in OskariUserHelper.onAuthenticationSuccess(). Extends different Spring class than the similar class
* in SAML package.
*/
public class OskariAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private Logger log = LogFactory.getLogger(OskariAuthenticationSuccessHandler.class);
private OskariUserHelper helper = new OskariUserHelper();
public OskariAuthenticationSuccessHandler() {
super();
setUseReferer(true);
}
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, javax.servlet.ServletException {
log.debug("Database based login successful:", authentication.getPrincipal());
super.onAuthenticationSuccess(request, response, authentication);
helper.onAuthenticationSuccess(request, response, authentication);
}
}
|
package fi.nls.oskari.spring.security.database;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.spring.security.OskariUserHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Hooks in OskariUserHelper.onAuthenticationSuccess(). Extends different Spring class than the similar class
* in SAML package.
*/
public class OskariAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private Logger log = LogFactory.getLogger(OskariAuthenticationSuccessHandler.class);
private OskariUserHelper helper = new OskariUserHelper();
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, javax.servlet.ServletException {
log.debug("Database based login successful:", authentication.getPrincipal());
super.onAuthenticationSuccess(request, response, authentication);
helper.onAuthenticationSuccess(request, response, authentication);
}
}
|
Make forward speed same during turns
|
var _ = require('lodash')
var transform = require('./transform.js')
function Fixmove(data) {
if (!data) data = {}
this.speed = data.speed || {position: 1, angle: 10}
}
Fixmove.prototype.compute = function(current, target) {
return this.delta(current, target)
}
Fixmove.prototype.delta = function(current, target) {
var dist = current.distance(target)
var speed = this.speed
var velocity = {position: 1, angle: 1}
var diff = current.difference(target)
if (dist.position > speed.position) {
diff.position[0] = diff.position[0] / dist.position
diff.position[1] = diff.position[1] / dist.position
velocity.position = speed.position
}
if (dist.angle > speed.angle) {
diff.angle = diff.angle / dist.angle
velocity.angle = speed.angle
if (dist.position > speed.position) velocity.angle = speed.position * dist.angle / dist.position
}
return {
position: [
diff.position[0] * velocity.position,
diff.position[1] * velocity.position
],
angle: diff.angle * velocity.angle
}
}
module.exports = Fixmove
|
var _ = require('lodash')
var transform = require('./transform.js')
function Fixmove(data) {
if (!data) data = {}
this.speed = data.speed || {position: 1, angle: 10}
}
Fixmove.prototype.compute = function(current, target) {
return this.delta(current, target)
}
Fixmove.prototype.delta = function(current, target) {
var dist = current.distance(target)
var speed = this.speed
var velocity = {position: 1, angle: 1}
var diff = current.difference(target)
if (dist.position > speed.position) {
diff.position[0] = diff.position[0] / dist.position
diff.position[1] = diff.position[1] / dist.position
velocity.position = speed.position
if (dist.angle > speed.angle) velocity.position = speed.angle * dist.position / dist.angle
}
if (dist.angle > speed.angle) {
diff.angle = diff.angle / dist.angle
velocity.angle = speed.angle
}
return {
position: [
diff.position[0] * velocity.position,
diff.position[1] * velocity.position
],
angle: diff.angle * velocity.angle
}
}
module.exports = Fixmove
|
Change to more logical method name
|
import React, { Component } from 'react';
import axios from 'axios';
import Modal from './modal';
export default class QrModal extends Component {
constructor(props) {
super(props);
this.state = {
qrCodeUrl: null
};
}
componentDidMount() {
axios.get(`/apps/${this.props.urlToken}/qr`)
.then(response => response.data)
.then(data => this.setState({qrCodeUrl: data.url}));
}
renderQRImage() {
if (this.state.qrCodeUrl) {
return <img src={this.state.qrCodeUrl} />
}
return null;
}
renderHeader() {
return (
<div className="modal__header">
<p>Scan this with our <a href="https://itunes.apple.com/us/app/react-native-playground/id1002032944">iOS app</a>!</p>
<img src="/img/app-store-badge.svg" width="135" height="40" />
</div>
);
}
render() {
return (
<Modal isOpen={this.props.isOpen} onClickBackdrop={this.props.onClickBackdrop}>
{this.renderHeader()}
<div className="modal__body qr-modal-body">
{this.renderQRImage()}
</div>
</Modal>
)
}
}
|
import React, { Component } from 'react';
import axios from 'axios';
import Modal from './modal';
export default class QrModal extends Component {
constructor(props) {
super(props);
this.state = {
qrCodeUrl: null
};
}
componentDidMount() {
axios.get(`/apps/${this.props.urlToken}/qr`)
.then(response => response.data)
.then(data => this.setState({qrCodeUrl: data.url}));
}
renderQRImage() {
if (this.state.qrCodeUrl) {
return <img src={this.state.qrCodeUrl} />
}
return null;
}
renderFooter() {
return (
<div className="modal__header">
<p>Scan this with our <a href="https://itunes.apple.com/us/app/react-native-playground/id1002032944">iOS app</a>!</p>
<img src="/img/app-store-badge.svg" width="135" height="40" />
</div>
);
}
render() {
return (
<Modal isOpen={this.props.isOpen} onClickBackdrop={this.props.onClickBackdrop}>
{this.renderFooter()}
<div className="modal__body qr-modal-body">
{this.renderQRImage()}
</div>
</Modal>
)
}
}
|
Revert "added function to change OIA AdminServer nodemanager credentials"
This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.
|
import os
createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py'
if os.path.exists(createDomain):
execfile(createDomain)
# ================================================================
# Main Code Execution
# ================================================================
if __name__== "main":
print '###################################################################'
print '# Domain Creation #'
print '###################################################################'
print ''
intialize()
createCustomDomain()
createAllBootProperties()
startAndConnnectToAdminServer()
# do enroll on local machine
print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n'
nmEnroll(domainLocation, domainProps.getProperty('nmDir'))
setJTATimeout()
createAllDatasources()
|
import os
createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py'
if os.path.exists(createDomain):
execfile(createDomain)
def updateNmProperties():
print "Updating NodeManager username and password for " + DomainLocation
edit()
startEdit()
cd("SecurityConfiguration/oia_iamv2")
cmo.setNodeManagerUsername("admin")
cmo.setNodeManagerPassword(adminPassword)
save()
activate()
# ================================================================
# Main Code Execution
# ================================================================
if __name__== "main":
print '###################################################################'
print '# Domain Creation #'
print '###################################################################'
print ''
intialize()
createCustomDomain()
createAllBootProperties()
startAndConnnectToAdminServer()
# do enroll on local machine
print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n'
nmEnroll(domainLocation, domainProps.getProperty('nmDir'))
updateNmProperties()
setJTATimeout()
createAllDatasources()
|
Check arguments after controller fetches message
|
'use strict';
const SlackBot = require('./src/SlackBot');
const GitHubApiClient = require("./src/GitHubApiClient");
const PullRequests = require('./src/PullRequests');
const _ = require('lodash');
const controller = new SlackBot().getController();
controller.hears("^ls (.+)",["direct_message","direct_mention","mention"], (bot, message) => {
const match = message.match[1].match(/author:([^\s]+) owner:([^\s]+)/);
const authors = match[1].split(',');
const owner = match[2];
const client = new GitHubApiClient();
client.getAllPullRequests(authors).then((prs) => {
bot.startConversation(message, (err, convo) => {
convo.say(':memo: Review waiting list!');
_.each(new PullRequests(prs, owner).convertToSlackMessages(), (pr) => convo.say(pr));
convo.next()
})
});
});
|
'use strict';
const SlackBot = require('./src/SlackBot');
const GitHubApiClient = require("./src/GitHubApiClient");
const PullRequests = require('./src/PullRequests');
const _ = require('lodash');
const controller = new SlackBot().getController();
controller.hears("^ls author:([^\s]+) owner:([^\s]+)",["direct_message","direct_mention","mention"], (bot, message) => {
const authors = message.match[1].split(',');
const owner = message.match[2];
const client = new GitHubApiClient();
client.getAllPullRequests(authors).then((prs) => {
bot.startConversation(message, (err, convo) => {
convo.say(':memo: Review waiting list!');
_.each(new PullRequests(prs, owner).convertToSlackMessages(), (pr) => convo.say(pr));
convo.next()
})
});
});
|
Fix for T2-674: Hardcoded default locations. System default configurable providers are now read from a file in Taverna startup/conf directory. Failing that - they are read from a hard coded list. User can now import and export services from such files as well.
git-svn-id: 2b4c7ad77658e4b3615e54128c4b6795c159dfbb@10041 bf327186-88b3-11dd-a302-d386e5130c1c
|
package net.sf.taverna.t2.activities.beanshell.servicedescriptions;
import java.net.URI;
import javax.swing.Icon;
import net.sf.taverna.t2.activities.beanshell.BeanshellActivity;
import net.sf.taverna.t2.activities.beanshell.BeanshellActivityConfigurationBean;
import net.sf.taverna.t2.servicedescriptions.AbstractTemplateService;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
public class BeanshellTemplateService extends
AbstractTemplateService<BeanshellActivityConfigurationBean> {
private static final String BEANSHELL = "Beanshell";
private static final URI providerId = URI
.create("http://taverna.sf.net/2010/service-provider/beanshell");
public String getName() {
return BEANSHELL;
}
@Override
public Class<BeanshellActivity> getActivityClass() {
return BeanshellActivity.class;
}
@Override
public BeanshellActivityConfigurationBean getActivityConfiguration() {
return new BeanshellActivityConfigurationBean();
}
@Override
public Icon getIcon() {
return BeanshellActivityIcon.getBeanshellIcon();
}
@Override
public String getDescription() {
return "A service that allows Beanshell scripts, with dependencies on libraries";
}
@SuppressWarnings("unchecked")
public static ServiceDescription getServiceDescription() {
BeanshellTemplateService bts = new BeanshellTemplateService();
return bts.templateService;
}
public String getId() {
return providerId.toString();
}
}
|
package net.sf.taverna.t2.activities.beanshell.servicedescriptions;
import javax.swing.Icon;
import net.sf.taverna.t2.activities.beanshell.BeanshellActivity;
import net.sf.taverna.t2.activities.beanshell.BeanshellActivityConfigurationBean;
import net.sf.taverna.t2.servicedescriptions.AbstractTemplateService;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
public class BeanshellTemplateService extends
AbstractTemplateService<BeanshellActivityConfigurationBean> {
private static final String BEANSHELL = "Beanshell";
public String getName() {
return BEANSHELL;
}
@Override
public Class<BeanshellActivity> getActivityClass() {
return BeanshellActivity.class;
}
@Override
public BeanshellActivityConfigurationBean getActivityConfiguration() {
return new BeanshellActivityConfigurationBean();
}
@Override
public Icon getIcon() {
return BeanshellActivityIcon.getBeanshellIcon();
}
@Override
public String getDescription() {
return "A service that allows Beanshell scripts, with dependencies on libraries";
}
public static ServiceDescription getServiceDescription() {
BeanshellTemplateService bts = new BeanshellTemplateService();
return bts.templateService;
}
}
|
Add TIMEOUT status and document statuses.
|
package com.collective.celos;
/**
* The execution status of a slot.
*/
public class SlotState extends ValueObject {
protected final SlotID slotID;
protected final Status status;
public enum Status {
/** No data availability yet. */
WAITING,
/** No data availability for too long, workflow will not run. */
TIMEOUT,
/** Data is available and the workflow will be run shortly.
Workflow will also enter this state when it is retried. */
READY,
/** The workflow is currently running. */
RUNNING,
/** The workflow has succeeded. */
SUCCESS,
/** The workflow has failed and will not be retried. */
FAILURE
};
public SlotState(SlotID slotID, Status status) {
this.slotID = Util.requireNonNull(slotID);
this.status = Util.requireNonNull(status);
}
public SlotID getSlotID() {
return slotID;
}
public Status getStatus() {
return status;
}
}
|
package com.collective.celos;
/**
* The execution status of a slot.
*/
public class SlotState extends ValueObject {
protected final SlotID slotID;
protected final Status status;
public enum Status {
WAITING,
READY,
RUNNING,
SUCCESS,
FAILURE
};
public SlotState(SlotID slotID, Status status) {
this.slotID = Util.requireNonNull(slotID);
this.status = Util.requireNonNull(status);
}
public SlotID getSlotID() {
return slotID;
}
public Status getStatus() {
return status;
}
}
|
Allow up to 5mb uploads
|
var yarn = require('yarn/lib/lockfile/wrapper.js')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 5000;
app.use(bodyParser.text());
app.disable('x-powered-by');
app.use(function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
next();
});
app.use(express.bodyParser({limit: '5mb'}));
app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){
var dependencies = yarn.parse(req.body)
var deps = []
Object.keys(dependencies).forEach((dep) => {
deps.push({
name: dep.split('@')[0],
version: dependencies[dep].version,
type: 'runtime'
})
})
res.json(deps)
});
app.use(function(err, req, res, next) {
console.error('ERR:', err);
console.error('STACK:', err.stack);
res.status(500).send({error: 'Something went wrong.'});
});
app.listen(port, function() {
console.log('Listening on', port);
});
|
var yarn = require('yarn/lib/lockfile/wrapper.js')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 5000;
app.use(bodyParser.text());
app.disable('x-powered-by');
app.use(function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
next();
});
app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){
var dependencies = yarn.parse(req.body)
var deps = []
Object.keys(dependencies).forEach((dep) => {
deps.push({
name: dep.split('@')[0],
version: dependencies[dep].version,
type: 'runtime'
})
})
res.json(deps)
});
app.use(function(err, req, res, next) {
console.error('ERR:', err);
console.error('STACK:', err.stack);
res.status(500).send({error: 'Something went wrong.'});
});
app.listen(port, function() {
console.log('Listening on', port);
});
|
Add some inherited @NonNull annotation
|
package net.ssehub.kernel_haven.fe_analysis.fes;
import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.config.Configuration;
import net.ssehub.kernel_haven.fe_analysis.pcs.PcFinder;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* An analysis that finds feature effect formulas for variables.
*
* @author Adam
*/
public class FeatureEffectAnalysis extends PipelineAnalysis {
/**
* Creates a new {@link FeatureEffectAnalysis}.
*
* @param config The global configuration.
*/
public FeatureEffectAnalysis(@NonNull Configuration config) {
super(config);
}
@Override
protected @NonNull AnalysisComponent<?> createPipeline() throws SetUpException {
return new FeatureEffectFinder(config,
new PcFinder(config,
getCmComponent(),
getBmComponent()
)
);
}
}
|
package net.ssehub.kernel_haven.fe_analysis.fes;
import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.config.Configuration;
import net.ssehub.kernel_haven.fe_analysis.pcs.PcFinder;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* An analysis that finds feature effect formulas for variables.
*
* @author Adam
*/
public class FeatureEffectAnalysis extends PipelineAnalysis {
/**
* Creates a new {@link FeatureEffectAnalysis}.
*
* @param config The global configuration.
*/
public FeatureEffectAnalysis(@NonNull Configuration config) {
super(config);
}
@Override
protected AnalysisComponent<?> createPipeline() throws SetUpException {
return new FeatureEffectFinder(config,
new PcFinder(config,
getCmComponent(),
getBmComponent()
)
);
}
}
|
Make application use log file if its name is not None
|
# -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.
.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views
__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'
log_file = app.config['LOG_FILE']
if not app.debug and log_file is not None:
import logging
from logging.handlers import TimedRotatingFileHandler
file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
app.run()
|
# -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spam.
.. __: https://github.com/piotr-rusin/spam-lists
'''
from url_shortener import app, event_handlers, views
__title__ = 'url-shortener'
__version__ = '0.9.0.dev1'
__author__ = 'Piotr Rusin'
__email__ = "piotr.rusin88@gmail.com"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Piotr Rusin'
if not app.debug:
import logging
from logging.handlers import TimedRotatingFileHandler
file_handler = TimedRotatingFileHandler(app.config['LOG_FILE'])
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
app.run()
|
Modify test specs with correct error messages.
|
const
labyParser = require('../lib/parser'),
expect = require('chai').expect;
describe('Icarus', function(){
it('should throw an error if there is a line which has indents gap more than 2.', function(){
var errorStr = '\t\tCONTEXT: should not have gap more than 2.';
var labyStr = 'DESCRIBE: Indents\n'+
errorStr;
expect(labyParser.parse.bind(null, labyStr)).to.throw(Error, 'Invalid indent.');
});
it('should throw an error if there is an line which has no key.', function(){
var errorStr = 'should have a key not like me.';
var labyStr = 'DESCRIBE: Lines\n'+
errorStr;
expect(labyParser.parse.bind(null, labyStr)).to.throw(Error, 'Invalid line.');
});
});
|
const
labyParser = require('../lib/parser'),
expect = require('chai').expect;
describe('Icarus', function(){
it('should throw an error if there is a line which has indents gap more than 2.', function(){
var errorStr = '\t\tCONTEXT: should not have gap more than 2.';
var labyStr = 'DESCRIBE: Indents\n'+
errorStr;
expect(labyParser.parse.bind(null, labyStr)).to.throw(Error, 'Invalid indents. '+errorStr);
});
it('should throw an error if there is an line which has no key.', function(){
var errorStr = 'should have a key not like me.';
var labyStr = 'DESCRIBE: Lines\n'+
errorStr;
expect(labyParser.parse.bind(null, labyStr)).to.throw(Error, 'Invalid line. '+errorStr);
});
});
|
Fix update to work with nodemon.
|
// github.js
// aoneill - 12/24/16
var child = require('child_process'),
GithubWebHook = require('express-github-webhook'),
process = require('process'),
_ = require('underscore');
var config = require('./config.js');
module.exports = function(server) {
var webhook = GithubWebHook(config.github);
webhook.on('push', function(repo, data) {
var branch = data.ref.replace(/^refs\/heads\//, '');
if(branch === 'master') {
var files = _.flatten(_.map(data.commits, function(commit) {
return [commit.added, commit.removed, commit.modified];
}));
child.execFile(config.github.script, files, function(err, stdout) {
if(err) {
console.log('err: Could not update with GitHub push: ' +
_.map(data.commits, function(commit) {
return commit.id;
}));
return;
}
console.log('GitHub: Successful update!');
});
}
});
server.use(webhook);
}
|
// github.js
// aoneill - 12/24/16
var child = require('child_process'),
GithubWebHook = require('express-github-webhook'),
process = require('process'),
_ = require('underscore');
var config = require('./config.js');
module.exports = function(server) {
var webhook = GithubWebHook(config.github);
webhook.on('push', function(repo, data) {
var branch = data.ref.replace(/^refs\/heads\//, '');
if(branch === 'master') {
var files = _.flatten(_.map(data.commits, function(commit) {
return [commit.added, commit.removed, commit.modified];
}));
child.execFile(config.github.script, files, function(err, stdout) {
if(err) {
console.log('err: Could not update with GitHub push: ' +
_.map(data.commits, function(commit) {
return commit.id;
}));
return;
}
console.log('GitHub: Successful update!');
if(stdout.includes('update')) {
console.log('GitHub: Quitting server...');
process.exit(0);
}
});
}
});
server.use(webhook);
}
|
Change tab to clicked list item
|
function makeListWithArray(array) {
var list = document.createElement('ul');
list.id = 'results_list';
for (var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.className = 'result';
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
document.addEventListener('DOMContentLoaded', function() {
var searchbar = document.getElementById('query');
var resultsSection = document.getElementById('results_section');
var resultsList;
var tabs = [];
chrome.windows.getAll({populate: true}, function(windows) {
tabs = windows.reduce(function(previous, current) {
return previous.concat(current.tabs);
}, []);
var titles = [];
for (var i = 0; i < tabs.length; i++) {
titles[i] = tabs[i].title;
}
resultsSection.appendChild(makeListWithArray(titles));
resultsList = resultsSection.lastChild;
});
resultsSection.addEventListener('mouseup', function(e) {
if (e.target && e.target.className === 'result') {
var clickIndex = Array.prototype.indexOf.call(resultsList.childNodes, e.target);
var tabId = tabs[clickIndex].id;
chrome.tabs.update(tabId, {active: true});
}
});
});
|
function makeListWithArray(array) {
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.className = 'result';
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
document.addEventListener('DOMContentLoaded', function() {
var searchbar = document.getElementById('query');
var resultsSection = document.getElementById('results_section');
var tabs = [];
chrome.windows.getAll({populate: true}, function(windows) {
tabs = windows.reduce(function(previous, current) {
return previous.concat(current.tabs);
}, []);
var titles = [];
for (var i = 0; i < tabs.length; i++) {
titles[i] = tabs[i].title;
}
resultsSection.appendChild(makeListWithArray(titles));
});
});
|
Add placeholder knob to stories.
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { withKnobs, boolean, number, text } from '@storybook/addon-knobs'
import { BasicSelect, BasicMultiSelect, BasicSearchSelect } from './components'
import states from './fixtures/states'
const stories = storiesOf('Select', module)
stories.addDecorator(withKnobs)
stories.add('with SimpleSelect', () => (
<BasicSelect
options={states}
labelKey="name"
valueKey="abbreviation"
showInput={boolean('Show Input', false)}
isOpen={boolean('Is Open', false)}
autoCloseMenu={boolean('Auto Close Menu', true)}
clearable={boolean('Clearable', false)}
autoClearInput={boolean('Auto Clear Input', true)}
placeholder={text('Placeholder', 'Select value...')}
/>
))
stories.add('with MultiSelect', () => (
<BasicMultiSelect
options={states}
labelKey="name"
valueKey="abbreviation"
isOpen={boolean('Is Open', false)}
valueLabelLimit={number('Value Label Limit', 3)}
autoCloseMenu={boolean('Auto Close Menu', false)}
clearable={boolean('Clearable', false)}
placeholder={text('Placeholder', 'Select value...')}
/>
))
stories.add('with SearchSelect', () => (
<BasicSearchSelect
options={states}
labelKey="name"
valueKey="abbreviation"
isOpen={boolean('Is Open', false)}
autoCloseMenu={boolean('Auto Close Menu', true)}
clearable={boolean('Clearable', false)}
placeholder={text('Placeholder', 'Select value...')}
/>
))
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { withKnobs, boolean, number } from '@storybook/addon-knobs'
import { BasicSelect, BasicMultiSelect, BasicSearchSelect } from './components'
import states from './fixtures/states'
const stories = storiesOf('Select', module)
stories.addDecorator(withKnobs)
stories.add('with SimpleSelect', () => (
<BasicSelect
options={states}
labelKey="name"
valueKey="abbreviation"
showInput={boolean('Show Input', false)}
isOpen={boolean('Is Open', false)}
autoCloseMenu={boolean('Auto Close Menu', true)}
clearable={boolean('Clearable', false)}
autoClearInput={boolean('Auto Clear Input', true)}
/>
))
stories.add('with MultiSelect', () => (
<BasicMultiSelect
options={states}
labelKey="name"
valueKey="abbreviation"
isOpen={boolean('Is Open', false)}
valueLabelLimit={number('Value Label Limit', 3)}
autoCloseMenu={boolean('Auto Close Menu', false)}
clearable={boolean('Clearable', false)}
/>
))
stories.add('with SearchSelect', () => (
<BasicSearchSelect
options={states}
labelKey="name"
valueKey="abbreviation"
isOpen={boolean('Is Open', false)}
autoCloseMenu={boolean('Auto Close Menu', true)}
clearable={boolean('Clearable', false)}
/>
))
|
Rename test case type for Sequence.Next
|
package keys_test
import (
"testing"
"github.com/kezhuw/leveldb/internal/keys"
)
type nextSequenceTest struct {
seq keys.Sequence
next uint64
want keys.Sequence
}
var nextSequenceTests = []nextSequenceTest{
{
seq: 0x00123456789abcde,
next: 0x000fc9a8743210fe,
want: 0x0021fdfeeccccddc,
},
{
seq: 0x00edcba987654321,
next: 0x0000149efb5c218e,
want: 0x00ede04882c164af,
},
}
func TestSequenceNext(t *testing.T) {
for i, test := range nextSequenceTests {
got := test.seq.Next(test.next)
if got != test.want {
t.Errorf("test=%d sequence=%#x next=%d got=%#x want=%#x", i, test.seq, test.next, got, test.want)
}
}
}
|
package keys_test
import (
"testing"
"github.com/kezhuw/leveldb/internal/keys"
)
type sequenceTest struct {
seq keys.Sequence
next uint64
want keys.Sequence
}
var sequenceTests = []sequenceTest{
{
seq: 0x00123456789abcde,
next: 0x000fc9a8743210fe,
want: 0x0021fdfeeccccddc,
},
{
seq: 0x00edcba987654321,
next: 0x0000149efb5c218e,
want: 0x00ede04882c164af,
},
}
func TestSequenceNext(t *testing.T) {
for i, test := range sequenceTests {
got := test.seq.Next(test.next)
if got != test.want {
t.Errorf("test=%d sequence=%#x next=%d got=%#x want=%#x", i, test.seq, test.next, got, test.want)
}
}
}
|
Migrate database before running dusk test
|
<?php
namespace Collejo\App\Modules\Auth\Tests\Browser;
use Collejo\Foundation\Testing\DuskTestCase;
use Laravel\Dusk\Browser;
class AuthModuleTest extends DuskTestCase
{
/**
* Test if the module is loaded.
*
* @throws \Exception
* @throws \Throwable
* @covers \Collejo\App\Modules\Auth\Http\Controllers\LoginController::showLoginForm()
*/
public function testModuleLoaded()
{
$this->runDatabaseMigrations();
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertSee(config('app.name'))
->assertTitle(trans('auth::auth.login').' - '.config('app.name'));
});
}
}
|
<?php
namespace Collejo\App\Modules\Auth\Tests\Browser;
use Collejo\Foundation\Testing\DuskTestCase;
use Laravel\Dusk\Browser;
class AuthModuleTest extends DuskTestCase
{
/**
* Test if the module is loaded.
*
* @throws \Exception
* @throws \Throwable
* @covers \Collejo\App\Modules\Auth\Http\Controllers\LoginController::showLoginForm()
*/
public function testModuleLoaded()
{
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertSee(config('app.name'))
->assertTitle(trans('auth::auth.login').' - '.config('app.name'));
});
}
}
|
Add PHP Benelux to other organisations
|
<?php
return [
'production' => true,
'twitter' => '@laravelbrussels',
'meetup_url' => '//meetup.com/Laravel-Brussels',
'other_organisations' => [
'PHP Antwerp' => '//www.meetup.com/phpantwerp',
'PHP Benelux' => '//www.phpbenelux.eu',
'PHP Brussels' => '//www.meetup.com/BrusselsPHP',
'PHP Gent' => '//www.meetup.com/phpgent',
'PHP Leuven' => '//www.meetup.com/PHP-Leuven-Web-Innovation-Group',
'PHP Limburg (BE)' => '//www.meetup.com/PHP-Limburg-BE',
'Laracon EU' => '//laracon.eu',
],
];
|
<?php
return [
'production' => true,
'twitter' => '@laravelbrussels',
'meetup_url' => '//meetup.com/Laravel-Brussels',
'other_organisations' => [
'PHP Antwerp' => '//www.meetup.com/phpantwerp',
'PHP Brussels' => '//www.meetup.com/BrusselsPHP',
'PHP Gent' => '//www.meetup.com/phpgent',
'PHP Leuven' => '//www.meetup.com/PHP-Leuven-Web-Innovation-Group',
'PHP Limburg (BE)' => '//www.meetup.com/PHP-Limburg-BE',
'Laracon EU' => '//laracon.eu',
],
];
|
Fix name of writeFile test
|
var path = require('path'),
fs = require('fs'),
crypto = require('crypto');
describe("writeFile functionality", function() {
var _this = this;
require('./harness.js')(_this);
it("writes data to a file that doesn't exist", function(done) {
var fname = "testDir";
var resolved = path.resolve(_this.tempdir, fname);
crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
if (err) throw err;
_this.wd.writeFile(fname, data, function(err) {
expect(err).toBe(null);
fs.readFile(resolved, function(err, rdata) {
if (err) throw err;
expect(rdata.toString()).toBe(data.toString());
done();
});
});
});
});
});
|
var path = require('path'),
fs = require('fs'),
crypto = require('crypto');
describe("writeFile functionality", function() {
var _this = this;
require('./harness.js')(_this);
it("creates a directory", function(done) {
var fname = "testDir";
var resolved = path.resolve(_this.tempdir, fname);
crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
if (err) throw err;
_this.wd.writeFile(fname, data, function(err) {
expect(err).toBe(null);
fs.readFile(resolved, function(err, rdata) {
if (err) throw err;
expect(rdata.toString()).toBe(data.toString());
done();
});
});
});
});
});
|
Include teh name of the backend in the error message
|
# 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 __future__ import absolute_import, division, print_function
import pytest
def skip_check(name, iface, item):
if name in item.keywords and "backend" in item.funcargs:
if not isinstance(item.funcargs["backend"], iface):
pytest.skip("{0} backend does not support {1}".format(
item.funcargs["backend"], 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 __future__ import absolute_import, division, print_function
import pytest
def skip_check(name, iface, item):
if name in item.keywords and item.funcargs.get('backend') is not None:
if not isinstance(item.funcargs['backend'], iface):
pytest.skip("Backend does not support {0}".format(name))
|
Remove extra whitespace in reminder email
|
Hi {{ $assignment->user->preferred_first_name }},
@if(!$assignment->tar_received && $assignment->travel->tar_required)
You still need to submit a Travel Authority Request for {{ $assignment->travel->name }}. Please visit {{ route('docusign.travel') }} to fill out and sign it.
@endif
@if(!$assignment->is_paid)
You{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? ' also': '' }} still need to make a ${{ intval($assignment->travel->fee_amount) }} payment{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? '' : ' for '.$assignment->travel->name }}.
You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($assignment->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments.
If you would prefer to pay by cash or check, make arrangements with {{ $assignment->travel->primaryContact->full_name }}.
Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it!
@endif
For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $assignment->travel->primaryContact->full_name }}.
----
To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.
|
Hi {{ $assignment->user->preferred_first_name }},
@if(!$assignment->tar_received && $assignment->travel->tar_required)
You still need to submit a Travel Authority Request for {{ $assignment->travel->name }}. Please visit {{ route('docusign.travel') }} to fill out and sign it.
@endif
@if(!$assignment->is_paid)
You{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? ' also': '' }} still need to make a ${{ intval($assignment->travel->fee_amount) }} payment{{ (!$assignment->tar_received && $assignment->travel->tar_required) ? '' : ' for '.$assignment->travel->name }}.
You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($assignment->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments.
If you would prefer to pay by cash or check, make arrangements with {{ $assignment->travel->primaryContact->full_name }}.
Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it!
@endif
For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $assignment->travel->primaryContact->full_name }}.
----
To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.
|
Include README in the module description
|
# vim:fileencoding=utf-8:noet
from setuptools import setup
version = "0.7.1"
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="powerline-taskwarrior",
description="Powerline segments for showing information from the Taskwarrior task manager",
version=version,
keywords="powerline taskwarrior context prompt",
license="MIT",
author="German Lashevich",
author_email="german.lashevich@gmail.com",
url="https://github.com/zebradil/powerline-taskwarrior",
download_url="https://github.com/zebradil/powerline-taskwarrior/tarball/{version}".format(version=version),
packages=["powerline_taskwarrior"],
install_requires=["powerline-status"],
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Terminals",
],
long_description=long_description,
long_description_content_type="text/markdown",
)
|
# vim:fileencoding=utf-8:noet
from setuptools import setup
version = "0.7.0"
setup(
name="powerline-taskwarrior",
description="Powerline segments for showing information from the Taskwarrior task manager",
version=version,
keywords="powerline taskwarrior context prompt",
license="MIT",
author="German Lashevich",
author_email="german.lashevich@gmail.com",
url="https://github.com/zebradil/powerline-taskwarrior",
download_url="https://github.com/zebradil/powerline-taskwarrior/tarball/{version}".format(version=version),
packages=["powerline_taskwarrior"],
install_requires=["powerline-status"],
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Terminals",
],
)
|
Order categories in search fields
|
from django import template
register = template.Library()
@register.filter
def dimension(value, arg):
"""
Dimension integers
If value, append arg, otherwise output nothing
"""
if value:
return str(value) + " " + arg
return ""
@register.filter
def verbose_name(obj):
"""
Return the verbose name of a model
"""
return obj._meta.verbose_name
@register.filter
def pdb(element):
"""
Inside a template do {{ template_var|pdb }}
"""
import ipdb
ipdb.set_trace()
return element
from cat.models import Category
from location.models import Country
@register.inclusion_tag('snippets/advanced_search_fields.html')
def advanced_search_fields():
categories = Category.objects.all().order_by('name')
places = Country.objects.all()
return {
'categories': categories,
'places': places,
}
|
from django import template
register = template.Library()
@register.filter
def dimension(value, arg):
"""
Dimension integers
If value, append arg, otherwise output nothing
"""
if value:
return str(value) + " " + arg
return ""
@register.filter
def verbose_name(obj):
"""
Return the verbose name of a model
"""
return obj._meta.verbose_name
@register.filter
def pdb(element):
"""
Inside a template do {{ template_var|pdb }}
"""
import ipdb
ipdb.set_trace()
return element
from cat.models import Category
from location.models import Country
@register.inclusion_tag('snippets/advanced_search_fields.html')
def advanced_search_fields():
categories = Category.objects.all()
places = Country.objects.all()
return {
'categories': categories,
'places': places,
}
|
Fix an incorrect postcode for Reading
|
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
elections = ["2022-05-05"]
csv_delimiter = "\t"
def address_record_to_dict(self, record):
if record.property_urn.strip().lstrip("0") == "310088234":
record = record._replace(addressline6="RG1 1SN")
if record.addressline6 in [
"RG30 4RX",
"RG4 8ES",
"RG2 7PS",
]:
return None
return super().address_record_to_dict(record)
|
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
elections = ["2022-05-05"]
csv_delimiter = "\t"
def address_record_to_dict(self, record):
if record.addressline6 in [
"RG30 4RX",
"RG1 3NF",
"RG4 8ES",
"RG2 7PS",
]:
return None
return super().address_record_to_dict(record)
|
Add short alias for start command
|
var program = require('commander')
var runner = require('./runner')
var json = require('../../package.json')
program
.version(json.version)
program
.command('new <name>')
.description('Generate scaffold for new Electron application')
.action(function (name) {
runner.new(name)
})
program
.command('start')
.alias('s')
.description('Compile and run application')
.action(function () {
runner.start()
})
program
.command('test [spec]')
.description('Run tests from spec/ directory')
.action(function (spec) {
runner.test(spec).then(function(result) {
process.exit(result.status);
})
})
program
.command('clear')
.description('Clear builds and releases directories')
.action(function () {
runner.clear()
})
program
.command('package <platform>')
.description('Build and Package applications for platforms defined in package.json')
.action(function (platform) {
runner.package(platform)
})
program.parse(process.argv)
|
var program = require('commander')
var runner = require('./runner')
var json = require('../../package.json')
program
.version(json.version)
program
.command('new <name>')
.description('Generate scaffold for new Electron application')
.action(function (name) {
runner.new(name)
})
program
.command('start')
.description('Compile and run application')
.action(function () {
runner.start()
})
program
.command('test [spec]')
.description('Run tests from spec/ directory')
.action(function (spec) {
runner.test(spec).then(function(result) {
process.exit(result.status);
})
})
program
.command('clear')
.description('Clear builds and releases directories')
.action(function () {
runner.clear()
})
program
.command('package <platform>')
.description('Build and Package applications for platforms defined in package.json')
.action(function (platform) {
runner.package(platform)
})
program.parse(process.argv)
|
Create logger on Deck creation
|
var utils = require('./utils');
module.exports.create = function (id, client) {
var instance = {},
logger = utils.logger(__filename);
/*
*/
instance.id = 'radio.' + id;
instance.volume = function (params) {
return sendCommandForAction('volume', params);
};
instance.playRandom = function (params) {
return sendCommandForAction('random', params);
};
instance.play = function (params) {
return sendCommandForAction('play', params);
};
function sendCommandForAction(action, params) {
params.action = action;
return client.createExchange({ exchangeName: 'radiodan' })
.then(function () {
return sendCommandToExchange(params);
})
.then(null, utils.failedPromiseHandler());
}
function sendCommandToExchange(params) {
return client.sendCommand({
exchangeName : 'radiodan',
topicKey : instance.id + '.command',
command : params
});
}
return instance;
};
|
var utils = require('./utils');
module.exports.create = function (id, client) {
var instance = {};
/*
*/
instance.id = 'radio.' + id;
instance.volume = function (params) {
return sendCommandForAction('volume', params);
};
instance.playRandom = function (params) {
return sendCommandForAction('random', params);
};
instance.play = function (params) {
return sendCommandForAction('play', params);
};
function sendCommandForAction(action, params) {
params.action = action;
return client.createExchange({ exchangeName: 'radiodan' })
.then(function () {
return sendCommandToExchange(params);
})
.then(null, utils.failedPromiseHandler());
}
function sendCommandToExchange(params) {
return client.sendCommand({
exchangeName : 'radiodan',
topicKey : instance.id + '.command',
command : params
});
}
return instance;
};
|
Fix test to properly compare chart types
A variable was being compared to itself
|
"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
|
"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.