text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change maintainer to Blanc Ltd
|
#!/usr/bin/env python
from setuptools import setup, find_packages
# Use latest_tweets.VERSION for version numbers
version_tuple = __import__('latest_tweets').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-latest-tweets',
version=version,
description='Latest Tweets for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-latest-tweets',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
install_requires=[
'twitter>=1.9.1',
],
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
license='BSD-2',
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
# Use latest_tweets.VERSION for version numbers
version_tuple = __import__('latest_tweets').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-latest-tweets',
version=version,
description='Latest Tweets for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-latest-tweets',
maintainer='Alex Tomkins',
maintainer_email='alex@blanc.ltd.uk',
platforms=['any'],
install_requires=[
'twitter>=1.9.1',
],
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
license='BSD-2',
)
|
Add serial adaptor and error handling.
|
package gorduino
import (
"github.com/tarm/goserial"
"github.com/yanzay/go-firmata"
)
type Gorduino struct {
pins map[byte]bool
client *firmata.FirmataClient
work func()
}
func NewGorduino(port string, pins ...byte) (*Gorduino, error) {
g := new(Gorduino)
g.pins = make(map[byte]bool)
c := &serial.Config{Name: port, Baud: 57600}
conn, err := serial.OpenPort(c)
if err != nil {
return nil, err
}
g.client, _ = firmata.NewClient(conn)
for _, pin := range pins {
g.pins[pin] = false
g.client.SetPinMode(pin, firmata.Output)
}
return g, nil
}
func (g *Gorduino) On(p byte) {
g.client.DigitalWrite(uint(p), true)
}
func (g *Gorduino) Off(p byte) {
g.client.DigitalWrite(uint(p), false)
}
func (g *Gorduino) Toggle(p byte) {
g.pins[p] = !g.pins[p]
g.client.DigitalWrite(uint(p), g.pins[p])
}
|
package gorduino
import (
"github.com/kraman/go-firmata"
)
type Gorduino struct {
pins map[byte]bool
client *firmata.FirmataClient
work func()
}
func NewGorduino(port string, pins ...byte) *Gorduino {
g := new(Gorduino)
g.pins = make(map[byte]bool)
g.client, _ = firmata.NewClient(port, 57600)
for _, pin := range pins {
g.pins[pin] = false
g.client.SetPinMode(pin, firmata.Output)
}
return g
}
func (g *Gorduino) On(p byte) {
g.client.DigitalWrite(uint(p), true)
}
func (g *Gorduino) Off(p byte) {
g.client.DigitalWrite(uint(p), false)
}
func (g *Gorduino) Toggle(p byte) {
g.pins[p] = !g.pins[p]
g.client.DigitalWrite(uint(p), g.pins[p])
}
|
Add refresh for each reply
|
// // Place all the behaviors and hooks related to the matching controller here.
// // All this logic will automatically be available in application.js.
var ready = function() {
$(".reply-button").hide();
$(".reply-content").focus(function() {
$(this).siblings(".reply-button").fadeIn("fast");
var container = $(this);
hideReplyContainer(container);
});
$(".reply-content").focusout(function() {
$(this).siblings(".reply-button").fadeOut("fast");
});
function hideReplyContainer(container) {
$(document).mouseup(function(e) {
var input = container.val().length;
console.log(container.val().length);
if (!container.is(e.target) && container.has(e.target).length === 0 && input === 0) {
container.siblings(".reply-button").hide();
}
});
}
$(".reply-button").click(function() {
// Refresh page for each reply until this gets more AJAX-y
if ($(this).siblings(".reply-content").val().length > 0) {
location.reload();
}
});
}
$(document).ready(ready);
$(document).on("page:load", ready);
|
// // Place all the behaviors and hooks related to the matching controller here.
// // All this logic will automatically be available in application.js.
var ready = function() {
$(".reply-button").hide();
$(".reply-content").focus(function() {
$(this).siblings(".reply-button").fadeIn("fast");
var container = $(this);
hideReplyContainer(container);
});
$(".reply-content").focusout(function() {
$(this).siblings(".reply-button").fadeOut("fast");
});
function hideReplyContainer(container) {
$(document).mouseup(function(e) {
var input = container.val().length;
console.log(container.val().length);
if (!container.is(e.target) && container.has(e.target).length === 0 && input === 0) {
container.siblings(".reply-button").hide();
}
});
}
}
$(document).ready(ready);
$(document).on("page:load", ready);
|
Use call instead of bind to prevent phantomjs failures
|
import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';
export default {
name: 'active-model-adapter',
initialize: function(applicationOrRegistry) {
var register;
if (applicationOrRegistry.register) {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registry for
// Ember pre 1.12, or an application instance for Ember >2.1.
register = applicationOrRegistry.register;
} else {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
register = applicationOrRegistry.registry.register;
}
register.call(applicationOrRegistry, 'adapter:-active-model', ActiveModelAdapter);
register.call(applicationOrRegistry, 'serializer:-active-model', ActiveModelSerializer);
}
};
|
import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';
export default {
name: 'active-model-adapter',
initialize: function(applicationOrRegistry) {
var register;
if (applicationOrRegistry.register) {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registry for
// Ember pre 1.12, or an application instance for Ember >2.1.
register = applicationOrRegistry.register.bind(applicationOrRegistry);
} else {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
register = applicationOrRegistry.registry.register.bind(applicationOrRegistry);
}
register('adapter:-active-model', ActiveModelAdapter);
register('serializer:-active-model', ActiveModelSerializer);
}
};
|
Switch to humanize from underscore instead of writing our own implementation.
|
Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
return new Handlebars.SafeString(html);
});
|
Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
capitalizedField = field.charAt(0).toUpperCase() + field.slice(1);
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + capitalizedField + "</label>";
return new Handlebars.SafeString(html);
});
|
Make XHR compatible with new Kitt implementation
|
var Q = require("../vendor/q/q");
exports.post = function (url, data) {
console.log('posting to', url);
var defer = Q.defer();
var xhr = new XMLHttpRequest();
xhr.onerror = function(err) {
console.log('XMLHttpRequest error: ' + err);
defer.reject(err);
};
xhr.onreadystatechange = function () {
console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
if(xhr.responseType === 'json') {
defer.resolve(xhr.response);
} else {
// backward compatibility with previous versions of Kitt
defer.resolve(JSON.parse(xhr.responseText));
}
} else if (this.readyState === 4 && this.status === 401) {
console.log('HTTP 401 returned');
defer.reject({code: 401});
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.setRequestHeader("X-Accept", "application/json");
xhr.send(data || null);
console.log('HTTP req sent to', url, data);
return defer.promise;
};
|
var Q = require("../vendor/q/q");
exports.post = function (url, data) {
console.log('posting to', url);
var defer = Q.defer();
var xhr = new XMLHttpRequest();
xhr.onerror = function(err) {
console.log('XMLHttpRequest error: ' + err);
defer.reject(err);
};
xhr.onreadystatechange = function () {
console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
defer.resolve(JSON.parse(xhr.responseText));
} else if (this.readyState === 4 && this.status === 401) {
console.log('HTTP 401 returned');
defer.reject({code: 401});
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.setRequestHeader("X-Accept", "application/json");
xhr.send(data || null);
console.log('HTTP req sent to', url, data);
return defer.promise;
};
|
Make safe_qualname more permissive (getting syntax errors on travis in 2.6)
|
import traceback
from qualname import qualname
def safe_qualname(cls):
# type: (type) -> str
result = _safe_qualname_cache.get(cls)
if not result:
try:
result = qualname(cls)
except (AttributeError, IOError, SyntaxError):
result = cls.__name__
if '<locals>' not in result:
_safe_qualname_cache[cls] = result
return result
_safe_qualname_cache = {}
def type_name(x):
return safe_qualname(x.__class__)
def exception_string(exc):
assert isinstance(exc, BaseException)
return ''.join(traceback.format_exception_only(type(exc), exc)).strip()
|
import traceback
from qualname import qualname
def safe_qualname(cls):
# type: (type) -> str
result = _safe_qualname_cache.get(cls)
if not result:
try:
result = qualname(cls)
except (AttributeError, IOError):
result = cls.__name__
if '<locals>' not in result:
_safe_qualname_cache[cls] = result
return result
_safe_qualname_cache = {}
def type_name(x):
return safe_qualname(x.__class__)
def exception_string(exc):
assert isinstance(exc, BaseException)
return ''.join(traceback.format_exception_only(type(exc), exc)).strip()
|
Allow SiteOption to load into the JS
|
import random
import json
from django import template
from django.conf import settings
from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
for opt in SiteOption.objects.filter(javascript_visible=True):
js_json[opt.name] = opt.value_boolean_or_string()
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
|
import random
import json
from django import template
from django.conf import settings
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
|
Exclude <Route>, <Switch>, etc. from UMD build
There has to be a better way...
|
import babel from "rollup-plugin-babel";
import uglify from "rollup-plugin-uglify";
import replace from "rollup-plugin-replace";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
const config = {
output: {
format: "umd",
name: "ReactRouterConfig",
globals: {
react: "React",
"react-router": "ReactRouter",
"react-router/es/Route": "ReactRouter.Route",
"react-router/es/Router": "ReactRouter.Router",
"react-router/es/Switch": "ReactRouter.Switch",
"react-router/es/matchPath": "ReactRouter.matchPath"
}
},
external: [
"react",
"react-router",
"react-router/es/Route",
"react-router/es/Router",
"react-router/es/Switch",
"react-router/es/matchPath"
],
plugins: [
babel({
exclude: "node_modules/**",
plugins: ["external-helpers"]
}),
resolve(),
commonjs({
include: /node_modules/
}),
replace({
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
})
]
};
if (process.env.NODE_ENV === "production") {
config.plugins.push(uglify());
}
export default config;
|
import babel from "rollup-plugin-babel";
import uglify from "rollup-plugin-uglify";
import replace from "rollup-plugin-replace";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
const config = {
output: {
format: "umd",
name: "ReactRouterConfig",
globals: {
react: "React",
"react-router": "ReactRouter"
}
},
external: ["react", "react-router"],
plugins: [
babel({
exclude: "node_modules/**",
plugins: ["external-helpers"]
}),
resolve(),
commonjs({
include: /node_modules/
}),
replace({
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
})
]
};
if (process.env.NODE_ENV === "production") {
config.plugins.push(uglify());
}
export default config;
|
Include private organization memberships for logged in user.
Closes #256.
|
package com.gh4a.loader;
import java.io.IOException;
import java.util.List;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.service.OrganizationService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class OrganizationListLoader extends BaseLoader<List<User>> {
private String mUserLogin;
public OrganizationListLoader(Context context, String userLogin) {
super(context);
mUserLogin = userLogin;
}
@Override
public List<User> doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
OrganizationService orgService = (OrganizationService)
app.getService(Gh4Application.ORG_SERVICE);
if (mUserLogin.equals(app.getAuthLogin())) {
return orgService.getOrganizations();
} else {
return orgService.getOrganizations(mUserLogin);
}
}
}
|
package com.gh4a.loader;
import java.io.IOException;
import java.util.List;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.service.OrganizationService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class OrganizationListLoader extends BaseLoader<List<User>> {
private String mUserLogin;
public OrganizationListLoader(Context context, String userLogin) {
super(context);
mUserLogin = userLogin;
}
@Override
public List<User> doLoadInBackground() throws IOException {
OrganizationService orgService = (OrganizationService)
Gh4Application.get().getService(Gh4Application.ORG_SERVICE);
return orgService.getOrganizations(mUserLogin);
}
}
|
Fix the response content type
|
package split
import (
"bytes"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
)
// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
var buf bytes.Buffer
multipartWriter := multipart.NewWriter(&buf)
mimeHeaders := textproto.MIMEHeader(make(map[string][]string))
mimeHeaders.Set("Content-Type", "application/http")
for _, resp := range responses {
part, err := multipartWriter.CreatePart(mimeHeaders)
if err != nil {
return err
}
resp.Write(part)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()}))
w.WriteHeader(http.StatusOK)
buf.WriteTo(w)
return nil
}
|
package split
import (
"bytes"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
)
// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
var buf bytes.Buffer
multipartWriter := multipart.NewWriter(&buf)
mimeHeaders := textproto.MIMEHeader(make(map[string][]string))
mimeHeaders.Set("Content-Type", "application/http")
for _, resp := range responses {
part, err := multipartWriter.CreatePart(mimeHeaders)
if err != nil {
return err
}
resp.Write(part)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()}))
buf.WriteTo(w)
return nil
}
|
Fix the postcode form so that it's actually validating the input
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_postcode(self):
postcode = self.cleaned_data['postcode']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
|
Add missing dots at the end of exception messages
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Zend\Code\Generator\ClassGenerator;
/**
* @internal
*/
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
/**
* {@inheritdoc}
*/
public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
{
parent::generate($originalClass, $classGenerator);
if ($classGenerator->hasMethod('__destruct')) {
$destructor = $classGenerator->getMethod('__destruct');
$body = $destructor->getBody();
$newBody = preg_replace('/^(\$this->initializer[a-zA-Z0-9]++) && .*;\n\nreturn (\$this->valueHolder)/', '$1 || $2', $body);
if ($body === $newBody) {
throw new \UnexpectedValueException(sprintf('Unexpected lazy-proxy format generated for method %s::__destruct().', $originalClass->name));
}
$destructor->setBody($newBody);
}
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Zend\Code\Generator\ClassGenerator;
/**
* @internal
*/
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
/**
* {@inheritdoc}
*/
public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
{
parent::generate($originalClass, $classGenerator);
if ($classGenerator->hasMethod('__destruct')) {
$destructor = $classGenerator->getMethod('__destruct');
$body = $destructor->getBody();
$newBody = preg_replace('/^(\$this->initializer[a-zA-Z0-9]++) && .*;\n\nreturn (\$this->valueHolder)/', '$1 || $2', $body);
if ($body === $newBody) {
throw new \UnexpectedValueException(sprintf('Unexpected lazy-proxy format generated for method %s::__destruct()', $originalClass->name));
}
$destructor->setBody($newBody);
}
}
}
|
Allow `-` in process names
|
package main
import (
"bufio"
"os"
"regexp"
)
type procfileEntry struct {
Name string
Command string
Port int
}
func parseProcfile(path string, portBase, portStep int) (entries []procfileEntry) {
re, _ := regexp.Compile(`^([\w-]+):\s+(.+)$`)
f, err := os.Open(path)
fatalOnErr(err)
port := portBase
names := make(map[string]bool)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if len(scanner.Text()) == 0 {
continue
}
params := re.FindStringSubmatch(scanner.Text())
if len(params) != 3 {
continue
}
name, cmd := params[1], params[2]
if names[name] {
fatal("Process names must be uniq")
}
names[name] = true
entries = append(entries, procfileEntry{name, cmd, port})
port += portStep
}
fatalOnErr(scanner.Err())
if len(entries) == 0 {
fatal("No entries was found in Procfile")
}
return
}
|
package main
import (
"bufio"
"os"
"regexp"
)
type procfileEntry struct {
Name string
Command string
Port int
}
func parseProcfile(path string, portBase, portStep int) (entries []procfileEntry) {
re, _ := regexp.Compile("^(\\w+):\\s+(.+)$")
f, err := os.Open(path)
fatalOnErr(err)
port := portBase
names := make(map[string]bool)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if len(scanner.Text()) == 0 {
continue
}
params := re.FindStringSubmatch(scanner.Text())
if len(params) != 3 {
continue
}
name, cmd := params[1], params[2]
if names[name] {
fatal("Process names must be uniq")
}
names[name] = true
entries = append(entries, procfileEntry{name, cmd, port})
port += portStep
}
fatalOnErr(scanner.Err())
if len(entries) == 0 {
fatal("No entries was found in Procfile")
}
return
}
|
Add security_group_rule to objects registry
This adds the security_group_rule module to the objects registry,
which allows a service to make sure that all of its objects are
registered before any could be received over RPC.
We don't really have a test for any of these because of the nature
of how they're imported. Refactoring this later could provide some
incremental steps to making this more testable.
Change-Id: Ie96021f3cdeac6addab21c42a14cd8f136eb0b27
Closes-Bug: #1264816
|
# Copyright 2013 IBM Corp.
#
# 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.
def register_all():
# NOTE(danms): You must make sure your object gets imported in this
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.dns_domain')
__import__('nova.objects.instance')
__import__('nova.objects.instance_info_cache')
__import__('nova.objects.security_group')
__import__('nova.objects.migration')
__import__('nova.objects.quotas')
__import__('nova.objects.virtual_interface')
__import__('nova.objects.network')
__import__('nova.objects.block_device')
__import__('nova.objects.fixed_ip')
__import__('nova.objects.floating_ip')
__import__('nova.objects.security_group_rule')
|
# Copyright 2013 IBM Corp.
#
# 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.
def register_all():
# NOTE(danms): You must make sure your object gets imported in this
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.dns_domain')
__import__('nova.objects.instance')
__import__('nova.objects.instance_info_cache')
__import__('nova.objects.security_group')
__import__('nova.objects.migration')
__import__('nova.objects.quotas')
__import__('nova.objects.virtual_interface')
__import__('nova.objects.network')
__import__('nova.objects.block_device')
__import__('nova.objects.fixed_ip')
__import__('nova.objects.floating_ip')
|
Set default conversation time to 30 minutes
|
package org.gluu.jsf2.service;
import java.io.Serializable;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@ConversationScoped
public class ConversationService implements Serializable {
private static final long serialVersionUID = -7432197667275722872L;
private static final long CONVERSATION_TIMEOUT = 30 * 60 * 60 * 1000L;
@Inject
private Conversation conversation;
public void initConversation() {
if (!FacesContext.getCurrentInstance().isPostback() && conversation.isTransient()) {
conversation.begin();
conversation.setTimeout(CONVERSATION_TIMEOUT);
}
}
public void endConversation() {
if (!conversation.isTransient()) {
conversation.end();
}
}
}
|
package org.gluu.jsf2.service;
import java.io.Serializable;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@ConversationScoped
public class ConversationService implements Serializable {
private static final long serialVersionUID = -7432197667275722872L;
@Inject
private Conversation conversation;
public void initConversation() {
if (!FacesContext.getCurrentInstance().isPostback() && conversation.isTransient()) {
conversation.begin();
}
}
public void endConversation() {
if (!conversation.isTransient()) {
conversation.end();
}
}
}
|
Fix tests to respect removal of magic arg
|
var test = require('tape');
var loader = require('../primus-loader');
var qsa = require('fdom/qsa');
var async = require('async');
test('can load primus', function(t) {
t.plan(2);
loader(location.origin, function(err, p) {
t.ifError(err);
t.ok(p === Primus, 'primus loaded, p is a valid Primus reference');
});
});
test('remove the primus script from the page', function(t) {
t.plan(1);
// iterate through the scripts and remove any primus scripts
qsa('script').forEach(function(script) {
if (/primus\.js$/.test(script.src)) {
script.parentNode.removeChild(script);
}
});
// unset Primus
Primus = undefined;
t.equal(typeof Primus, 'undefined', 'Primus now undefined');
});
test('concurrent loads pass', function(t) {
var dl = function(cb) {
setTimeout(function() {
loader(location.origin, cb);
}, 0);
};
t.plan(7);
async.parallel([dl, dl, dl, dl, dl], function(err, instances) {
t.ifError(err);
t.ok(Array.isArray(instances), 'got instances');
instances.forEach(function(instance) {
t.ok(instance === Primus, 'valid Primus instance');
})
});
});
|
var test = require('tape');
var loader = require('../primus-loader');
var qsa = require('fdom/qsa');
var async = require('async');
test('can load primus', function(t) {
t.plan(2);
loader(location.origin, function(err, p) {
t.ifError(err);
t.ok(p === Primus, 'primus loaded, p is a valid Primus reference');
});
});
test('can load primus, defaulting to location.origin', function(t) {
t.plan(2);
loader(function(err, p) {
t.ifError(err);
t.ok(p === Primus, 'primus loaded, p is a valid Primus reference');
});
});
test('remove the primus script from the page', function(t) {
t.plan(1);
// iterate through the scripts and remove any primus scripts
qsa('script').forEach(function(script) {
if (/primus\.js$/.test(script.src)) {
script.parentNode.removeChild(script);
}
});
// unset Primus
Primus = undefined;
t.equal(typeof Primus, 'undefined', 'Primus now undefined');
});
test('concurrent loads pass', function(t) {
var dl = function(cb) {
setTimeout(function() {
loader(cb);
}, 0);
};
t.plan(7);
async.parallel([dl, dl, dl, dl, dl], function(err, instances) {
t.ifError(err);
t.ok(Array.isArray(instances), 'got instances');
instances.forEach(function(instance) {
t.ok(instance === Primus, 'valid Primus instance');
})
});
});
|
Add a settings key to ensure index at start
|
from pyramid.settings import asbool
from .client import ElasticClient
def client_from_config(settings, prefix='elastic.'):
"""
Instantiate and configure an Elasticsearch from settings.
In typical Pyramid usage, you shouldn't use this directly: instead, just
include ``pyramid_es`` and use the :py:func:`get_client` function to get
access to the shared :py:class:`.client.ElasticClient` instance.
"""
return ElasticClient(
servers=settings.get(prefix + 'servers', ['localhost:9200']),
timeout=settings.get(prefix + 'timeout', 1.0),
index=settings[prefix + 'index'],
use_transaction=asbool(settings.get(prefix + 'use_transaction', True)),
disable_indexing=settings.get(prefix + 'disable_indexing', False))
def includeme(config):
registry = config.registry
settings = registry.settings
client = client_from_config(settings)
if asbool(settings.get('elastic.ensure_index_on_start')):
client.ensure_index()
registry.pyramid_es_client = client
def get_client(request):
"""
Get the registered Elasticsearch client. The supplied argument can be
either a ``Request`` instance or a ``Registry``.
"""
registry = getattr(request, 'registry', None)
if registry is None:
registry = request
return registry.pyramid_es_client
|
from pyramid.settings import asbool
from .client import ElasticClient
def client_from_config(settings, prefix='elastic.'):
"""
Instantiate and configure an Elasticsearch from settings.
In typical Pyramid usage, you shouldn't use this directly: instead, just
include ``pyramid_es`` and use the :py:func:`get_client` function to get
access to the shared :py:class:`.client.ElasticClient` instance.
"""
return ElasticClient(
servers=settings.get(prefix + 'servers', ['localhost:9200']),
timeout=settings.get(prefix + 'timeout', 1.0),
index=settings[prefix + 'index'],
use_transaction=asbool(settings.get(prefix + 'use_transaction', True)),
disable_indexing=settings.get(prefix + 'disable_indexing', False))
def includeme(config):
registry = config.registry
settings = registry.settings
client = client_from_config(settings)
client.ensure_index()
registry.pyramid_es_client = client
def get_client(request):
"""
Get the registered Elasticsearch client. The supplied argument can be
either a ``Request`` instance or a ``Registry``.
"""
registry = getattr(request, 'registry', None)
if registry is None:
registry = request
return registry.pyramid_es_client
|
Replace placeholder countries with real service call
|
'use strict';
mldsApp.factory('CountryService', ['$http', '$log', '$q', function($http, $log, $q){
var countriesListQ = $http.get('/app/rest/countries')
.then(function(d){return d.data;});
var service = {};
service.countries = [];
service.countriesByCode = {};
service.getCountries = function getCountries() {
return countriesListQ;
};
countriesListQ.then(function(countries){
// append to countries list
Array.prototype.push.apply(service.countries,countries);
// fill countriesByCode map
service.countries.map(function(c){
service.countriesByCode[c.isoCode2] = c;
});
$log.log('CountryService', service);
});
return service;
}]);
|
'use strict';
mldsApp.factory('CountryService', ['$http', '$log', '$q', function($http, $log, $q){
return {
getCountries: function() {
return $q.when([
{
isoCode2: 'DK',
isoCode3: 'DNK',
commonName: 'Denmark'
},
{
isoCode2: 'FR',
isoCode3: 'FRA',
commonName: 'France'
},
{
isoCode2: 'UA',
isoCode3: 'URE',
commonName: 'United Arab Emirates'
},
{
isoCode2: 'GB',
isoCode3: 'GBP',
commonName: 'United Kingdom'
},
{
isoCode2: 'US',
isoCode3: 'USA',
commonName: 'United States'
}
]);
//FIXME retrieve countries from server
//return $http.get('/app/countries');
},
};
}]);
|
Update click requirement from <6.8,>=6.7 to >=6.7,<7.1
Updates the requirements on [click](https://github.com/pallets/click) to permit the latest version.
- [Release notes](https://github.com/pallets/click/releases)
- [Changelog](https://github.com/pallets/click/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pallets/click/commits/7.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1-pre',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<7.1',
'PyYAML>=3.12,<5.2',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1-pre',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<6.8',
'PyYAML>=3.12,<5.2',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
Clean up date guessing benchmarking code
* Remove unused imports
* use sys.exit(message) instead of exit()
* Use Pythonic way to call main function (if __name__ == '__main__')
* Reformat code
* Avoid encoding / decoding things to / from UTF-8
|
#!/usr/bin/env python3
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
if __name__ == '__main__':
benchmark_date_guessing()
|
#!/usr/bin/env python
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-8")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory,filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(
url='http://dont.know.the.date/some/path.html',
html=content
)
print(date_guess.date)
main()
|
Add Header to Produit page
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nos Bonbons</title>
</head>
<body>
<?php
include "Reference.php";
?>
<?php include("header.php"); ?>
<?php //include("footer.php"); ?>
<article class="card" style="width: 20rem;">
<figure class="imageBonbon">
<img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap">
</figure>
<!-- <div class="card-block">
<h4 class="card-title"><?php echo $value['Titre']?></h4>
<p class="card-text"><?php echo $value['Description']?></p>
</div> -->
</article>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nos Bonbons</title>
</head>
<body>
<?php
include "Reference.php";
?>
<?php //include("header.php"); ?>
<?php //include("footer.php"); ?>
<article class="card" style="width: 20rem;">
<figure class="imageBonbon">
<img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap">
</figure>
<!-- <div class="card-block">
<h4 class="card-title"><?php echo $value['Titre']?></h4>
<p class="card-text"><?php echo $value['Description']?></p>
</div> -->
</article>
</body>
</html>
|
Write compact json when using built-in json.dumps
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import ast
import sys
import struct
import functools
try:
import ujson as json
json_dumps = json.dumps
except ImportError:
import json
json_dumps = functools.partial(json.dumps, separators=',:')
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
def flatten_dtype(dtype):
dtype = str(dtype)
if dtype.startswith(('{', '[')):
return ast.literal_eval(dtype)
return dtype
def write_i64(stream, *values):
for value in values:
stream.write(struct.pack('<Q', value))
def read_i64(stream, count=None):
if count is None:
return struct.unpack('<Q', stream.read(8))[0]
return tuple(struct.unpack('<Q', stream.read(8))[0] for _ in range(count))
def write_json(stream, data):
payload = json_dumps(data).encode('utf-8')
write_i64(stream, len(payload))
stream.write(payload)
return len(payload) + 8
def read_json(stream):
length = read_i64(stream)
return json.loads(stream.read(length).decode('utf-8'))
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import ast
import sys
import struct
try:
import ujson as json
except ImportError:
import json
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
def flatten_dtype(dtype):
dtype = str(dtype)
if dtype.startswith(('{', '[')):
return ast.literal_eval(dtype)
return dtype
def write_i64(stream, *values):
for value in values:
stream.write(struct.pack('<Q', value))
def read_i64(stream, count=None):
if count is None:
return struct.unpack('<Q', stream.read(8))[0]
return tuple(struct.unpack('<Q', stream.read(8))[0] for _ in range(count))
def write_json(stream, data):
payload = json.dumps(data).encode('utf-8')
write_i64(stream, len(payload))
stream.write(payload)
return len(payload) + 8
def read_json(stream):
length = read_i64(stream)
return json.loads(stream.read(length).decode('utf-8'))
|
Add test case related to devide numbers.
|
package study.hard.javalib.nativelib;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MathTest {
private static Logger logger = LoggerFactory.getLogger(MathTest.class);
private Double amount;
private Double ratio;
private Double result;
@Before
public void setUp() {
amount = 0D;
ratio = 0D;
result = 0D;
logger.debug("amount: {} / ratio: {} / result: {}", new Object[] {amount, ratio, result});
}
@Test
public void floor() {
amount = 39000.000D;
ratio = 0.020D;
result = Math.floor(amount * ratio);
logger.debug("result: {}", result);
assertEquals(new Double(780D), result);
}
@Test
public void ceil() {
logger.debug("(3 / 7): " + (3 / 7));
logger.debug("(3D / 7D): " + (3D / 7D));
logger.debug("Math.ceil(3 / 7): " + Math.ceil(3 / 7));
logger.debug("Math.ceil(3D / 7D): " + Math.ceil(3D / 7D));
logger.debug("(int)Math.ceil(3 / 7): " + (int)Math.ceil(3 / 7));
logger.debug("(int)Math.ceil(3D / 7D): " + (int)Math.ceil(3D / 7D));
logger.debug("(int)Math.ceil((double)3 / (double)7): " + (int)Math.ceil((double)3 / (double)7));
}
}
|
package study.hard.javalib.nativelib;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MathTest {
private static Logger logger = LoggerFactory.getLogger(MathTest.class);
private Double amount;
private Double ratio;
private Double result;
@Before
public void setUp() {
amount = 0D;
ratio = 0D;
result = 0D;
logger.debug("amount: {} / ratio: {} / result: {}", new Object[] {amount, ratio, result});
}
@Test
public void floor() {
amount = 39000.000D;
ratio = 0.020D;
result = Math.floor(amount * ratio);
logger.debug("result: {}", result);
assertEquals(new Double(780D), result);
}
}
|
Make cloud check evaluate greater than or equals
|
from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')
self.last_updated = datetime.now()
def is_cloudy(self, threshold):
# Only update every 20 minutes at most
if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):
self.load_data()
return self.data.current.clouds >= threshold
|
from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')
self.last_updated = datetime.now()
def is_cloudy(self, threshold):
# Only update every 20 minutes at most
if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):
self.load_data()
return self.data.current.clouds > threshold
|
Fix native reference so that it does not violate circularity rules between $impl and header files.
PiperOrigin-RevId: 168731186
|
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.j2cl.transpiler.integration.selfreferencingnativetype;
import jsinterop.annotations.JsType;
@JsType(namespace = "zoo")
public class Foo {
public static String getMe() {
return "me";
}
// Refer to the implementation "zoo.Foo$impl" instead to avoid creating an "invalid" circular
// reference.
@JsType(isNative = true, name = "Foo$impl", namespace = "zoo")
public static class ZooFoo {
public static native String getMe();
}
public static String getMeViaNative() {
return ZooFoo.getMe();
}
}
|
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.j2cl.transpiler.integration.selfreferencingnativetype;
import jsinterop.annotations.JsType;
@JsType(namespace = "zoo")
public class Foo {
public static String getMe() {
return "me";
}
@JsType(isNative = true, name = "Foo", namespace = "zoo")
public static class ZooFoo {
public static native String getMe();
}
public static String getMeViaNative() {
return ZooFoo.getMe();
}
}
|
Use `navigator.userAgentData` for platform detection when available
|
function uaDetect(platform, re) {
if (navigator.userAgentData) {
return platform === navigator.userAgentData.platform;
}
return re.test(navigator.userAgent);
}
var IS_MAC = uaDetect("macOS", /Mac/);
var KEY_A = 65;
var KEY_COMMA = 188;
var KEY_RETURN = 13;
var KEY_ESC = 27;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_P = 80;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_N = 78;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CMD = IS_MAC ? 91 : 17;
var KEY_CTRL = IS_MAC ? 18 : 17;
var KEY_TAB = 9;
var TAG_SELECT = 1;
var TAG_INPUT = 2;
// for now, android support in general is too spotty to support validity
var SUPPORTS_VALIDITY_API = !uaDetect("Android", /android/i) && !!document.createElement('input').validity;
|
var IS_MAC = /Mac/.test(navigator.userAgent);
var KEY_A = 65;
var KEY_COMMA = 188;
var KEY_RETURN = 13;
var KEY_ESC = 27;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_P = 80;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_N = 78;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CMD = IS_MAC ? 91 : 17;
var KEY_CTRL = IS_MAC ? 18 : 17;
var KEY_TAB = 9;
var TAG_SELECT = 1;
var TAG_INPUT = 2;
// for now, android support in general is too spotty to support validity
var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('input').validity;
|
Change HTTP error for fallback: did not match standards.
|
package net.chibidevteam.apiversioning.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import net.chibidevteam.apiversioning.annotation.ValidApiVersion;
@RestController
@Validated
public class ApiVersionFallbackController {
@Value("${net.chibidevteam.apiversioning.path.varname}")
private final String apiPathVarname = "";
@RequestMapping("${net.chibidevteam.apiversioning.path.api}/**")
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "This endpoint is not implemented for the given version")
public void pathFallback(@ValidApiVersion @PathVariable(apiPathVarname) String apiVersion) {
// It only makes difference between not supported versions and non implemented endpoints.
// It always leads to a HTTP error
}
}
|
package net.chibidevteam.apiversioning.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import net.chibidevteam.apiversioning.annotation.ValidApiVersion;
@RestController
@Validated
public class ApiVersionFallbackController {
@Value("${net.chibidevteam.apiversioning.path.varname}")
private final String apiPathVarname = "";
@RequestMapping("${net.chibidevteam.apiversioning.path.api}/**")
@ResponseStatus(code = HttpStatus.NOT_IMPLEMENTED, reason = "This endpoint is not implemented for the given version")
public void pathFallback(@ValidApiVersion @PathVariable(apiPathVarname) String apiVersion) {
// It only makes difference between not supported versions and non implemented endpoints.
// It always leads to a HTTP error
}
}
|
Disable "no-negated-condition" for if condition
|
'use strict';
const os = require('os');
const path = require('path');
const alfy = require('alfy');
const dotenv = require('dotenv');
const imgur = require('imgur');
const clipboardy = require('clipboardy');
// Load config from ~/.alfred-imgur
dotenv.config({path: path.join(os.homedir(), '.alfred-imgur.conf')});
// Check for errors
if (alfy.input === 'errorNoSelection') {
console.log(`Error: no file selected`);
} else if (alfy.input === 'errorFolder') {
console.log(`Error: folder detected - please select a file`);
// eslint-disable-next-line no-negated-condition
} else if (!path.extname(alfy.input).match(/(jpg|png|gif|tiff)/)) {
console.log(`Error: no valid image file extension detected`);
} else {
// Set client id
imgur.setClientId(process.env.APIKEY);
// Upload file to Imgur
imgur.uploadFile(alfy.input).then(function (json) {
// Copy upload URL to clipboard and write to stdout
clipboardy.writeSync(json.data.link);
console.log(json.data.link);
}).catch(function (err) {
console.error(`Error: ${err.message}`);
});
}
|
'use strict';
const os = require('os');
const path = require('path');
const alfy = require('alfy');
const dotenv = require('dotenv');
const imgur = require('imgur');
const clipboardy = require('clipboardy');
// Load config from ~/.alfred-imgur
dotenv.config({path: path.join(os.homedir(), '.alfred-imgur.conf')});
// Check for errors
if (alfy.input === 'errorNoSelection') {
console.log(`Error: no file selected`);
} else if (alfy.input === 'errorFolder') {
console.log(`Error: folder detected - please select a file`);
} else if (!path.extname(alfy.input).match(/(jpg|png|gif|tiff)/)) {
console.log(`Error: no valid image file extension detected`);
} else {
// Set client id
imgur.setClientId(process.env.APIKEY);
// Upload file to Imgur
imgur.uploadFile(alfy.input).then(function (json) {
// Copy upload URL to clipboard and write to stdout
clipboardy.writeSync(json.data.link);
console.log(json.data.link);
}).catch(function (err) {
console.error(`Error: ${err.message}`);
});
}
|
Refactor bubble legend compatibility rules with styles for clarity
|
var _ = require('underscore');
var LegendTypes = require('builder/editor/layers/layer-content-views/legend/legend-types');
var styleHelper = require('builder/helpers/style');
module.exports = [
{
value: LegendTypes.NONE,
tooltipTranslationKey: 'editor.legend.tooltips.style.none',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/none.tpl'),
label: _t('editor.legend.types.none')
}, {
value: LegendTypes.BUBBLE,
tooltipTranslationKey: 'editor.legend.tooltips.style.bubble',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/bubble.tpl'),
label: _t('editor.legend.types.bubble'),
isStyleCompatible: function (styleModel) {
var size = styleHelper.getSize(styleModel);
if (size == null) return false;
return size && size.attribute !== undefined;
}
}
];
|
var _ = require('underscore');
var LegendTypes = require('builder/editor/layers/layer-content-views/legend/legend-types');
module.exports = [
{
value: LegendTypes.NONE,
tooltipTranslationKey: 'editor.legend.tooltips.style.none',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/none.tpl'),
label: _t('editor.legend.types.none')
}, {
value: LegendTypes.BUBBLE,
tooltipTranslationKey: 'editor.legend.tooltips.style.bubble',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/bubble.tpl'),
label: _t('editor.legend.types.bubble'),
isStyleCompatible: function (styleModel) {
var fill = styleModel.get('fill');
var stroke = styleModel.get('stroke');
var size;
if (!fill && !stroke || _.isEmpty(fill) && _.isEmpty(stroke)) return false;
size = fill && fill.size || stroke && stroke.size;
return size && size.attribute !== undefined;
}
}
];
|
Remove support for versions before 5.3
|
<?php
namespace Ferret\Detector;
use \Ferret\Detector\DetectorInterface;
use \Ferret\Detector\Exception\DetectorException;
class Fileinfo extends DetectorAbstract
{
protected $magic_filepath = null;
public function __construct()
{
if (!class_exists('finfo'))
{
throw new DetectorException('Fileinfo extension is not loaded');
}
}
public function getMagicFilepath()
{
return $this->magic_filepath;
}
public function setMagicFilepath($magic_filepath)
{
$this->magic_filepath = $magic_filepath;
}
public function detect($filepath)
{
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($filepath);
if ($type !== false)
{
return $type;
}
return false;
}
}
|
<?php
namespace Ferret\Detector;
use \Ferret\Detector\DetectorInterface;
use \Ferret\Detector\Exception\DetectorException;
class Fileinfo extends DetectorAbstract
{
protected $magic_filepath = null;
public function __construct()
{
if (!class_exists('finfo'))
{
throw new DetectorException('Fileinfo extension is not loaded');
}
}
public function getMagicFilepath()
{
return $this->magic_filepath;
}
public function setMagicFilepath($magic_filepath)
{
$this->magic_filepath = $magic_filepath;
}
public function detect($filepath)
{
// Support for PHP 5.3+
if (defined('FILEINFO_MIME_TYPE'))
{
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($filepath);
}
else
{
$finfo = \finfo_open(FILEINFO_MIME);
$type = \finfo_file($finfo, $filepath);
\finfo_close($finfo);
}
if ($type !== false)
{
return $type;
}
return false;
}
}
|
Add italic and inverse ansi codes to definition
|
// ANSI color code outputs for strings
var ANSI_CODES = {
"off": 0,
"bold": 1,
"italic": 3,
"underline": 4,
"blink": 5,
"inverse": 7,
"hidden": 8,
"black": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"white": 37,
"black_bg": 40,
"red_bg": 41,
"green_bg": 42,
"yellow_bg": 43,
"blue_bg": 44,
"magenta_bg": 45,
"cyan_bg": 46,
"white_bg": 47
};
exports.set = function(str, color) {
if(!color) return str;
var color_attrs = color.split("+");
var ansi_str = "";
for(var i=0, attr; attr = color_attrs[i]; i++) {
ansi_str += "\033[" + ANSI_CODES[attr] + "m";
}
ansi_str += str + "\033[" + ANSI_CODES["off"] + "m";
return ansi_str;
};
|
// ANSI color code outputs for strings
var ANSI_CODES = {
"off": 0,
"bold": 1,
"underline": 4,
"blink": 5,
"hidden": 8,
"black": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"white": 37,
"black_bg": 40,
"red_bg": 41,
"green_bg": 42,
"yellow_bg": 43,
"blue_bg": 44,
"magenta_bg": 45,
"cyan_bg": 46,
"white_bg": 47
};
exports.set = function(str, color) {
if(!color) return str;
var color_attrs = color.split("+");
var ansi_str = "";
for(var i=0, attr; attr = color_attrs[i]; i++) {
ansi_str += "\033[" + ANSI_CODES[attr] + "m";
}
ansi_str += str + "\033[0m";
return ansi_str;
};
|
Fix the potential issue of variable shadowing
|
'use strict';
var document = require('global/document');
var window = require('global/window');
var createCustomEvent;
if (window && window.CustomEvent && typeof window.CustomEvent === 'function') {
createCustomEvent = function createCustomEventDefault(type, eventInitDict) {
return new window.CustomEvent(type, eventInitDict);
};
} else if (document && document.createEvent) {
// http://www.w3.org/TR/dom/#customevent
createCustomEvent = function createCustomEventShim(type, eventInitDict) {
var params = eventInitDict || {};
var evt = document.createEvent('CustomEvent');
if (evt.initCustomEvent) {
evt.initCustomEvent(
type,
!!params.bubbles,
!!params.cancelable,
params.detail
);
}
return evt;
};
}
module.exports = createCustomEvent;
|
'use strict';
var document = require('global/document');
var window = require('global/window');
var createCustomEvent;
if (window && window.CustomEvent && typeof window.CustomEvent === 'function') {
createCustomEvent = function createCustomEvent(type, eventInitDict) {
return new window.CustomEvent(type, eventInitDict);
};
} else if (document && document.createEvent) {
// http://www.w3.org/TR/dom/#customevent
createCustomEvent = function createCustomEventShim(type, eventInitDict) {
var params = eventInitDict || {};
var evt = document.createEvent('CustomEvent');
if (evt.initCustomEvent) {
evt.initCustomEvent(
type,
!!params.bubbles,
!!params.cancelable,
params.detail
);
}
return evt;
};
}
module.exports = createCustomEvent;
|
LUCENE-1769: Add also the opposite assert statement
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@891907 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.lucene;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.util.LuceneTestCase;
public class TestAssertions extends LuceneTestCase {
public void test() {
try {
assert Boolean.FALSE.booleanValue();
fail("assertions are not enabled!");
} catch (AssertionError e) {
assert Boolean.TRUE.booleanValue();
}
}
}
|
package org.apache.lucene;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.util.LuceneTestCase;
public class TestAssertions extends LuceneTestCase {
public void test() {
try {
assert Boolean.FALSE.booleanValue();
fail("assertions are not enabled!");
} catch (AssertionError e) {
}
}
}
|
Fix Job error on shutdown
|
/*******************************************************************************
* Copyright 2013 Friedrich Schiller University Jena
* stephan.druskat@uni-jena.de
*
* 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 de.uni_jena.iaa.linktype.atomic.core;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextService;
public class Perspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
((IContextService) PlatformUI.getWorkbench().getService(IContextService.class)).activateContext("de.uni_jena.iaa.linktype.atomic.core.context");
}
}
|
/*******************************************************************************
* Copyright 2013 Friedrich Schiller University Jena
* stephan.druskat@uni-jena.de
*
* 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 de.uni_jena.iaa.linktype.atomic.core;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextService;
public class Perspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
((IContextService) PlatformUI.getWorkbench().getService(IContextService.class)).activateContext("de.uni_jena.iaa.linktype.atomic.core.context");
}
});
}
}
|
Switch out 'createModel' for 'extend'
|
var Arrow = require('arrow');
var Base = Arrow.Model.extend('base', {
connector: 'appc.redis',
fields: { },
expire: function expire(seconds, callback){
return this.getConnector().expire(this.getModel(), this, seconds, callback);
},
expireAt: function expireAt(date, callback){
return this.getConnector().expireAt(this.getModel(), this, date, callback);
},
keys: function keys(limit, callback){
return this.getConnector().keys(this.getModel(), limit, callback);
},
persist: function persist(callback){
return this.getConnector().persist(this.getModel(), this, callback);
},
ttl: function ttl(callback){
return this.getConnector().ttl(this.getModel(), this, callback);
}
});
module.exports = Base;
|
var Arrow = require('arrow');
module.exports = Arrow.createModel('base', {
connector: 'appc.redis',
fields: { },
expire: function expire(seconds, callback){
return this.getConnector().expire(this.getModel(), this, seconds, callback);
},
expireAt: function expireAt(date, callback){
return this.getConnector().expireAt(this.getModel(), this, date, callback);
},
keys: function keys(limit, callback){
return this.getConnector().keys(this.getModel(), limit, callback);
},
persist: function persist(callback){
return this.getConnector().persist(this.getModel(), this, callback);
},
ttl: function ttl(callback){
return this.getConnector().ttl(this.getModel(), this, callback);
}
});
|
Add the Accept header to all API calls
|
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
import HalJsonVuex from 'hal-json-vuex'
import lang from './lang'
class StorePlugin {
install (Vue, options) {
Vue.use(Vuex)
store = new Vuex.Store({
modules: {
lang
},
strict: process.env.NODE_ENV !== 'production'
})
axios.defaults.withCredentials = true
axios.defaults.baseURL = window.environment.API_ROOT_URL
axios.defaults.headers.common.Accept = 'application/hal+json'
Vue.use(VueAxios, axios)
let halJsonVuex = HalJsonVuex
if (typeof halJsonVuex !== 'function') {
halJsonVuex = HalJsonVuex.default
}
apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true })
Vue.use(apiStore)
}
}
export let apiStore
export let store
export default new StorePlugin()
|
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
import HalJsonVuex from 'hal-json-vuex'
import lang from './lang'
class StorePlugin {
install (Vue, options) {
Vue.use(Vuex)
store = new Vuex.Store({
modules: {
lang
},
strict: process.env.NODE_ENV !== 'production'
})
axios.defaults.withCredentials = true
axios.defaults.baseURL = window.environment.API_ROOT_URL
Vue.use(VueAxios, axios)
let halJsonVuex = HalJsonVuex
if (typeof halJsonVuex !== 'function') {
halJsonVuex = HalJsonVuex.default
}
apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true })
Vue.use(apiStore)
}
}
export let apiStore
export let store
export default new StorePlugin()
|
Use standard 3-part version number.
|
import os
from setuptools import setup, find_packages
setup(
name = 'temps',
version = '0.1.0',
license = 'MIT',
description = 'Context managers for creating and cleaning up temporary directories and files.',
long_description = open(os.path.join(os.path.dirname(__file__),
'README.md')).read(),
keywords = 'python temporary files directories context manager',
url = 'https://github.com/todddeluca/temps',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
py_modules = ['temps'],
)
|
import os
from setuptools import setup, find_packages
setup(
name = 'temps',
version = '0.1',
license = 'MIT',
description = 'Context managers for creating and cleaning up temporary directories and files.',
long_description = open(os.path.join(os.path.dirname(__file__),
'README.md')).read(),
keywords = 'python temporary files directories context manager',
url = 'https://github.com/todddeluca/temps',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
py_modules = ['temps'],
)
|
Convert *_INTERVAL variables to int
ALERT_INTERVAL and NOTIFICATION_INTERVAL are now converted to
numbers. This allows user-defined ALERT_INTERVAL and
NOTIFICATION_INTERVAL env variables to work without throwing
TypeErrors:
return self.run(*args, **kwargs)
File "/cabot/cabot/cabotapp/tasks.py", line 68, in update_service
service.update_status()
File "/cabot/cabot/cabotapp/models.py", line 243, in update_status
self.alert()
File "/cabot/cabot/cabotapp/models.py", line 174, in alert
if self.last_alert_sent and (timezone.now() - timedelta(minutes=settings.ALERT_INTERVAL)) < self.last_alert_sent:
TypeError: unsupported type for timedelta minutes component: str
|
import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.environ.get('JENKINS_PASS')
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
ALERT_INTERVAL = int(os.environ.get('ALERT_INTERVAL', 10))
NOTIFICATION_INTERVAL = int(os.environ.get('NOTIFICATION_INTERVAL', 120))
# Default plugins are used if the user has not specified.
CABOT_PLUGINS_ENABLED = os.environ.get('CABOT_PLUGINS_ENABLED', 'cabot_alert_hipchat,cabot_alert_twilio,cabot_alert_email')
|
import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.environ.get('JENKINS_PASS')
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
ALERT_INTERVAL = os.environ.get('ALERT_INTERVAL', 10)
NOTIFICATION_INTERVAL = os.environ.get('NOTIFICATION_INTERVAL', 120)
# Default plugins are used if the user has not specified.
CABOT_PLUGINS_ENABLED = os.environ.get('CABOT_PLUGINS_ENABLED', 'cabot_alert_hipchat,cabot_alert_twilio,cabot_alert_email')
|
Make each manufacturer a link to the edit page instead of using a form button
|
<!-- resources/views/admin/manufacturer_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Manufacturers</h2>
<p>Click a manufacturer to edit</p>
<table class="table">
<tbody>
@foreach ($manufacturers->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $manufacturer)
<td>{{ $manufacturer->id }}</td>
<td><a href="/admin/manufacturers/{{ $manufacturer->id }}/edit">{{ $manufacturer->manufacturer }}</a></td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Manufacturer</h2>
<!-- Add a new manufacturer -->
<form class="form-inline" action="/admin/manufacturers" method="POST">
<div class="form-group">
{{ csrf_field() }}
<label for="manufacturer">New Manufacturer:</label> <input type="TEXT" class="form-control" id="manufacturer" name="manufacturer" size="20" placeholder="Manufacturer" />
<button class="btn btn-default" type="SUBMIT">Add manufacturer</button> / <a href="/">Main</a>
</div>
</form>
@endsection
|
<!-- resources/views/admin/manufacturer_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Manufacturers</h2>
<table class="table">
<tbody>
@foreach ($manufacturers->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $manufacturer)
<td>{{ $manufacturer->id }}</td>
<td>{{ $manufacturer->manufacturer }}</td>
<td>
<form action="/admin/manufacturers/{{ $manufacturer->id }}/edit" method="POST">
<button type="submit">Edit</button>
</form>
</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Manufacturer</h2>
<!-- Add a new manufacturer -->
<form action="/admin/manufacturers" method="POST">
{{ csrf_field() }}
New Manufacturer: <input type="TEXT" name="manufacturer" size="20" />
<button type="SUBMIT">Add manufacturer</button> / <a href="/">Main</a>
</form>
@endsection
|
Fix some confusion of creating folders
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
Set a flag when config is loaded on a browser
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 0) return ".";
};
window.process._RJS_isBrowser = true;
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1
});
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 0) return ".";
};
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1
});
|
Handle case of generating ID with no speakers
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
|
Change presence clientId to _cookieId in client object
|
const program = require('commander');
program
.version('1.0.0')
.option('-p, --port <port>', 'specify the websocket port to listen to [9870]', 9870)
.parse(process.argv);
const io = require('socket.io'),
winston = require('winston');
winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = program.port;
winston.info('Unichat presence service');
winston.info('Listening on port ' + PORT);
const socket = io.listen(PORT);
const ROOMID = 'room1';
socket.on('connection', (client) => {
winston.debug('New connection from client ' + client.id);
client.on('client-get-partner', (clientId) => {
client._cookieId = clientId;
winston.debug('Client ' + client.id + ' is actually Unichat user ' + client._cookieId + ' and wants partner.');
client.emit('server-join-room', ROOMID);
winston.debug('Sending client ' + client.id + ' to room ' + ROOMID);
});
client.on('disconnect', () => {
winston.debug('Client ' + client.id + ' disconnected');
});
});
|
const program = require('commander');
program
.version('1.0.0')
.option('-p, --port <port>', 'specify the websocket port to listen to [9870]', 9870)
.parse(process.argv);
const io = require('socket.io'),
winston = require('winston');
winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = program.port;
winston.info('Unichat presence service');
winston.info('Listening on port ' + PORT);
const socket = io.listen(PORT);
const ROOMID = 'room1';
socket.on('connection', (client) => {
winston.debug('New connection from client ' + client.id);
this.clientId = '';
client.on('client-get-partner', (clientId) => {
this.clientId = clientId;
winston.debug('Client ' + client.id + ' is actually Unichat user ' + this.clientId + ' and wants partner.');
client.emit('server-join-room', ROOMID);
winston.debug('Sending client ' + client.id + ' to room ' + ROOMID);
});
client.on('disconnect', () => {
winston.debug('Client ' + client.id + ' disconnected');
});
});
|
Switch to PropTypes because Hyper's React got rid of it
|
import React from 'react'
import PropTypes from 'prop-types'
import Component from 'hyper/component'
import SvgIcon from '../../utils/svg-icon'
export default class Draining extends Component {
static propTypes() {
return {
percentage: PropTypes.number
}
}
calculateChargePoint(percent) {
const base = 3.5,
val = Math.round((100 - percent) / 4.5),
point = base + (val / 2)
return val > 0 ? `M5,3 L11,3 L11,${point} L5,${point} L5,3 Z` : ''
}
styles() {
return {
'cpu-discharging-icon': {
fill: '#fff'
}
}
}
template(css) {
const chargePoint = this.calculateChargePoint(this.props.percentage)
return (
<SvgIcon>
<g fillRule="evenodd">
<g className={css('cpu-discharging-icon')}>
<path d={`M7,1 L9,1 L9,2 L7,2 L7,1 Z M4,2 L12,2 L12,15 L4,15 L4,2 Z ${chargePoint}`}></path>
</g>
</g>
</SvgIcon>
)
}
}
|
import React, {PropTypes} from 'react'
import Component from 'hyper/component'
import SvgIcon from '../../utils/svg-icon'
export default class Draining extends Component {
static propTypes() {
return {
percentage: PropTypes.number
}
}
calculateChargePoint(percent) {
const base = 3.5,
val = Math.round((100 - percent) / 4.5),
point = base + (val / 2)
return val > 0 ? `M5,3 L11,3 L11,${point} L5,${point} L5,3 Z` : ''
}
styles() {
return {
'cpu-discharging-icon': {
fill: '#fff'
}
}
}
template(css) {
const chargePoint = this.calculateChargePoint(this.props.percentage)
return (
<SvgIcon>
<g fillRule="evenodd">
<g className={css('cpu-discharging-icon')}>
<path d={`M7,1 L9,1 L9,2 L7,2 L7,1 Z M4,2 L12,2 L12,15 L4,15 L4,2 Z ${chargePoint}`}></path>
</g>
</g>
</SvgIcon>
)
}
}
|
Add raw line data to output
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a csv file with the following columns:'
print ' cartodb_id, date_time, day_of_year, distance_from_nest_in_meters'
sys.exit(-1)
def main():
dvis = DataVisualizing.TrackingVisualizer(infile=sys.argv[1])
print ('var day_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', agg_function='max')))
print ('var hour_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', subdomain='hour', agg_function='max')))
print ('var hour_month_linedata = [ {{ \'key\': \'Maximum distance\', \'color\': \'green\', \'values\': {0} }} ];'.format(dvis.as_raw_line_json(agg_function='max')))
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)) + '/src')
import DataVisualizing
if len(sys.argv) != 2:
print 'usage: create_heatmap.py <data file>'
print ' expected infile is a datafile containing tracking data'
print ' this is a csv file with the following columns:'
print ' cartodb_id, date_time, day_of_year, distance_from_nest_in_meters'
sys.exit(-1)
def main():
dvis = DataVisualizing.TrackingVisualizer(infile=sys.argv[1])
print ('var day_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', agg_function='max')))
print ('var hour_month_heatdata = {0};'.format(dvis.as_heatmap_json(domain='month', subdomain='hour', agg_function='max')))
main()
|
Change "error" to "error_code" in error object
|
var logger = require('log4js').getLogger('APP_LOG');
var request = require('request');
function sendMessage(config, receiver, message, botname, callback) {
var chat_id = config.receivers[receiver].chat_id;
var token = config.bots[botname].token;
request.post({
url: 'https://api.telegram.org/bot' + token + '/sendMessage',
form: {
chat_id: chat_id,
text: message
}
},
function(err, res, body) {
body = JSON.parse(body);
if (err) {
logger.error(err);
callback(err, null);
return;
}
if (body['error_code']) {
logger.error(body['description']);
err = {
error_code: body['error_code'],
description: body['description']
};
callback(err, null);
return;
}
logger.info('Message sent!');
var successMessage = {
receiver: receiver,
botname: botname,
message: message,
sendTime: new Date()
};
callback(null, successMessage);
});
}
module.exports = {
'sendMessage': sendMessage
};
|
var logger = require('log4js').getLogger('APP_LOG');
var request = require('request');
function sendMessage(config, receiver, message, botname, callback) {
var chat_id = config.receivers[receiver].chat_id;
var token = config.bots[botname].token;
request.post({
url: 'https://api.telegram.org/bot' + token + '/sendMessage',
form: {
chat_id: chat_id,
text: message
}
},
function(err, res, body) {
body = JSON.parse(body);
if (err) {
logger.error(err);
callback(err, null);
return;
}
if (body['error_code']) {
logger.error(body['description']);
err = {
error: body['error_code'],
description: body['description']
};
callback(err, null);
return;
}
logger.info('Message sent!');
var successMessage = {
receiver: receiver,
botname: botname,
message: message,
sendTime: new Date()
};
callback(null, successMessage);
});
}
module.exports = {
'sendMessage': sendMessage
};
|
[previews] Fix more FAKE syntax errors
|
import React, {PropTypes} from 'react'
import PreviewComponentCard from 'part:@sanity/components/previews/card'
import PreviewComponentDefault from 'part:@sanity/components/previews/default'
import PreviewComponentDetail from 'part:@sanity/components/previews/detail'
import PreviewComponentInline from 'part:@sanity/components/previews/inline'
import PreviewComponentMedia from 'part:@sanity/components/previews/media'
import PreviewComponentBlock from 'part:@sanity/components/previews/block'
import PreviewMaterializer from './PreviewMaterializer'
const previewComponentMap = {
default: PreviewComponentDefault,
card: PreviewComponentCard,
media: PreviewComponentMedia,
detail: PreviewComponentDetail,
inline: PreviewComponentInline,
block: PreviewComponentBlock
}
export default class SanityPreview extends React.PureComponent {
static propTypes = {
layout: PropTypes.oneOf(Object.keys(previewComponentMap)),
value: PropTypes.object,
type: PropTypes.object.isRequired
};
render() {
const {layout, value, type} = this.props
const PreviewComponent = previewComponentMap.hasOwnProperty(layout)
? previewComponentMap[layout]
: previewComponentMap.default
return (
<PreviewMaterializer type={type} value={value}>
{({materialized, isDeferred, isLoading, error}) => {
return <PreviewComponent item={materialized} placeholder={isDeferred} />
}}
</PreviewMaterializer>
)
}
}
|
import React, {PropTypes} from 'react'
import PreviewComponentCard from 'part:@sanity/components/previews/card'
import PreviewComponentDefault from 'part:@sanity/components/previews/default'
import PreviewComponentDetail from 'part:@sanity/components/previews/detail'
import PreviewComponentInline from 'part:@sanity/components/previews/inline'
import PreviewComponentMedia from 'part:@sanity/components/previews/media'
import PreviewComponentBlock from 'part:@sanity/components/previews/block'
import PreviewMaterializer from './PreviewMaterializer'
const previewComponentMap = {
default: PreviewComponentDefault,
card: PreviewComponentCard,
media: PreviewComponentMedia,
detail: PreviewComponentDetail,
inline: PreviewComponentInline,
block: PreviewComponentBlock
}
export default class SanityPreview extends React.PureComponent {
static propTypes = {
layout: PropTypes.oneOf(Object.keys(previewComponentMap)),
value: PropTypes.object,
type: PropTypes.object.isRequired
};
render() {
const {layout, value, type} = this.props
const PreviewComponent = previewComponentMap.hasOwnProperty(layout)
? previewComponentMap[layout]
: previewComponentMap.default
return (
<PreviewMaterializer type={type} value={value}>
{({materialized, isDeferred, isLoading, error}) => {
return <PreviewComponent item={materialized} placeholder={isDeferred} />
})
</PreviewMaterializer>
)
}
}
|
Use this instead of local variable
|
/*
* Application logic
*/
var Logic = {
parser: PEG.buildParser(" \
start = logic* \
logic = q:query a:action ' '* { return {query:q, action:a} } \
query = q:[^{]+ { return Query.compile(q.join('').trim()) } \
action = block:curly { return eval('(function()' + block + ')') } \
curly = curly:('{' ([^{}]+ / curly)+ '}') { return curly.flatten().join('') } \
"),
compile: function(logics) {
return this.parser.parse(logics).map(function(logic) {
logic.apply = function() {
var entities = World.queryRaw(this.query);
for (var i = 0; i < entities.length; i++)
this.action.call(entities[i]);
}
return logic;
});
},
store: [],
add: function(logics) {
this.store = this.store.concat(this.compile(logics));
},
runAll: function() {
for (var i = 0; i < this.store.length; i++) {
this.store[i].apply();
};
}
}
var scripts = document.querySelectorAll("script[type='text/logic']");
for (var i = 0; i < scripts.length; i++) {
Logic.add( scripts[i].text.trim() )
};
window.onload = function() {
Logic.runAll();
setInterval(function(){Logic.runAll()}, 3);
}
|
/*
* Application logic
*/
var Logic = {
parser: PEG.buildParser(" \
start = logic* \
logic = q:query a:action ' '* { return {query:q, action:a} } \
query = q:[^{]+ { return Query.compile(q.join('').trim()) } \
action = block:curly { return eval('(function()' + block + ')') } \
curly = curly:('{' ([^{}]+ / curly)+ '}') { return curly.flatten().join('') } \
"),
compile: function(logics) {
return this.parser.parse(logics).map(function(logic) {
logic.apply = function() {
var entities = World.queryRaw(logic.query);
for (var i = 0; i < entities.length; i++)
this.action.call(entities[i]);
}
return logic;
});
},
store: [],
add: function(logics) {
this.store = this.store.concat(this.compile(logics));
},
runAll: function() {
for (var i = 0; i < this.store.length; i++) {
this.store[i].apply();
};
}
}
var scripts = document.querySelectorAll("script[type='text/logic']");
for (var i = 0; i < scripts.length; i++) {
Logic.add( scripts[i].text.trim() )
};
window.onload = function() {
Logic.runAll();
setInterval(function(){Logic.runAll()}, 3);
}
|
Add "test" disposition to doc
|
<?php
declare(strict_types=1);
namespace MaxMind\MinFraud\Model;
/**
* Model with the disposition set by custom rules.
*
* In order to receive a disposition, you must be using minFraud custom rules.
*
* @property-read string|null $action The action to take on the transaction as
* defined by your custom rules. The current set of values are "accept",
* "manual_review", "reject", and "test". If you do not have custom rules set
* up, `null` will be returned.
* @property-read string|null $reason The reason for the action. The current
* possible values are "custom_rule", "block_list", and "default". If you do
* not have custom rules set up, `null` will be returned.
*/
class Disposition extends AbstractModel
{
/**
* @internal
*
* @var string|null
*/
protected $action;
/**
* @internal
*
* @var string|null
*/
protected $reason;
public function __construct(?array $response, array $locales = ['en'])
{
parent::__construct($response, $locales);
$this->action = $this->safeArrayLookup($response['action']);
$this->reason = $this->safeArrayLookup($response['reason']);
}
}
|
<?php
declare(strict_types=1);
namespace MaxMind\MinFraud\Model;
/**
* Model with the disposition set by custom rules.
*
* In order to receive a disposition, you must be using minFraud custom rules.
*
* @property-read string|null $action The action to take on the transaction as
* defined by your custom rules. The current set of values are "accept",
* "manual_review", and "reject". If you do not have custom rules set up,
* `null` will be returned.
* @property-read string|null $reason The reason for the action. The current
* possible values are "custom_rule", "block_list", and "default". If you do
* not have custom rules set up, `null` will be returned.
*/
class Disposition extends AbstractModel
{
/**
* @internal
*
* @var string|null
*/
protected $action;
/**
* @internal
*
* @var string|null
*/
protected $reason;
public function __construct(?array $response, array $locales = ['en'])
{
parent::__construct($response, $locales);
$this->action = $this->safeArrayLookup($response['action']);
$this->reason = $this->safeArrayLookup($response['reason']);
}
}
|
Fix error causing PhantomJS to eat RAM
|
// 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 any plugin's vendor/assets/javascripts directory 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/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui/sortable
//= require jquery-ui/selectable
//= require jquery-ui/slider
//= require jquery-ui/datepicker
//= require jqueryui-timepicker-addon
// Required by Blacklight
//= require blacklight/blacklight
//= require browse_everything
//= require nestedSortable/jquery.mjs.nestedSortable
//= require bootstrap-select
//= require openseadragon
// = require curation_concerns/application
//= require_tree .
//= require modernizr
//= require jquery.iiifOsdViewer
Blacklight.onLoad(function() {
Initializer = require('plum_boot')
window.plum = new Initializer()
})
|
// 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 any plugin's vendor/assets/javascripts directory 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/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require babel-polyfill
//= require jquery
//= require jquery_ujs
//= require jquery-ui/sortable
//= require jquery-ui/selectable
//= require jquery-ui/slider
//= require jquery-ui/datepicker
//= require jqueryui-timepicker-addon
// Required by Blacklight
//= require blacklight/blacklight
//= require browse_everything
//= require nestedSortable/jquery.mjs.nestedSortable
//= require bootstrap-select
//= require openseadragon
// = require curation_concerns/application
//= require_tree .
//= require modernizr
//= require jquery.iiifOsdViewer
Blacklight.onLoad(function() {
Initializer = require('plum_boot')
window.plum = new Initializer()
})
|
Return the EntityData on entity undo
|
package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparable<UndoList> {
public void commit();
public void undo();
public void undo(boolean undoEntityChanges);
public void setScheduleUndo(int ttl);
public int getScheduledUndo();
public boolean bypass();
public long getCreatedTime();
public long getModifiedTime();
public long getScheduledTime();
public boolean isScheduled();
public void prune();
public void add(Entity entity);
public void remove(Entity entity);
public EntityData modify(Entity entity);
public void add(Runnable runnable);
public void convert(Entity entity, Block block);
public void fall(Entity entity, Block block);
public void explode(Entity entity, List<Block> explodedBlocks);
public void cancelExplosion(Entity entity);
public boolean contains(Location location, int threshold);
public String getName();
public Mage getOwner();
}
|
package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparable<UndoList> {
public void commit();
public void undo();
public void undo(boolean undoEntityChanges);
public void setScheduleUndo(int ttl);
public int getScheduledUndo();
public boolean bypass();
public long getCreatedTime();
public long getModifiedTime();
public long getScheduledTime();
public boolean isScheduled();
public void prune();
public void add(Entity entity);
public void remove(Entity entity);
public void modify(Entity entity);
public void add(Runnable runnable);
public void convert(Entity entity, Block block);
public void fall(Entity entity, Block block);
public void explode(Entity entity, List<Block> explodedBlocks);
public void cancelExplosion(Entity entity);
public boolean contains(Location location, int threshold);
public String getName();
public Mage getOwner();
}
|
Fix test failing in macOS due to short GIdleThread timeout
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
|
import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.02 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result = t.wait(0.02)
yield wait_result
# Teardown GIdle Thread
t.interrupt()
@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True)
def test_wait_with_timeout(gidle_counter):
# GIVEN a long coroutine thread
# WHEN waiting short timeout
# THEN timeout is True
assert gidle_counter
@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True)
def test_wait_until_finished(gidle_counter):
# GIVEN a short coroutine thread
# WHEN wait for coroutine to finish
# THEN coroutine finished
assert not gidle_counter
|
import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.01 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result = t.wait(0.01)
yield wait_result
# Teardown GIdle Thread
t.interrupt()
@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True)
def test_wait_with_timeout(gidle_counter):
# GIVEN a long coroutine thread
# WHEN waiting short timeout
# THEN timeout is True
assert gidle_counter
@pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True)
def test_wait_until_finished(gidle_counter):
# GIVEN a short coroutine thread
# WHEN wait for coroutine to finish
# THEN coroutine finished
assert not gidle_counter
|
Remove unneccessary Customer Dashboard navbar link
|
import React from 'react';
import { Link } from 'react-router';
import { Menu, Segment } from 'semantic-ui-react';
import DynamicLinks from './DynamicLinks';
const Navbar = ({ id, location, logout }) =>
<Segment inverted>
<Menu inverted borderless>
<Menu.Item
as={Link}
to="landing"
className="logo"
>
<img alt="raptor" src="/client/src/assets/half-raptor.png" />
</Menu.Item>
<Menu.Item as={Link} to="/about" color="green" name="About Us" active={location === '/about'} />
<Menu.Item as={Link} to="/listings" name="Listings" color="green" active={location === '/listings'} />
<Menu.Item as={Link} to="/addlisting" color="green" name="addlisting" active={location === '/addlisting'} />
<DynamicLinks location={location} id={id} logout={logout} />
</Menu>
</Segment>;
export default Navbar;
Navbar.propTypes = {
location: React.PropTypes.string.isRequired,
};
|
import React from 'react';
import { Link } from 'react-router';
import { Menu, Segment } from 'semantic-ui-react';
import DynamicLinks from './DynamicLinks';
const Navbar = ({ id, location, logout }) =>
<Segment inverted>
<Menu inverted borderless>
<Menu.Item
as={Link}
to="landing"
className="logo"
>
<img alt="raptor" src="/client/src/assets/half-raptor.png" />
</Menu.Item>
<Menu.Item as={Link} to="/about" color="green" name="About" active={location === '/about'} />
<Menu.Item as={Link} to="/listings" name="Listings" color="green" active={location === '/listings'} />
<Menu.Item as={Link} to="/dashboard" color="green" name="customer dashboard" active={location === '/dashboard'} />
<Menu.Item as={Link} to="/addlisting" color="green" name="addlisting" active={location === '/addlisting'} />
<DynamicLinks location={location} id={id} logout={logout} />
</Menu>
</Segment>;
export default Navbar;
Navbar.propTypes = {
location: React.PropTypes.string.isRequired,
};
|
[desk-tool] Remove Ink on Pane items
|
import styles from './styles/PaneItem.css'
import listStyles from './styles/ListView.css'
import PropTypes from 'prop-types'
import React from 'react'
// import Ink from 'react-ink'
import {StateLink} from 'part:@sanity/base/router'
import {Item as GridListItem} from 'part:@sanity/components/lists/grid'
export default function PaneItemWrapper(props) {
const {useGrid, linkState, layout, isSelected} = props
const link = (
<StateLink state={linkState} className={isSelected ? styles.linkIsSelected : styles.link}>
{props.children}
{/* <Ink duration={1000} opacity={0.1} radius={200} /> */}
</StateLink>
)
return useGrid ? (
<GridListItem className={listStyles[`${layout}ListItem`]}>{link}</GridListItem>
) : (
<div className={isSelected ? styles.selected : styles.item}>{link}</div>
)
}
PaneItemWrapper.propTypes = {
layout: PropTypes.string,
useGrid: PropTypes.bool,
isSelected: PropTypes.bool,
linkState: PropTypes.object,
children: PropTypes.node
}
|
import styles from './styles/PaneItem.css'
import listStyles from './styles/ListView.css'
import PropTypes from 'prop-types'
import React from 'react'
import Ink from 'react-ink'
import {StateLink} from 'part:@sanity/base/router'
import {Item as GridListItem} from 'part:@sanity/components/lists/grid'
export default function PaneItemWrapper(props) {
const {useGrid, linkState, layout, isSelected} = props
const link = (
<StateLink state={linkState} className={isSelected ? styles.linkIsSelected : styles.link}>
{props.children}
<Ink duration={1000} opacity={0.1} radius={200} />
</StateLink>
)
return useGrid ? (
<GridListItem className={listStyles[`${layout}ListItem`]}>{link}</GridListItem>
) : (
<div className={isSelected ? styles.selected : styles.item}>{link}</div>
)
}
PaneItemWrapper.propTypes = {
layout: PropTypes.string,
useGrid: PropTypes.bool,
isSelected: PropTypes.bool,
linkState: PropTypes.object,
children: PropTypes.node
}
|
Use `-w` flag to display password directly
Fixes #2.
|
'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-wa', ssid];
execFile(cmd, args, function (err, stdout) {
stdout = stdout.trim();
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
}
if (err) {
cb(err);
return;
}
if (!stdout) {
cb(new Error('Could not get password'));
return;
}
cb(null, stdout);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'darwin') {
throw new Error('Only OS X systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
|
'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'security';
var args = ['find-generic-password', '-D', 'AirPort network password', '-ga', ssid];
var ret;
execFile(cmd, args, function (err, stdout, stderr) {
if (err && /The specified item could not be found in the keychain/.test(err.message)) {
err.message = 'Your network doesn\'t have a password';
}
if (err) {
cb(err);
return;
}
ret = /^\s*password: "(.+)"\s*$/gm.exec(stderr);
ret = ret && ret.length ? ret[1] : null;
if (!ret) {
cb(new Error('Could not get password'));
return;
}
cb(null, ret);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'darwin') {
throw new Error('Only OS X systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
|
Check for active session before bootstrapping
|
//make sure all dependencies are loaded
require([
'es5shim',
'angular',
'json!data/config.json',
'angular-ui-router',
'angular-flash',
'angular-moment',
'angular-sanitize',
'emoji',
'socketio',
'socket',
'jquery',
'jquery-filedrop',
'app',
'services/services',
'controllers/controllers',
'filters/filters',
'directives/directives',
'config/flash',
'config/http',
'config/routes',
'config/finalize',
'config/socket'
], function (es5shim, angular, config) {
'use strict';
console.log('Dependencies loaded');
//kick off!
angular.element(document).ready(function () {
console.log('Document ready, bootstrapping app');
// Get user state before bootstrap so we can route correctly
var $http = angular.bootstrap().get('$http');
$http.get("/api/users/session").success(function(user) {
sessionStorage.setItem("user", user.id);
angular.bootstrap(document, [config.appName]);
}).error(function(data, status, headers, config) {
console.log('Error accessing api');
});
});
});
|
//make sure all dependencies are loaded
require([
'es5shim',
'angular',
'json!data/config.json',
'angular-ui-router',
'angular-flash',
'angular-moment',
'angular-sanitize',
'emoji',
'socketio',
'socket',
'jquery',
'jquery-filedrop',
'app',
'services/services',
'controllers/controllers',
'filters/filters',
'directives/directives',
'config/flash',
'config/http',
'config/routes',
'config/finalize',
'config/socket'
], function (es5shim, angular, config) {
'use strict';
console.log('Dependencies loaded');
//kick off!
angular.element(document).ready(function () {
console.log('Document ready, bootstrapping app');
angular.bootstrap(document, [config.appName]);
});
});
|
Add author to post transformer
|
<?php namespace Autumn\Tools\Transformers;
use RainLab\Blog\Models\Post;
use League\Fractal\TransformerAbstract;
class BlogPostTransformer extends TransformerAbstract
{
protected $defaultIncludes = [
'featured_images',
];
public function transform(Post $post)
{
return [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'excerpt' => $post->excerpt,
'content' => $post->content,
'published' => $post->published,
'published_at' => $post->published_at->toDateTimeString(),
'categories' => $post->categories()->get(['id', 'name', 'slug']),
'author' => $post->user()->get(['id', 'first_name', 'last_name', 'login', 'email'])
];
}
public function includeFeaturedImages(Post $post)
{
return $this->collection($post->featured_images, new SystemFileTransformer);
}
}
|
<?php namespace Autumn\Tools\Transformers;
use RainLab\Blog\Models\Post;
use League\Fractal\TransformerAbstract;
class BlogPostTransformer extends TransformerAbstract
{
protected $defaultIncludes = [
'featured_images',
];
public function transform(Post $post)
{
return [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'excerpt' => $post->excerpt,
'content' => $post->content,
'published' => $post->published,
'published_at' => $post->published_at,
'categories' => $post->categories
];
}
public function includeFeaturedImages(Post $post)
{
$images = $post->featured_images;
return $this->collection($images, new SystemFileTransformer);
}
}
|
Use interface as return type
|
<?php
declare(strict_types=1);
namespace phpDocumentor\Reflection\Php;
use phpDocumentor\Reflection\Exception;
use phpDocumentor\Reflection\Metadata\MetaDataContainer as MetaDataContainerInterface;
trait MetadataContainerTest
{
/**
* @covers ::addMetadata
* @covers ::getMetadata
*/
public function testSetMetaDataForNonExistingKey(): void
{
$stub = new MetadataStub('stub');
$this->getFixture()->addMetadata($stub);
self::assertSame(['stub' => $stub], $this->getFixture()->getMetadata());
}
/**
* @covers ::addMetadata
*/
public function testSetMetaDataWithExistingKeyThrows(): void
{
self::expectException(Exception::class);
$stub = new MetadataStub('stub');
$this->getFixture()->addMetadata($stub);
$this->getFixture()->addMetadata($stub);
}
abstract public function getFixture(): MetaDataContainerInterface;
}
|
<?php
declare(strict_types=1);
namespace phpDocumentor\Reflection\Php;
use phpDocumentor\Reflection\Exception;
trait MetadataContainerTest
{
/**
* @covers ::addMetadata
* @covers ::getMetadata
*/
public function testSetMetaDataForNonExistingKey(): void
{
$stub = new MetadataStub('stub');
$this->getFixture()->addMetadata($stub);
self::assertSame(['stub' => $stub], $this->getFixture()->getMetadata());
}
/**
* @covers ::addMetadata
*/
public function testSetMetaDataWithExistingKeyThrows(): void
{
self::expectException(Exception::class);
$stub = new MetadataStub('stub');
$this->getFixture()->addMetadata($stub);
$this->getFixture()->addMetadata($stub);
}
abstract public function getFixture(): MetadataContainer;
}
|
Fix parseNumber in case of 3 numbers after decimal dot
|
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = parseNumber;
}
var numberRegexp = new RegExp('^(?:((?:\\d{1,3}(?:\\.\\d{3})+|\\d+)(,\\d{1,})?)|((?:\\d{1,3}(?:,\\d{3})+|\\d+)(\\.\\d{1,})?))$');
var dotRegexp = /\./g;
var commaRegexp = /,/g;
/**
* Create float number from number, given by string with decimal comma/dot
* @param {string} number
* @return {float|null}
*/
function parseNumber(number) {
if (typeof number === 'undefined' || number === null) return null;
if (typeof number.amount !== 'undefined') {
number = number.amount;
}
number = number.toString();
var match = number.match(numberRegexp);
if (!match) return null;
var isDecimalComma =
typeof match[2] !== 'undefined' ||
(typeof match[3] !== 'undefined' && typeof match[4] === 'undefined');
number = isDecimalComma ?
number.replace(dotRegexp, '').replace(',', '.') :
number.replace(commaRegexp, '');
return parseFloat(number);
}
|
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = parseNumber;
}
var numberRegexp = new RegExp('^(?:((?:\\d{1,3}(?:\\.\\d{3})+|\\d+)(?:,\\d{1,})?)|((?:\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.\\d{1,})?))$');
var dotRegexp = /\./g;
var commaRegexp = /,/g;
/**
* Create float number from number, given by string with decimal comma/dot
* @param {string} number
* @return {float|null}
*/
function parseNumber(number) {
if (typeof number === 'undefined' || number === null) return null;
if (typeof number.amount !== 'undefined') {
number = number.amount;
}
number = number.toString();
var match = number.match(numberRegexp);
if (!match) return null;
var isDecimalComma = typeof match[1] !== 'undefined';
number = isDecimalComma ?
number.replace(dotRegexp, '').replace(',', '.') :
number.replace(commaRegexp, '');
return parseFloat(number);
}
|
Test setting @Transactional on findById repository method.
|
/*
*
* 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.ohdsi.webapi.cohortdefinition;
import java.io.Serializable;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
/**
*
* @author cknoll1
*/
public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> {
Page<CohortDefinition> findAll(Pageable pageable);
// Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER,
// but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve)
@EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD)
@Transactional
CohortDefinition findById(Integer id);
}
|
/*
*
* 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.ohdsi.webapi.cohortdefinition;
import java.io.Serializable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
/**
*
* @author cknoll1
*/
public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> {
Page<CohortDefinition> findAll(Pageable pageable);
// Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER,
// but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve)
@EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD)
CohortDefinition findById(Integer id);
}
|
Fix a problem with PESEL validation
|
# -*- coding: utf-8 -*-
from operator import mul
from openerp import models, fields, api, exceptions
class Volunteer(models.Model):
_inherit = 'res.users'
pesel = fields.Char(string=u"PESEL")
def __init__(self, pool, cr):
super(Volunteer, self).__init__(pool, cr)
self._add_permitted_fields(level='owner', fields={'pesel'})
@api.one
@api.constrains('pesel')
def _check_pesel(self):
if not self.pesel:
return
try:
digits = map(int, self.pesel)
except ValueError:
raise exceptions.ValidationError("Numer PESEL może składać się wyłącznie z cyfr!")
if len(digits) != 11:
raise exceptions.ValidationError("Numer PESEL musi składać się z 11 cyfr!")
weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
control_sum = -(sum(map(mul, digits[:-1], weights))) % 10
if control_sum != digits[-1]:
raise exceptions.ValidationError("Niepoprawny numer PESEL.")
|
# -*- coding: utf-8 -*-
from operator import mul
from openerp import models, fields, api, exceptions
class Volunteer(models.Model):
_inherit = 'res.users'
pesel = fields.Char(string=u"PESEL")
def __init__(self, pool, cr):
super(Volunteer, self).__init__(pool, cr)
self._add_permitted_fields(level='owner', fields={'pesel'})
@api.one
@api.constrains('pesel')
def _check_pesel(self):
if not self.pesel:
return
try:
digits = map(int, self.pesel)
except ValueError:
raise exceptions.ValidationError("Numer PESEL może składać się wyłącznie z cyfr!")
weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
control_sum = -(sum(map(mul, digits[:-1], weights))) % 10
if len(digits) != 11 or control_sum != digits[-1]:
raise exceptions.ValidationError("Niepoprawny numer PESEL.")
|
Refactor public_view_url check to be more pythonic
In addition to this I also removed the is_public variable because the new utils
function says the same thing so it is redundant.
|
from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in django settings in the
STRONGHOLD_PUBLIC_URLS dictionary
each url in STRONGHOLD_PUBLIC_URLS must be a valid regex
"""
def __init__(self, *args, **kwargs):
self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ())
def process_view(self, request, view_func, view_args, view_kwargs):
# if request is authenticated, dont process it
if request.user.is_authenticated():
return None
# if its a public view, don't process it
if utils.is_view_func_public(view_func):
return None
# if this view matches a whitelisted regex, don't process it
if any(view_url.match(request.path_info) for view_url in self.public_view_urls):
return None
return login_required(view_func)(request, *view_args, **view_kwargs)
|
from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in django settings in the
STRONGHOLD_PUBLIC_URLS dictionary
each url in STRONGHOLD_PUBLIC_URLS must be a valid regex
"""
def __init__(self, *args, **kwargs):
self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ())
def process_view(self, request, view_func, view_args, view_kwargs):
# if request is authenticated, dont process it
if request.user.is_authenticated():
return None
# if its a public view, don't process it
is_public = utils.is_view_func_public(view_func)
if is_public:
return None
# if this view matches a whitelisted regex, don't process it
for view_url in self.public_view_urls:
if view_url.match(request.path_info):
return None
return login_required(view_func)(request, *view_args, **view_kwargs)
|
Fix noisy processor propertycount output
|
package main.java.org.wikidata.analyzer.Processor;
import org.wikidata.wdtk.datamodel.interfaces.*;
/**
* This processor simply outputs status lines to the console.
*
* @author Addshore
*/
public class NoisyProcessor implements EntityDocumentProcessor {
private int itemCount = 0;
private int propertyCount = 0;
@Override
public void processItemDocument(ItemDocument item) {
this.itemCount++;
//Output a line ever 250,000 items
if (this.itemCount % 250000 == 0) {
System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
}
}
@Override
public void processPropertyDocument(PropertyDocument property) {
this.propertyCount++;
//Output a line ever 100 properties
if (this.propertyCount % 100 == 0) {
System.out.println("Processed " + this.propertyCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
}
}
}
|
package main.java.org.wikidata.analyzer.Processor;
import org.wikidata.wdtk.datamodel.interfaces.*;
/**
* This processor simply outputs status lines to the console.
*
* @author Addshore
*/
public class NoisyProcessor implements EntityDocumentProcessor {
private int itemCount = 0;
private int propertyCount = 0;
@Override
public void processItemDocument(ItemDocument item) {
this.itemCount++;
//Output a line ever 250,000 items
if (this.itemCount % 250000 == 0) {
System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
}
}
@Override
public void processPropertyDocument(PropertyDocument property) {
this.propertyCount++;
//Output a line ever 100 properties
if (this.propertyCount % 100 == 0) {
System.out.println("Processed " + this.itemCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
}
}
}
|
[chore] Define uglify (minify) grunt task
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client/lib/dest/libs.min.js': ['client/lib/angular.js', 'client/lib/angular-ui-router.js']
}
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
};
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
};
|
Make path assertions windows friendly
|
package utils
import (
"os"
"os/user"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNormalizingHomeDirectories(t *testing.T) {
t.Parallel()
usr, err := user.Current()
assert.NoError(t, err)
fp, err := NormalizeFilePath(filepath.Join(`~`, `.ssh`))
assert.NoError(t, err)
assert.Equal(t, filepath.Join(usr.HomeDir, `.ssh`), fp)
assert.True(t, filepath.IsAbs(fp))
}
func TestNormalizingFilePaths(t *testing.T) {
t.Parallel()
workingDir, err := os.Getwd()
assert.NoError(t, err)
fp, err := NormalizeFilePath(filepath.Join(`.`, `builds`))
assert.NoError(t, err)
assert.Equal(t, filepath.Join(workingDir,`builds`), fp)
assert.True(t, filepath.IsAbs(fp))
}
func TestNormalizingEmptyPaths(t *testing.T) {
t.Parallel()
fp, err := NormalizeFilePath("")
assert.NoError(t, err)
assert.Equal(t, "", fp)
}
|
package utils
import (
"os"
"os/user"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNormalizingHomeDirectories(t *testing.T) {
t.Parallel()
usr, err := user.Current()
assert.NoError(t, err)
fp, err := NormalizeFilePath(filepath.Join(`~`, `.ssh`))
assert.NoError(t, err)
assert.Equal(t, filepath.Join(usr.HomeDir, `.ssh`), fp)
assert.True(t, filepath.IsAbs(fp))
}
func TestNormalizingFilePaths(t *testing.T) {
t.Parallel()
workingDir, err := os.Getwd()
assert.NoError(t, err)
fp, err := NormalizeFilePath(filepath.Join(`.`, `builds`))
assert.NoError(t, err)
assert.Equal(t, workingDir+`/builds`, fp)
assert.True(t, filepath.IsAbs(fp))
}
func TestNormalizingEmptyPaths(t *testing.T) {
t.Parallel()
fp, err := NormalizeFilePath("")
assert.NoError(t, err)
assert.Equal(t, "", fp)
}
|
Remove deprecated lifecycle methods from ObserveModel
|
import React from 'react';
import PropTypes from 'prop-types';
import ModelObserver from '../models/model-observer';
export default class ObserveModel extends React.Component {
static propTypes = {
model: PropTypes.shape({
onDidUpdate: PropTypes.func.isRequired,
}),
fetchData: PropTypes.func.isRequired,
children: PropTypes.func.isRequired,
}
constructor(props, context) {
super(props, context);
this.state = {data: null};
this.modelObserver = new ModelObserver({fetchData: this.fetchData, didUpdate: this.didUpdate});
}
componentDidMount() {
this.mounted = true;
this.modelObserver.setActiveModel(this.props.model);
}
componentDidUpdate() {
this.modelObserver.setActiveModel(this.props.model);
}
fetchData = model => this.props.fetchData(model);
didUpdate = () => {
if (this.mounted) {
const data = this.modelObserver.getActiveModelData();
this.setState({data});
}
}
render() {
return this.props.children(this.state.data);
}
componentWillUnmount() {
this.mounted = false;
this.modelObserver.destroy();
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import ModelObserver from '../models/model-observer';
export default class ObserveModel extends React.Component {
static propTypes = {
model: PropTypes.shape({
onDidUpdate: PropTypes.func.isRequired,
}),
fetchData: PropTypes.func.isRequired,
children: PropTypes.func.isRequired,
}
constructor(props, context) {
super(props, context);
this.state = {data: null};
this.modelObserver = new ModelObserver({fetchData: this.fetchData, didUpdate: this.didUpdate});
}
componentWillMount() {
this.mounted = true;
this.modelObserver.setActiveModel(this.props.model);
}
componentWillReceiveProps(nextProps) {
this.modelObserver.setActiveModel(nextProps.model);
}
fetchData = model => this.props.fetchData(model);
didUpdate = () => {
if (this.mounted) {
const data = this.modelObserver.getActiveModelData();
this.setState({data});
}
}
render() {
return this.props.children(this.state.data);
}
componentWillUnmount() {
this.mounted = false;
this.modelObserver.destroy();
}
}
|
Use fasthttp client in avalanche.HTTPWriter
benchmark old ns/op new ns/op delta
BenchmarkHTTPSmallPoints1-4 97655 75615 -22.57%
BenchmarkHTTPSmallPoints2-4 111484 73023 -34.50%
BenchmarkHTTPSmallPoints4-4 107066 72719 -32.08%
BenchmarkHTTPSmallPoints8-4 97721 76665 -21.55%
BenchmarkHTTPSmallPoints16-4 85786 76575 -10.74%
BenchmarkHTTPSmallPoints32-4 93731 77108 -17.73%
BenchmarkHTTPSmallPoints64-4 95344 83935 -11.97%
BenchmarkHTTPSmallPoints128-4 103471 85348 -17.52%
BenchmarkHTTPSmallPoints256-4 117981 100875 -14.50%
BenchmarkHTTPSmallPoints512-4 128273 128810 +0.42%
BenchmarkHTTPSmallPoints1024-4 188951 185461 -1.85%
BenchmarkHTTPSmallPoints2048-4 280742 266309 -5.14%
BenchmarkHTTPSmallPoints4096-4 470528 426102 -9.44%
BenchmarkHTTPSmallPoints8192-4 774074 806194 +4.15%
BenchmarkHTTPSmallPoints16384-4 1441046 1509301 +4.74%
BenchmarkHTTPSmallPoints32768-4 3127086 2846811 -8.96%
BenchmarkHTTPSmallPoints65536-4 5725378 5842206 +2.04%
benchmark old MB/s new MB/s speedup
BenchmarkHTTPSmallPoints1-4 0.22 0.28 1.27x
BenchmarkHTTPSmallPoints2-4 0.38 0.58 1.53x
BenchmarkHTTPSmallPoints4-4 0.78 1.16 1.49x
BenchmarkHTTPSmallPoints8-4 1.72 2.19 1.27x
BenchmarkHTTPSmallPoints16-4 3.92 4.39 1.12x
BenchmarkHTTPSmallPoints32-4 7.17 8.71 1.21x
BenchmarkHTTPSmallPoints64-4 14.10 16.01 1.14x
BenchmarkHTTPSmallPoints128-4 25.98 31.49 1.21x
BenchmarkHTTPSmallPoints256-4 45.57 53.29 1.17x
BenchmarkHTTPSmallPoints512-4 83.82 83.47 1.00x
BenchmarkHTTPSmallPoints1024-4 113.81 115.95 1.02x
BenchmarkHTTPSmallPoints2048-4 153.19 161.50 1.05x
BenchmarkHTTPSmallPoints4096-4 182.81 201.87 1.10x
BenchmarkHTTPSmallPoints8192-4 222.24 213.39 0.96x
BenchmarkHTTPSmallPoints16384-4 238.76 227.96 0.95x
BenchmarkHTTPSmallPoints32768-4 220.05 241.72 1.10x
BenchmarkHTTPSmallPoints65536-4 240.38 235.57 0.98x
benchmark old allocs new allocs delta
BenchmarkHTTPSmallPoints1-4 42 1
-97.62%
BenchmarkHTTPSmallPoints2-4 41 1
-97.56%
BenchmarkHTTPSmallPoints4-4 41 1
-97.56%
BenchmarkHTTPSmallPoints8-4 41 1
-97.56%
BenchmarkHTTPSmallPoints16-4 42 1
-97.62%
BenchmarkHTTPSmallPoints32-4 42 1
-97.62%
BenchmarkHTTPSmallPoints64-4 42 1
-97.62%
BenchmarkHTTPSmallPoints128-4 42 1
-97.62%
BenchmarkHTTPSmallPoints256-4 42 1
-97.62%
BenchmarkHTTPSmallPoints512-4 42 1
-97.62%
BenchmarkHTTPSmallPoints1024-4 42 1
-97.62%
BenchmarkHTTPSmallPoints2048-4 41 1
-97.56%
BenchmarkHTTPSmallPoints4096-4 41 1
-97.56%
BenchmarkHTTPSmallPoints8192-4 42 1
-97.62%
BenchmarkHTTPSmallPoints16384-4 42 1
-97.62%
BenchmarkHTTPSmallPoints32768-4 42 1
-97.62%
BenchmarkHTTPSmallPoints65536-4 42 1
-97.62%
benchmark old bytes new bytes delta
BenchmarkHTTPSmallPoints1-4 2856 51 -98.21%
BenchmarkHTTPSmallPoints2-4 2855 51 -98.21%
BenchmarkHTTPSmallPoints4-4 2859 51 -98.22%
BenchmarkHTTPSmallPoints8-4 2855 51 -98.21%
BenchmarkHTTPSmallPoints16-4 2862 51 -98.22%
BenchmarkHTTPSmallPoints32-4 2861 51 -98.22%
BenchmarkHTTPSmallPoints64-4 2864 51 -98.22%
BenchmarkHTTPSmallPoints128-4 2865 51 -98.22%
BenchmarkHTTPSmallPoints256-4 2865 56 -98.05%
BenchmarkHTTPSmallPoints512-4 2873 58 -97.98%
BenchmarkHTTPSmallPoints1024-4 2877 61 -97.88%
BenchmarkHTTPSmallPoints2048-4 2913 87 -97.01%
BenchmarkHTTPSmallPoints4096-4 2959 158 -94.66%
BenchmarkHTTPSmallPoints8192-4 3039 345 -88.65%
BenchmarkHTTPSmallPoints16384-4 3414 1168 -65.79%
BenchmarkHTTPSmallPoints32768-4 5081 4378 -13.84%
BenchmarkHTTPSmallPoints65536-4 10053 14280 +42.05%
|
package avalanche
import (
"fmt"
"github.com/valyala/fasthttp"
)
type HTTPWriterConfig struct {
Host string
Generator Generator
}
type HTTPWriter struct {
client fasthttp.Client
c HTTPWriterConfig
url []byte
}
func NewHTTPWriter(c HTTPWriterConfig) Writer {
return &HTTPWriter{
client: fasthttp.Client{
Name: "avalanche",
},
c: c,
url: []byte(c.Host + "/write"),
}
}
var post = []byte("POST")
func (w *HTTPWriter) Write() error {
req := fasthttp.AcquireRequest()
req.Header.SetMethodBytes(post)
req.Header.SetRequestURIBytes(w.url)
req.SetBodyStream(w.c.Generator(), -1)
resp := fasthttp.AcquireResponse()
err := w.client.Do(req, resp)
if err == nil {
sc := resp.StatusCode()
if sc != fasthttp.StatusNoContent {
err = fmt.Errorf("Invalid write response (status %d): %s", sc, resp.Body())
}
}
fasthttp.ReleaseResponse(resp)
fasthttp.ReleaseRequest(req)
return err
}
|
package avalanche
import (
"fmt"
"io/ioutil"
"net/http"
)
type HTTPWriterConfig struct {
Host string
Generator Generator
}
type HTTPWriter struct {
c HTTPWriterConfig
}
func NewHTTPWriter(c HTTPWriterConfig) Writer {
return &HTTPWriter{c: c}
}
func (w *HTTPWriter) Write() error {
g := w.c.Generator()
resp, err := http.Post(w.c.Host+"/write", "", g)
if err != nil {
return err
}
// NoContent is the only acceptable status.
// OK responses can have errors, and non-200 is another class of error.
if resp.StatusCode != http.StatusNoContent {
// Already received invalid status code,
// don't care if something goes wrong reading the response body
b, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("Invalid write response (status %d): %s", resp.StatusCode, b)
}
return nil
}
|
Use Str::random() instead of str_random()
|
<?php
use Faker\Generator as Faker;
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
];
});
|
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10),
];
});
|
Add delete method to source data cache interface.
|
<?php
/*
* This file is part of the Tadcka package.
*
* (c) Tadas Gliaubicas <tadcka89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tadcka\Mapper\Cache;
use Tadcka\Mapper\Source\Data\SourceDataInterface;
/**
* @author Tadas Gliaubicas <tadcka89@gmail.com>
*
* @since 1/27/15 9:57 PM
*/
interface SourceDataCacheInterface
{
const SUB_DIR = 'data';
/**
* Delete mapper source data from cache.
*
* @param string $key
*
* @return bool
*/
public function delete($key);
/**
* Fetch mapper source data from cache.
*
* @param string $key
*
* @return null|SourceDataInterface
*/
public function fetch($key);
/**
* Save mapper source data to cache.
*
* @param string $key
* @param SourceDataInterface $data
* @param \DateTime $ttl
*/
public function save($key, SourceDataInterface $data, \DateTime $ttl);
}
|
<?php
/*
* This file is part of the Tadcka package.
*
* (c) Tadas Gliaubicas <tadcka89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tadcka\Mapper\Cache;
use Tadcka\Mapper\Source\Data\SourceDataInterface;
/**
* @author Tadas Gliaubicas <tadcka89@gmail.com>
*
* @since 1/27/15 9:57 PM
*/
interface SourceDataCacheInterface
{
const SUB_DIR = 'data';
/**
* Fetch mapper source data from cache.
*
* @param string $key
*
* @return null|SourceDataInterface
*/
public function fetch($key);
/**
* Save mapper source data to cache.
*
* @param string $key
* @param SourceDataInterface $data
* @param \DateTime $ttl
*/
public function save($key, SourceDataInterface $data, \DateTime $ttl);
}
|
Fix for handling HTTP requests properly
|
package com.manning.siia;
import siia.booking.domain.trip.LegQuoteCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import javax.xml.transform.Source;
public class TripQuoteRequestProcessor {
private Log logger = LogFactory.getLog(getClass());
public Source processTripRequest(Source requestSource) throws Exception{
logger.info("Trip request recevied");
StringResult res = new StringResult();
res.getWriter().append("<ok/>");
return new StringSource(res.toString());
}
public OkResponse processTripRequest(String requestSource) throws Exception{
logger.info("Trip request recevied");
return new OkResponse();
}
public OkResponse processTripRequest(LegQuoteCommand legQuoteCommand) throws Exception{
logger.info("Trip request received:" + legQuoteCommand);
return new OkResponse();
}
}
|
package com.manning.siia;
import siia.booking.domain.trip.LegQuoteCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import javax.xml.transform.Source;
public class TripQuoteRequestProcessor {
private Log logger = LogFactory.getLog(getClass());
public Source processTripRequest(Source requestSource) throws Exception{
logger.info("Trip request recevied");
StringResult res = new StringResult();
res.getWriter().append("<ok/>");
return new StringSource(res.toString());
}
public OkResponse processTripRequest(LegQuoteCommand legQuoteCommand) throws Exception{
logger.info("Trip request received:" + legQuoteCommand);
StringResult res = new StringResult();
return new OkResponse();
}
}
|
Make a unit test compatible with php 7.0
|
<?php
/**
* @param ?array $a
* @param array{key:?string} $a2
* @param string $offset
*/
function example471Isset($a, array $a2, string $offset) {
if (isset($a[$offset])) {
echo intdiv($a, 2); // Expect array (not null)
}
if (isset($a2['key'])) {
echo intdiv($a2, -2); // Expect array{key:string} (not null)
}
}
/**
* @param ?array $a
* @param array{key:?string} $a2
* @param array{key:?bool} $a3
* @param string $offset
*/
function example471NotEmpty($a, array $a2, array $a3, string $offset) {
if (!empty($a[$offset])) {
echo intdiv($a, 2);
}
if (!empty($a2['key'])) {
echo intdiv($a2, -2); // Expect array{key:string} (not falsey)
}
if (!empty($a3['key'])) {
echo intdiv($a3, -2); // Expect array{key:true} (not falsey)
}
}
|
<?php
/**
* @param ?array $a
* @param array{key:?string} $a2
* @param string $offset
*/
function example471Isset($a, array $a2, string $offset) {
if (isset($a[$offset])) {
echo intdiv($a, 2); // Expect array (not null)
}
if (isset($a2['key'])) {
echo intdiv($a2, -2); // Expect array{key:string} (not null)
}
}
/**
* @param ?array $a
* @param array{key:?string} $a2
* @param array{key:?bool} $a3
* @param string $offset
*/
function example471NotEmpty(?array $a, array $a2, array $a3, string $offset) {
if (!empty($a[$offset])) {
echo intdiv($a, 2);
}
if (!empty($a2['key'])) {
echo intdiv($a2, -2); // Expect array{key:string} (not falsey)
}
if (!empty($a3['key'])) {
echo intdiv($a3, -2); // Expect array{key:true} (not falsey)
}
}
|
Add size parameter to chooseTasks, in case we need it
|
var formatData = function(restaurants) {
var formattedData = [];
// for each restaurant element in restaurants
// {
// yelpId:
// name:
// rating:
// price:
// location: (might want to use display_address here - it's an array)
// address:
// zip_code:
// }
return formattedData;
};
var chooseTasks = function(restaurants, size) {
var tasks = [];
var numTasks = size || 3;
for (var i = 0; i < numTasks; i++) {
var random = Math.floor( Math.random() * numTasks );
tasks.push( restaurants[random] );
}
return tasks;
};
module.exports.formatData = formatData;
module.exports.chooseTasks = chooseTasks;
|
var formatData = function(restaurants) {
var formattedData = [];
// for each restaurant element in restaurants
// {
// yelpId:
// name:
// rating:
// price:
// location: (might want to use display_address here - it's an array)
// address:
// zip_code:
// }
return formattedData;
};
var chooseTasks = function(restaurants) {
var tasks = [];
const numTasks = 3;
for (var i = 0; i < numTasks; i++) {
var random = Math.floor( Math.random() * numTasks );
tasks.push( restaurants[random] );
}
return tasks;
};
module.exports.formatData = formatData;
module.exports.chooseTasks = chooseTasks;
|
Update url so it take care of filters and remove `t=id` not sure why it
was needed!
|
function showGenericRelatedObjectLookupPopup(triggeringLink, ctArray)
{
var realName = triggeringLink.id.replace(/^lookup_/, '');
var name = id_to_windowname(realName);
realName = realName.replace(/object_id/, 'content_type');
var select = document.getElementById(realName);
if (select.value === "") {
alert("Select a content type first.");
return false;
}
var selectedItem = select.item(select.selectedIndex).value;
var href = triggeringLink.href.replace(/(\?|\#).*/,'../../../'+ctArray[selectedItem]);
alert(href);
if (href.search(/\?/) >= 0) {
href = href + '&_popup=1';
} else {
href = href + '?_popup=1';
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
|
function showGenericRelatedObjectLookupPopup(triggeringLink, ctArray)
{
var realName = triggeringLink.id.replace(/^lookup_/, '');
var name = id_to_windowname(realName);
realName = realName.replace(/object_id/, 'content_type');
var select = document.getElementById(realName);
if (select.value === "") {
alert("Select a content type first.");
return false;
}
var selectedItem = select.item(select.selectedIndex).value;
var href = triggeringLink.href.replace(/#/,'../../../'+ctArray[selectedItem]+"/?t=id");
if (href.search(/\?/) >= 0) {
href = href + '&_popup=1';
} else {
href = href + '?_popup=1';
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
|
Fix example to use get
|
"""An example application using Confit for configuration."""
from __future__ import print_function
from __future__ import unicode_literals
import confit
import argparse
config = confit.LazyConfig('ConfitExample', __name__)
def main():
parser = argparse.ArgumentParser(description='example Confit program')
parser.add_argument('--library', '-l', dest='library', metavar='LIBPATH',
help='library database file')
parser.add_argument('--directory', '-d', dest='directory',
metavar='DIRECTORY',
help='destination music directory')
parser.add_argument('--verbose', '-v', dest='verbose', action='store_true',
help='print debugging messages')
args = parser.parse_args()
config.set_args(args)
print('configuration directory is', config.config_dir())
# Use a boolean flag and the transient overlay.
if config['verbose']:
print('verbose mode')
config['log']['level'] = 2
else:
config['log']['level'] = 0
print('logging level is', config['log']['level'].get(int))
# Some validated/converted values.
print('directory is', config['directory'].as_filename())
print('library is', config['library'].as_filename())
|
"""An example application using Confit for configuration."""
from __future__ import print_function
from __future__ import unicode_literals
import confit
import argparse
config = confit.LazyConfig('ConfitExample', __name__)
def main():
parser = argparse.ArgumentParser(description='example Confit program')
parser.add_argument('--library', '-l', dest='library', metavar='LIBPATH',
help='library database file')
parser.add_argument('--directory', '-d', dest='directory',
metavar='DIRECTORY',
help='destination music directory')
parser.add_argument('--verbose', '-v', dest='verbose', action='store_true',
help='print debugging messages')
args = parser.parse_args()
config.set_args(args)
print('configuration directory is', config.config_dir())
# Use a boolean flag and the transient overlay.
if config['verbose']:
print('verbose mode')
config['log']['level'] = 2
else:
config['log']['level'] = 0
print('logging level is', config['log']['level'].validate(int))
# Some validated/converted values.
print('directory is', config['directory'].as_filename())
print('library is', config['library'].as_filename())
|
Fix async logic in integration test runner
|
/**
* Run each test under ./integration, one at a time.
* Each one will likely need to pollute global namespace, and thus will need to be run in a forked process.
*/
var fs = require('fs');
var files = fs.readdirSync(fs.realpathSync('./test/integration'));
var shell = require('shelljs');
var pattern = /^(test)\w*\.js$/;
for (var i in files) {
if (files.hasOwnProperty(i)) {
pattern.lastIndex = 0;
if (pattern.test(files[i])) {
exports[files[i]] = function(file, assert, done) {
file = './test/integration/' + file;
console.log(file);
shell.exec('node ' + file, function(code, output) {
assert.equal(code, 0, "Integration run must exit with 0 status");
done();
});
}.bind(this, files[i])
}
}
}
|
/**
* Run each test under ./integration, one at a time.
* Each one will likely need to pollute global namespace, and thus will need to be run in a forked process.
*/
var fs = require('fs');
var files = fs.readdirSync(fs.realpathSync('./test/integration'));
var shell = require('shelljs');
var pattern = /^(test)\w*\.js$/;
for (var i in files) {
if (files.hasOwnProperty(i)) {
pattern.lastIndex = 0;
if (pattern.test(files[i])) {
exports[files[i]] = function(file, assert) {
file = './test/integration/' + file;
console.log(file);
shell.exec('node ' + file, function(code, output) {
console.log(output);
assert.equal(code, 0, "Integration run must exit with 0 status");
});
}.bind(this, files[i])
}
}
}
|
Update in output to terminal.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
|
# The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
pprint(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
|
# The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
print(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
|
Update the PyPI version to 7.0.13.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.13',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.12',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Remove chamadas desnecessárias da classe `App`
|
<?php
/**
* Alf CMS
*
* PHP 5
*
* Alf CMS
* Copyright 2013-2013, Tonight Systems, Inc. (https://github.com/tonightsystems)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package Alf
* @copyright Copyright 2013-2013, Tonight Systems, Inc.
* @link https://github.com/tonightsystems/alf-cms
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Define as constantes principais do sistema
*/
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__) . DS);
define('CORE', ROOT . DS . 'core' . DS);
define('THEMES', ROOT . DS . 'themes' . DS);
define('EXT', '.php');
require CORE . 'convenience' . EXT;
require CORE . 'config' . EXT;
// Carrega as configurações do usuário
require ROOT . 'config' . EXT;
require CORE . 'init' . EXT;
|
<?php
/**
* Alf CMS
*
* PHP 5
*
* Alf CMS
* Copyright 2013-2013, Tonight Systems, Inc. (https://github.com/tonightsystems)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package Alf
* @copyright Copyright 2013-2013, Tonight Systems, Inc.
* @link https://github.com/tonightsystems/alf-cms
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Define as constantes principais do sistema
*/
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__) . DS);
define('CORE', ROOT . DS . 'core' . DS);
define('THEMES', ROOT . DS . 'themes' . DS);
define('EXT', '.php');
require CORE . 'app' . EXT;
App::load(array(
'convenience',
'config',
));
// Carrega as configurações do usuário
App::load('config', ROOT);
// Carrega o sistema em si
require CORE . 'init' . EXT;
|
Remove unneeded grunt task (PR comment)
|
'use strict';
module.exports = function(grunt) {
var gtx = require('gruntfile-gtx').wrap(grunt);
gtx.loadAuto();
var gruntConfig = require('./grunt');
gruntConfig.package = require('./package.json');
gtx.config(gruntConfig);
gtx.alias('build', ['build-dist', 'less', 'copy']);
gtx.alias('build-dist', ['shell:buildDist']);
gtx.alias('docs', ['docs-build', 'concurrent:docs']);
gtx.alias('docs-build', ['shell:docsBuild']);
gtx.alias('docs-start', ['shell:docsStart']);
gtx.alias('docs-view', ['shell:docsView']);
gtx.alias('release-docs', ['build', 'docs-build', 'gh-pages']);
//gtx.alias('deploy', ['release-docs', 'release', 'aws_s3']);
gtx.alias('deploy', ['aws_s3']);
gtx.finalise();
};
|
'use strict';
module.exports = function(grunt) {
var gtx = require('gruntfile-gtx').wrap(grunt);
gtx.loadAuto();
var gruntConfig = require('./grunt');
gruntConfig.package = require('./package.json');
gtx.config(gruntConfig);
gtx.alias('build', ['build-dist', 'less', 'copy']);
gtx.alias('build-dist', ['shell:buildDist']);
gtx.alias('docs', ['docs-build', 'concurrent:docs']);
gtx.alias('docs-build', ['shell:docsBuild']);
gtx.alias('docs-start', ['shell:docsStart']);
gtx.alias('docs-view', ['shell:docsView']);
gtx.alias('upload', ['aws_s3']);
gtx.alias('release-docs', ['build', 'docs-build', 'gh-pages']);
//gtx.alias('deploy', ['release-docs', 'release', 'upload']);
gtx.alias('deploy', ['upload']);
gtx.finalise();
};
|
Select textarea contents on click
|
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('source').addEventListener('click', function() {
this.focus();
this.select();
});
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerText = quotedPrintable.decode(source);
});
});
}
|
document.addEventListener('DOMContentLoaded', function() {
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerText = quotedPrintable.decode(source);
});
});
}
|
Remove non-required column from test.
|
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | audit | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
)
|
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | | |
| | type | name | label | parameters |
| | audit | audit | | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
)
|
Update ptvsd version number for 2.2 beta.
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.2.0b1',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://aka.ms/ptvs',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.1.0',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://pytools.codeplex.com/',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
Change the class name on the arrival component container
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['timeline__event'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['arrival'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
|
Fix error noticed when running Phan under php 7.2.0alpha1
In php 7.2, `count()` can only be called on `array` or `Countable`.
It will emit a warning if it is called on other types, e.g. `null`,
`string`, etc.
|
<?php declare(strict_types=1);
namespace Phan\Language\Element;
use Phan\Language\FQSEN;
use Phan\Language\FQSEN\FullyQualifiedClassName;
/**
* This contains info for a single sub-node of a node of type \ast\AST_USE_TRAIT
* (Which aliases of methods exist for this trait, which `insteadof` exist, etc)
*/
class TraitAdaptations
{
/**
* @var FQSEN
*/
private $trait_fqsen;
/**
* @var TraitAliasSource[] maps alias methods from this trait
* to the info about the source method
*/
public $alias_methods = [];
/**
* @var bool[] Has an entry mapping name to true if a method with a given name is hidden.
*/
public $hidden_methods = [];
public function __construct(FQSEN $trait_fqsen)
{
$this->trait_fqsen = $trait_fqsen;
}
/**
* Gets the FQSEN
*
* @return FQSEN the trait's FQSEN
*/
public function getTraitFQSEN() : FQSEN
{
return $this->trait_fqsen;
}
}
|
<?php declare(strict_types=1);
namespace Phan\Language\Element;
use Phan\Language\FQSEN;
use Phan\Language\FQSEN\FullyQualifiedClassName;
/**
* This contains info for a single sub-node of a node of type \ast\AST_USE_TRAIT
* (Which aliases of methods exist for this trait, which `insteadof` exist, etc)
*/
class TraitAdaptations
{
/**
* @var FQSEN
*/
private $trait_fqsen;
/**
* @var TraitAliasSource[] maps alias methods from this trait
* to the info about the source method
*/
public $alias_methods;
/**
* @var bool[] Has an entry mapping name to true if a method with a given name is hidden.
*/
public $hidden_methods;
public function __construct(FQSEN $trait_fqsen)
{
$this->trait_fqsen = $trait_fqsen;
}
/**
* Gets the FQSEN
*
* @return FQSEN the trait's FQSEN
*/
public function getTraitFQSEN() : FQSEN
{
return $this->trait_fqsen;
}
}
|
Fix video view and remove some sub components
- Fixes #28
|
import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {compose, withProps} from 'recompose'
import {updateVideo} from '../../actions/videos'
import CommentList from '../CommentList'
import {withDatabaseSubscribe} from '../hocs'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withProps(({match}) => ({
videoId: match.params.videoId,
})),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.videoId}`),
(props) => (snapshot) => (
props.dispatch(updateVideo(
{
videoId: props.videoId,
videoSnapshot: snapshot.val()
}))
)
),
)
const styles = {
videoContainer: {
height: 'calc(100vh - 56px)',
display: 'flex',
flexWrap: 'wrap',
}
}
const VideoView = ({videos, videoId}) => (
<div style={styles.videoContainer}>
{JSON.stringify(_.get(videos, videoId, {}))}
<CommentList videoId={videoId}/>
</div>
)
export default enhance(VideoView)
|
import React from 'react'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { updateVideo } from '../../actions/videos'
import { withDatabaseSubscribe } from '../hocs'
import CommentList from '../CommentList'
import PerformanceFrame from '../PerformanceFrame'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.params.videoId}`),
(props) => (snapshot) => (
props.dispatch(updateVideo({
videoId: props.params.videoId,
videoSnapshot: snapshot.val()
}))
)
),
)
const styles = {
videoContainer: {
height: 'calc(100vh - 56px)',
display: 'flex',
flexWrap: 'wrap',
}
}
const VideoView = ({videos, params}) => (
<div style={styles.videoContainer}>
{(params.videoId in videos && videos[params.videoId] !== null) ?
<PerformanceFrame size={{width: 854, height: 480}} layout={{ videoStreams: [{videoId: params.videoId, z_index: 0, scale: 1.0}]}} /> :
<p>{"404 not found"}</p>
}
{videos[params.videoId] !== null ?
<CommentList videoId={params.videoId}/> :
<p>{"duh"}</p>
}
</div>
)
export default enhance(VideoView)
|
Set up a few items
|
package org.fountanio.juancode.out;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.Border;
import org.fountanio.juancode.eng.Engine;
import org.lwjgl.openal.AL;
import org.lwjgl.opengl.Display;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
public class IPWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JButton gotoip = new JButton("Go");
private JButton gotoipf = new JButton("Go");
private Border topborder = BorderFactory.createTitledBorder("Connect");
private Border bottomborder = BorderFactory.createTitledBorder("Friends");
private JTextField ipinput = new JTextField();
private JList<String> friendlist = new JList();
public IPWindow() {
super("Speed Civilization");
setSize(400, 340);
setLayout(new BorderLayout());
ipinput.setBorder(topborder);
gotoip.setBorder(topborder);
gotoipf.setBorder(bottomborder);
friendlist.setBorder(bottomborder);
// actions
}
void refreshList() {
try {
File file = new File(Engine.getAppDataDir() + "\\fountanio\\speedcivilization\\friends.fls");
Reader r = new FileReader(file);
BufferedReader reader = new BufferedReader(r);
} catch (FileNotFoundException e) {
Main.getConsole().errorln("Data directory NOT found!\nPerhaps you may want to restart the game?");
}
}
}
|
package org.fountanio.juancode.out;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.event.*;
public class IPWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JButton gotoip = new JButton("Go");
private JButton gotoipf = new JButton("Go");
private Border topborder = BorderFactory.createTitledBorder("Connect");
private Border bottomborder = BorderFactory.createTitledBorder("Friends");
private JTextField ipinput = new JTextField();
private JList<String> friendlist = new JList();
public IPWindow() {
super("Speed Civilization");
setSize(400, 340);
setLayout(new BorderLayout());
ipinput.setBorder(topborder);
gotoip.setBorder(topborder);
gotoipf.setBorder(bottomborder);
friendlist.setBorder(bottomborder);
// actions
}
}
|
Rename deleteRule variable to currentRule
|
'use strict';
var FormManager = require('./formmanager');
var Rules = require('./rules');
var TableController = require('./table');
var translate = require('./translate');
var rulesContainer;
var currentRule;
var addButton = document.querySelector('#add-button');
addButton.addEventListener('click', () => FormManager.show('add'));
FormManager.on('add', (rule) => rulesContainer.add(rule));
FormManager.on('save', (rule) => rulesContainer.edit(currentRule, rule));
FormManager.on('hide', () => addButton.classList.remove('hidden'));
FormManager.on('show', () => addButton.classList.add('hidden'));
TableController.on('remove', (number) => rulesContainer.remove(number));
TableController.on('click', (number) => {
currentRule = number;
FormManager.fill(rulesContainer.storage.rules[number]);
FormManager.show('edit');
});
window.addEventListener('load', () => {
translate.translateHTML();
chrome.storage.sync.get('rules', obj => {
rulesContainer = new Rules(obj.rules || []);
TableController.table(rulesContainer.storage.rules);
if (rulesContainer.storage.rules.length === 0) {
addButton.click();
}
chrome.storage.onChanged.addListener(() => {
TableController.table(rulesContainer.storage.rules);
});
});
});
|
'use strict';
var FormManager = require('./formmanager');
var Rules = require('./rules');
var TableController = require('./table');
var translate = require('./translate');
var rulesContainer;
var deleteRule;
var addButton = document.querySelector('#add-button');
addButton.addEventListener('click', () => FormManager.show('add'));
FormManager.on('add', (rule) => rulesContainer.add(rule));
FormManager.on('save', (rule) => rulesContainer.edit(deleteRule, rule));
FormManager.on('hide', () => addButton.classList.remove('hidden'));
FormManager.on('show', () => addButton.classList.add('hidden'));
TableController.on('remove', (number) => rulesContainer.remove(number));
TableController.on('click', (number) => {
deleteRule = number;
FormManager.fill(rulesContainer.storage.rules[number]);
FormManager.show('edit');
});
window.addEventListener('load', () => {
translate.translateHTML();
chrome.storage.sync.get('rules', obj => {
rulesContainer = new Rules(obj.rules || []);
TableController.table(rulesContainer.storage.rules);
if (rulesContainer.storage.rules.length === 0) {
addButton.click();
}
chrome.storage.onChanged.addListener(() => {
TableController.table(rulesContainer.storage.rules);
});
});
});
|
Move Rollup.js babel plugin before commonjs
|
// https://github.com/rollup/rollup-starter-project
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
let pkg = require('./package.json');
let external = []
// Mark dependencies and peerDependencies as external
.concat(
Object.keys(pkg.dependencies), Object.keys(pkg.peerDependencies)
)
// ...But bundle svg-partial-circle into the package
.filter(pkgName => pkgName !== 'svg-partial-circle');
let plugins = [
resolve(),
babel(),
commonjs({
// https://github.com/reactjs/react-redux/issues/643#issuecomment-285008041
namedExports: {
'node_modules/react/react.js': ['PureComponent'],
},
}),
];
export default {
input: 'src/index.js',
plugins: plugins,
external: external,
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true,
},
{
file: pkg.module,
format: 'es',
sourcemap: true,
},
],
};
|
// https://github.com/rollup/rollup-starter-project
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
let pkg = require('./package.json');
let external = []
// Mark dependencies and peerDependencies as external
.concat(
Object.keys(pkg.dependencies), Object.keys(pkg.peerDependencies)
)
// ...But bundle svg-partial-circle into the package
.filter(pkgName => pkgName !== 'svg-partial-circle');
let plugins = [
resolve(),
commonjs({
// https://github.com/reactjs/react-redux/issues/643#issuecomment-285008041
namedExports: {
'node_modules/react/react.js': ['PureComponent'],
},
}),
babel(),
];
export default {
input: 'src/index.js',
plugins: plugins,
external: external,
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true,
},
{
file: pkg.module,
format: 'es',
sourcemap: true,
},
],
};
|
Drop Ember v1.11/1.12 compatibility code
We don't support these old Ember versions anymore, so we can drop this codepath now
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let { traverse } = this.syntax;
traverse(ast, {
ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
});
return ast;
};
module.exports = StripTestSelectorsTransform;
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
if ('sexpr' in node) {
node = node.sexpr;
}
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let { traverse } = this.syntax;
traverse(ast, {
ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
});
return ast;
};
module.exports = StripTestSelectorsTransform;
|
Test ingeschakeld om te testen of login scherm getoond wordt
|
<?php
class Webenq_Test_ControllerTestCase_UserControllerTest extends Webenq_Test_Controller
{
public function testLoginFormIsRendered()
{
$this->dispatch('user/login');
$this->assertQuery('input#username');
$this->assertQuery('input#password');
}
// public function testUserCanLoginAndLogout()
// {
// $this->request->setMethod('POST');
// $this->request->setParams(array(
// 'username' => 'test',
// 'password' => 'test'
// ));
// $this->dispatch('user/login');
// $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
// $this->assertTrue(Zend_Auth::getInstance()->getIdentity() == 'test');
//
// $this->dispatch('user/logout');
// $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());
// $this->assertFalse(Zend_Auth::getInstance()->getIdentity() == 'test');
// }
}
|
<?php
class Webenq_Test_ControllerTestCase_UserControllerTest extends Webenq_Test_Controller
{
public function test() {}
// public function testLoginFormIsRendered()
// {
// $this->dispatch('user/login');
// $this->assertQuery('input#username');
// $this->assertQuery('input#password');
// }
// public function testUserCanLoginAndLogout()
// {
// $this->request->setMethod('POST');
// $this->request->setParams(array(
// 'username' => 'test',
// 'password' => 'test'
// ));
// $this->dispatch('user/login');
// $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
// $this->assertTrue(Zend_Auth::getInstance()->getIdentity() == 'test');
//
// $this->dispatch('user/logout');
// $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());
// $this->assertFalse(Zend_Auth::getInstance()->getIdentity() == 'test');
// }
}
|
Unify 'onEventAppeared' and 'onEvent' signatures.
`onEvent` has the signature `(subscription, event) => { }`.
`onEventAppeared` should also be `(subscription, event) => {}` and not `(event) => {}`.
|
import connectionManager from './connectionManager';
import mapEvents from './utilities/mapEvents';
import client from 'node-eventstore-client';
import debugModule from 'debug';
import assert from 'assert';
const debug = debugModule('geteventstore:subscribeToStream');
const baseErr = 'Subscribe to Stream - ';
export default (config) => (
streamName,
onEventAppeared,
onDropped,
resolveLinkTos = false
) => new Promise(async (resolve, reject) => {
assert(streamName, `${baseErr}Stream Name not provided`);
let connection;
const onEvent = (sub, ev) => {
const mappedEvent = mapEvents([ev])[0];
if (mappedEvent) onEventAppeared(sub, mappedEvent);
};
const onConnected = async () => {
try {
const subscription = await connection.subscribeToStream(streamName, resolveLinkTos, onEvent, onDropped, new client.UserCredentials(config.credentials.username, config.credentials.password));
debug('', 'Subscription: %j', subscription);
resolve(subscription);
} catch (ex) {
reject(ex);
}
};
try {
connection = await connectionManager.create(config, onConnected, true);
} catch (ex) {
reject(ex);
}
});
|
import connectionManager from './connectionManager';
import mapEvents from './utilities/mapEvents';
import client from 'node-eventstore-client';
import debugModule from 'debug';
import assert from 'assert';
const debug = debugModule('geteventstore:subscribeToStream');
const baseErr = 'Subscribe to Stream - ';
export default (config) => (
streamName,
onEventAppeared,
onDropped,
resolveLinkTos = false
) => new Promise(async (resolve, reject) => {
assert(streamName, `${baseErr}Stream Name not provided`);
let connection;
const onEvent = (sub, ev) => {
const mappedEvent = mapEvents([ev])[0];
if (mappedEvent) onEventAppeared(mappedEvent);
};
const onConnected = async () => {
try {
const subscription = await connection.subscribeToStream(streamName, resolveLinkTos, onEvent, onDropped, new client.UserCredentials(config.credentials.username, config.credentials.password));
debug('', 'Subscription: %j', subscription);
resolve(subscription);
} catch (ex) {
reject(ex);
}
};
try {
connection = await connectionManager.create(config, onConnected, true);
} catch (ex) {
reject(ex);
}
});
|
Remove testing of private methods (other than that they exist)
|
import unittest
from unittest.mock import patch
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_worksheet should be defined.')
def test_get_data_function_is_defined(self):
if not hasattr(parse_worksheet, '__get_data'):
self.fail('__get_data should be defined.')
def test_write_data_function_is_defined(self):
if not hasattr(parse_worksheet, '__write_data'):
self.fail('__write_data should be defined.')
def test_parse_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, 'parse_worksheet'):
self.fail('parse_worksheet should be defined.')
if __name__ == '__main__':
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestParseWorksheet)
unittest.TextTestRunner(verbosity=2).run(suite)
|
import unittest
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_sheet should be defined.')
def test_get_data_function_is_defined(self):
if not hasattr(parse_worksheet, '__get_data'):
self.fail('__get_data should be defined.')
def test_write_data_function_is_defined(self):
if not hasattr(parse_worksheet, '__write_data'):
self.fail('__write_data should be defined.')
def test_parse_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, 'parse_worksheet'):
self.fail('parse_worksheet should be defined.')
def test_parse_worksheet_function_calls_open_worksheet(self):
if __name__ == '__main__':
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestParseWorksheet)
unittest.TextTestRunner(verbosity=2).run(suite)
|
Use default formatter in dev env in unit-tests
|
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
},
test_with_xunit: {
options: process.env.BUILD_NUMBER ? {
reporter: 'xunit',
quiet: true,
captureFile: 'test-report.xml'
} : {},
src: ['test/**/*.js']
}
},
eslint: {
target: ['Gruntfile.js', './*.js', 'test/**/*.js'],
options: process.env.BUILD_NUMBER ? {
format: 'checkstyle',
outputFile: 'eslint3.xml'
} : {}
}
})
grunt.loadNpmTasks('grunt-mocha-test')
grunt.loadNpmTasks('grunt-eslint')
grunt.registerTask('default', ['eslint', 'mochaTest'])
grunt.registerTask('ci', ['eslint','mochaTest:test_with_xunit'])
}
|
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
},
test_with_xunit: {
options: {
reporter: 'xunit',
quiet: true,
captureFile: 'test-report.xml'
},
src: ['test/**/*.js']
}
},
eslint: {
target: ['Gruntfile.js', './*.js', 'test/**/*.js'],
options: process.env.BUILD_NUMBER ? {
format: 'checkstyle',
outputFile: 'eslint3.xml'
} : {}
}
})
grunt.loadNpmTasks('grunt-mocha-test')
grunt.loadNpmTasks('grunt-eslint')
grunt.registerTask('default', ['eslint', 'mochaTest'])
grunt.registerTask('ci', ['eslint','mochaTest:test_with_xunit'])
}
|
Fix test: make sure that Isolation Forest actually make a categorical split
|
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
cat_frame = h2o.create_frame(cols=10, categorical_fraction=1, seed=42)
# check all columns are categorical
assert set(cat_frame.types.values()) == set(['enum'])
iso_model = H2OIsolationForestEstimator(seed=42)
iso_model.train(training_frame=cat_frame)
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
|
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate.csv"))
prostate["RACE"] = prostate["RACE"].asfactor()
iso_model = H2OIsolationForestEstimator()
iso_model.train(training_frame = prostate, x = list(set(prostate.col_names) - set(["ID", "CAPSULE"])))
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
|
Use data attribute instead of val()
|
var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = $(this).val();
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
|
var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).val());
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = $(this).val();
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
|
Change constant value for backward compatibility
|
export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestCookie'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
}
|
export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestPostMessage'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
}
|
Remove left over console log
|
module("Hide department children", {
setup: function() {
this.$departments = $(
'<div class="js-hide-department-children">'
+ '<div class="department">'
+ '<div class="child-organisations">'
+ '<p>child content</p>'
+ '</div>'
+ '</div>'
+ '</div>');
$('#qunit-fixture').append(this.$departments);
}
});
test("should create toggle link before department list", function() {
GOVUK.hideDepartmentChildren.init();
equals(this.$departments.find('.view-all').length, 1);
});
test("should toggle class when clicking view all link", function() {
GOVUK.hideDepartmentChildren.init();
ok(this.$departments.find('.department').hasClass('js-hiding-children'));
this.$departments.find('.view-all').click();
ok(!this.$departments.find('.department').hasClass('js-hiding-children'));
});
|
module("Hide department children", {
setup: function() {
this.$departments = $(
'<div class="js-hide-department-children">'
+ '<div class="department">'
+ '<div class="child-organisations">'
+ '<p>child content</p>'
+ '</div>'
+ '</div>'
+ '</div>');
$('#qunit-fixture').append(this.$departments);
}
});
test("should create toggle link before department list", function() {
GOVUK.hideDepartmentChildren.init();
equals(this.$departments.find('.view-all').length, 1);
console.log(this.$departments.html());
});
test("should toggle class when clicking view all link", function() {
GOVUK.hideDepartmentChildren.init();
ok(this.$departments.find('.department').hasClass('js-hiding-children'));
this.$departments.find('.view-all').click();
ok(!this.$departments.find('.department').hasClass('js-hiding-children'));
});
|
Fix instance memory output for space-quota(s).
|
package resources
import "github.com/cloudfoundry/cli/cf/models"
type PaginatedSpaceQuotaResources struct {
Resources []SpaceQuotaResource
}
type SpaceQuotaResource struct {
Resource
Entity models.SpaceQuota
}
func (resource SpaceQuotaResource) ToModel() models.SpaceQuota {
entity := resource.Entity
return models.SpaceQuota{
Guid: resource.Metadata.Guid,
Name: entity.Name,
MemoryLimit: entity.MemoryLimit,
InstanceMemoryLimit: entity.InstanceMemoryLimit,
RoutesLimit: entity.RoutesLimit,
ServicesLimit: entity.ServicesLimit,
NonBasicServicesAllowed: entity.NonBasicServicesAllowed,
OrgGuid: entity.OrgGuid,
}
}
|
package resources
import "github.com/cloudfoundry/cli/cf/models"
type PaginatedSpaceQuotaResources struct {
Resources []SpaceQuotaResource
}
type SpaceQuotaResource struct {
Resource
Entity models.SpaceQuota
}
func (resource SpaceQuotaResource) ToModel() models.SpaceQuota {
entity := resource.Entity
return models.SpaceQuota{
Guid: resource.Metadata.Guid,
Name: entity.Name,
MemoryLimit: entity.MemoryLimit,
RoutesLimit: entity.RoutesLimit,
ServicesLimit: entity.ServicesLimit,
NonBasicServicesAllowed: entity.NonBasicServicesAllowed,
OrgGuid: entity.OrgGuid,
}
}
|
Fix calling sendAction on destroyed object error
|
import Ember from 'ember';
import layout from '../templates/components/resize-detector';
const {
inject: { service },
run: { scheduleOnce, bind }
} = Ember;
export default Ember.Component.extend({
layout,
tagName: '',
resizeDetector: service(),
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, this.setup);
},
setup() {
this.callback = bind(this, this.onResize);
this.get('resizeDetector').setup(this.get('selector'), this.callback);
},
teardown() {
this.get('resizeDetector').teardown(this.get('selector'), this.callback);
},
onResize(element) {
if (this.get('isDestroyed') || this.get('isDestroying')) {
return;
}
let $el = Ember.$(element);
this.sendAction('on-resize', {
width: $el.width(),
height: $el.height()
}, element);
},
willDestroyElement() {
this.teardown();
this._super(...arguments);
}
}).reopenClass({
positionalParams: ['selector']
});
|
import Ember from 'ember';
import layout from '../templates/components/resize-detector';
const {
inject: { service },
run: { scheduleOnce, bind }
} = Ember;
export default Ember.Component.extend({
layout,
tagName: '',
resizeDetector: service(),
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, this.setup);
},
setup() {
this.callback = bind(this, this.onResize);
this.get('resizeDetector').setup(this.get('selector'), this.callback);
},
teardown() {
this.get('resizeDetector').teardown(this.get('selector'), this.callback);
},
onResize(element) {
let $el = Ember.$(element);
this.sendAction('on-resize', {
width: $el.width(),
height: $el.height()
}, element);
},
willDestroyElement() {
this.teardown();
this._super(...arguments);
}
}).reopenClass({
positionalParams: ['selector']
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.