text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Switch first handler arg from "server" to "client".
|
from kismetclient.utils import csv
from kismetclient.exceptions import ServerError
def kismet(client, version, starttime, servername, dumpfiles, uid):
""" Handle server startup string. """
print version, servername, uid
def capability(client, CAPABILITY, capabilities):
""" Register a server capability. """
client.capabilities[CAPABILITY] = csv(capabilities)
def protocols(client, protocols):
""" Enumerate capabilities so they can be registered. """
for protocol in csv(protocols):
client.cmd('CAPABILITY', protocol)
def ack(client, cmdid, text):
""" Handle ack messages in response to commands. """
# Simply remove from the in_progress queue
client.in_progress.pop(cmdid)
def error(client, cmdid, text):
""" Handle error messages in response to commands. """
cmd = client.in_progress.pop(cmdid)
raise ServerError(cmd, text)
def print_fields(client, **fields):
""" A generic handler which prints all the fields. """
for k, v in fields.items():
print '%s: %s' % (k, v)
print '-' * 80
|
from kismetclient.utils import csv
from kismetclient.exceptions import ServerError
def kismet(server, version, starttime, servername, dumpfiles, uid):
""" Handle server startup string. """
print version, servername, uid
def capability(server, CAPABILITY, capabilities):
""" Register a server's capability. """
server.capabilities[CAPABILITY] = csv(capabilities)
def protocols(server, protocols):
""" Enumerate capabilities so they can be registered. """
for protocol in csv(protocols):
server.cmd('CAPABILITY', protocol)
def ack(server, cmdid, text):
""" Handle ack messages in response to commands. """
# Simply remove from the in_progress queue
server.in_progress.pop(cmdid)
def error(server, cmdid, text):
""" Handle error messages in response to commands. """
cmd = server.in_progress.pop(cmdid)
raise ServerError(cmd, text)
def print_fields(server, **fields):
""" A generic handler which prints all the fields. """
for k, v in fields.items():
print '%s: %s' % (k, v)
print '-' * 80
|
Allow passing new messages for same locale
|
import { Component, Children } from 'react'
import PropTypes from 'prop-types'
import Polyglot from 'node-polyglot'
// Provider root component
export default class I18n extends Component {
constructor(props) {
super(props)
this._polyglot = new Polyglot({
locale: props.locale,
phrases: props.messages,
})
}
getChildContext() {
return { t: this._polyglot.t.bind(this._polyglot) }
}
componentWillReceiveProps(newProps) {
if (newProps.locale !== this.props.locale) {
this._polyglot.locale(newProps.locale)
}
if (newProps.messages !== this.props.messages) {
this._polyglot.replace(newProps.messages)
}
}
render() {
const children = this.props.children
return Children.only(children)
}
}
I18n.propTypes = {
locale: PropTypes.string.isRequired,
messages: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
}
I18n.childContextTypes = {
t: PropTypes.func.isRequired,
}
|
import { Component, Children } from 'react'
import PropTypes from 'prop-types'
import Polyglot from 'node-polyglot'
// Provider root component
export default class I18n extends Component {
constructor(props) {
super(props)
this._polyglot = new Polyglot({
locale: props.locale,
phrases: props.messages,
})
}
getChildContext() {
return { t: this._polyglot.t.bind(this._polyglot) }
}
componentWillReceiveProps(newProps) {
if (newProps.locale !== this.props.locale) {
this._polyglot.locale(newProps.locale)
this._polyglot.replace(newProps.messages)
}
}
render() {
const children = this.props.children
return Children.only(children)
}
}
I18n.propTypes = {
locale: PropTypes.string.isRequired,
messages: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
}
I18n.childContextTypes = {
t: PropTypes.func.isRequired,
}
|
Add ginkgo defer to allow us to see error message
-This is when the main_suite_test fails before running
the main_test
|
package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
defer GinkgoRecover()
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
|
package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
|
Use triple-quotes for long strings
|
from distutils.core import setup
import bugspots
setup(
name="bugspots",
version=bugspots.__version__,
description="""Identify hot spots in a codebase with the bug prediction
algorithm used at Google.""",
long_description=bugspots.__doc__,
author=bugspots.__author__,
author_email="bmbslice@gmail.com",
url="http://pypi.python.org/pypi/bugspots",
py_modules=["bugspots"],
license=bugspots.__license__,
platforms="Unix",
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Natural Language :: English",
"Operating System :: Unix",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development :: Bug Tracking",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities"
]
)
|
from distutils.core import setup
import bugspots
setup(
name="bugspots",
version=bugspots.__version__,
description="Identify hot spots in a codebase with the bug prediction \
algorithm used at Google",
long_description=bugspots.__doc__,
author=bugspots.__author__,
author_email="bmbslice@gmail.com",
url="http://pypi.python.org/pypi/bugspots",
py_modules=["bugspots"],
license=bugspots.__license__,
platforms="Unix",
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Natural Language :: English",
"Operating System :: Unix",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development :: Bug Tracking",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities"
]
)
|
Copy new implementation of $trWrapper and $tr from i18n.js
|
import vue from 'vue';
import vuex from 'vuex';
import router from 'vue-router';
import vueintl from 'vue-intl';
import 'intl';
import 'intl/locale-data/jsonp/en.js';
vue.prototype.Kolibri = {};
vue.config.silent = true;
vue.use(vuex);
vue.use(router);
vue.use(vueintl, { defaultLocale: 'en-us' });
function $trWrapper(nameSpace, defaultMessages, formatter, messageId, args) {
if (args) {
if (!Array.isArray(args) && typeof args !== 'object') {
console.error(`The $tr functions take either an array of positional
arguments or an object of named options.`);
}
}
const defaultMessageText = defaultMessages[messageId];
const message = {
id: `${nameSpace}.${messageId}`,
defaultMessage: defaultMessageText,
};
return formatter(message, args);
}
vue.prototype.$tr = function $tr(messageId, args) {
const nameSpace = this.$options.name || this.$options.$trNameSpace;
return $trWrapper(nameSpace, this.$options.$trs, this.$formatMessage, messageId, args);
};
export default vue;
|
import vue from 'vue';
import vuex from 'vuex';
import router from 'vue-router';
import vueintl from 'vue-intl';
vue.prototype.Kolibri = {};
vue.config.silent = true;
vue.use(vuex);
vue.use(router);
require('intl');
require('intl/locale-data/jsonp/en.js');
vue.use(vueintl, { defaultLocale: 'en-us' });
vue.mixin({
store: new vuex.Store({}),
});
function $trWrapper(formatter, messageId, args) {
if (args) {
if (!Array.isArray(args) && typeof args !== 'object') {
logging.error(`The $tr functions take either an array of positional
arguments or an object of named options.`);
}
}
const defaultMessageText = this.$options.$trs[messageId];
const message = {
id: `${this.$options.$trNameSpace}.${messageId}`,
defaultMessage: defaultMessageText,
};
return formatter(message, args);
}
vue.prototype.$tr = function $tr(messageId, args) {
return $trWrapper.call(this, this.$formatMessage, messageId, args);
};
export default vue;
|
Fix parseDocument (was broken on Firefox)
|
/* HTML utilities */
define(function () {
function parseDocument(html) {
// The HTML parsing is not supported on all the browsers, maybe we
// should use a polyfill?
var parser = new DOMParser();
return parser.parseFromString(html, 'text/html');
}
function load(url, processResponse) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // async
xhr.responseType = 'document';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // response received and loaded
processResponse({
status: xhr.status,
document: xhr.response
});
}
};
xhr.send(null);
}
return {
parseDocument: parseDocument,
load: load
};
});
|
/* HTML utilities */
define(function () {
function parseDocument(html) {
/*
var parser = new DOMParser();
return parser.parseFromString(html, 'text/html');
*/
var doc = document.implementation.createHTMLDocument('');
doc.open();
doc.write(html);
doc.close();
return doc;
}
function load(url, processResponse) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // async
xhr.responseType = 'document';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // response received and loaded
processResponse({
status: xhr.status,
document: xhr.response
});
}
};
xhr.send(null);
}
return {
parseDocument: parseDocument,
load: load
};
});
|
Use buffered channel for signals to fix go vet
|
package cli
import (
"os"
"os/signal"
"syscall"
"github.com/99designs/aws-vault/v6/server"
"github.com/alecthomas/kingpin"
)
func ConfigureProxyCommand(app *kingpin.Application, a *AwsVault) {
stop := false
cmd := app.Command("proxy", "Start a proxy for the ec2 instance role server locally").
Alias("server").
Hidden()
cmd.Flag("stop", "Stop the proxy").
BoolVar(&stop)
cmd.Action(func(*kingpin.ParseContext) error {
if stop {
server.StopProxy()
return nil
} else {
handleSigTerm()
return server.StartProxy()
}
})
}
func handleSigTerm() {
// shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
server.Shutdown()
os.Exit(1)
}()
}
|
package cli
import (
"os"
"os/signal"
"syscall"
"github.com/99designs/aws-vault/v6/server"
"github.com/alecthomas/kingpin"
)
func ConfigureProxyCommand(app *kingpin.Application, a *AwsVault) {
stop := false
cmd := app.Command("proxy", "Start a proxy for the ec2 instance role server locally").
Alias("server").
Hidden()
cmd.Flag("stop", "Stop the proxy").
BoolVar(&stop)
cmd.Action(func(*kingpin.ParseContext) error {
if stop {
server.StopProxy()
return nil
} else {
handleSigTerm()
return server.StartProxy()
}
})
}
func handleSigTerm() {
// shutdown
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
server.Shutdown()
os.Exit(1)
}()
}
|
Replace tiles after the world ticked. Might stop a crash with fastcraft
|
package ganymedes01.etfuturum.core.handlers;
import ganymedes01.etfuturum.ModBlocks;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.WorldTickEvent;
import cpw.mods.fml.relauncher.Side;
public class WorldTickEventHandler {
@SubscribeEvent
@SuppressWarnings("unchecked")
public void tick(WorldTickEvent event) {
if (event.side != Side.SERVER || event.phase != Phase.END)
return;
World world = event.world;
for (TileEntity tile : (List<TileEntity>) world.loadedTileEntityList) {
Block block = world.getBlock(tile.xCoord, tile.yCoord, tile.zCoord);
if (block == Blocks.brewing_stand) {
world.setBlock(tile.xCoord, tile.yCoord, tile.zCoord, ModBlocks.brewing_stand);
return;
}
}
}
}
|
package ganymedes01.etfuturum.core.handlers;
import ganymedes01.etfuturum.ModBlocks;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.WorldTickEvent;
import cpw.mods.fml.relauncher.Side;
public class WorldTickEventHandler {
@SubscribeEvent
@SuppressWarnings("unchecked")
public void tick(WorldTickEvent event) {
if (event.side != Side.SERVER || event.phase != Phase.START)
return;
World world = event.world;
for (TileEntity tile : (List<TileEntity>) world.loadedTileEntityList) {
Block block = world.getBlock(tile.xCoord, tile.yCoord, tile.zCoord);
if (block == Blocks.brewing_stand) {
world.setBlock(tile.xCoord, tile.yCoord, tile.zCoord, ModBlocks.brewing_stand);
return;
}
}
}
}
|
Modify Validate Region for test cases
|
package common
import (
"flag"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func listEC2Regions() []string {
var regions []string
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
ec2conn := ec2.New(sess)
resultRegions, _ := ec2conn.DescribeRegions(nil)
for _, region := range resultRegions.Regions {
regions = append(regions, *region.RegionName)
}
return regions
}
// ValidateRegion returns true if the supplied region is a valid AWS
// region and false if it's not.
func ValidateRegion(region string) bool {
// To pass tests
if v := flag.Lookup("test.v"); v != nil || v.Value.String() == "true" {
regions := []string{
"us-east-1",
"us-east-2",
"us-west-1",
}
for _, valid := range regions {
if region == valid {
return true
}
}
}
// Normal run
for _, valid := range listEC2Regions() {
if region == valid {
return true
}
}
return false
}
|
package common
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func listEC2Regions() []string {
var regions []string
// append regions that are not part of autogenerated list
regions = append(regions, "us-gov-west-1", "cn-north-1", "cn-northwest-1")
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
ec2conn := ec2.New(sess)
resultRegions, _ := ec2conn.DescribeRegions(nil)
for _, region := range resultRegions.Regions {
regions = append(regions, *region.RegionName)
}
return regions
}
// ValidateRegion returns true if the supplied region is a valid AWS
// region and false if it's not.
func ValidateRegion(region string) bool {
for _, valid := range listEC2Regions() {
if region == valid {
return true
}
}
return false
}
|
Update Arconaitv to new url
|
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
_url_re = re.compile(r'''https?://(www\.)?arconaitv\.co/stream\.php\?id=\d+''')
_playlist_re = re.compile(r'''source\ssrc=["'](?P<url>[^"']+)["']''')
class ArconaiTv(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
headers = {
'User-Agent': useragents.CHROME,
'Referer': self.url
}
res = http.get(self.url, headers=headers)
match = _playlist_re.search(res.text)
if match is None:
return
url = match.group('url')
if url:
self.logger.debug('HLS URL: {0}'.format(url))
yield 'live', HLSStream(self.session, url, headers=headers)
__plugin__ = ArconaiTv
|
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
_url_re = re.compile(r'''https?://(www\.)?arconaitv\.me/stream\.php\?id=\d+''')
_playlist_re = re.compile(r'''source\ssrc=["'](?P<url>[^"']+)["']''')
class ArconaiTv(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
headers = {
'User-Agent': useragents.CHROME,
'Referer': self.url
}
res = http.get(self.url, headers=headers)
match = _playlist_re.search(res.text)
if match is None:
return
url = match.group('url')
if url:
self.logger.debug('HLS URL: {0}'.format(url))
yield 'live', HLSStream(self.session, url, headers=headers)
__plugin__ = ArconaiTv
|
Fix ft for my bets page
|
class UserBetsPage(object):
def __init__(self, test):
self.test = test
self.url = self.test.live_server_url + '/my_bets'
def go(self):
self.test.browser.get(self.url)
def get_matches(self):
return self.test.browser \
.find_elements_by_css_selector('tr.match')
def get_match_body(self, match):
return match.find_element_by_class_name('bet').text
def get_match_input(self, match):
return match.find_element_by_tag_name('input')
def press_save_button(self):
self.test.browser.find_element_by_id('save_bets').click()
def get_match_error(self, match):
return match.find_element_by_css_selector('div.error').text
|
class UserBetsPage(object):
def __init__(self, test):
self.test = test
self.url = self.test.live_server_url + '/my_bets'
def go(self):
self.test.browser.get(self.url)
def get_matches(self):
return self.test.browser \
.find_elements_by_css_selector('div.match')
def get_match_body(self, match):
return match.find_element_by_class_name('bet').text
def get_match_input(self, match):
return match.find_element_by_tag_name('input')
def press_save_button(self):
self.test.browser.find_element_by_id('save_bets').click()
def get_match_error(self, match):
return match.find_element_by_css_selector('div.error').text
|
Disable parallel requests for now
|
"use strict";
plugin.consumes = [
"db", "connect.static"
];
plugin.provides = [
"unpacked_helper"
];
module.exports = plugin;
function plugin(options, imports, register) {
var connectStatic = imports["connect.static"];
var assert = require("assert");
var baseUrl = options.baseUrl;
var ideBaseUrl = options.ideBaseUrl;
assert(options.baseUrl, "baseUrl must be set");
assert(options.ideBaseUrl, "ideBaseUrl must be set");
var balancers = [
baseUrl + "/uph",
];
/* UNDONE: for now we put all static content on one domain
because of reports of CORS errors
if (!options.avoidSubdomains)
balancers.push(
ideBaseUrl
// We could include others but dogfooding URLs like
// vfs.newclient-lennartcl.c9.io don't have a cert, so
// let's not
// apiBaseUrl + "/uph",
// vfsBaseUrl + "/uph"
);
*/
connectStatic.getRequireJsConfig().baseUrlLoadBalancers = balancers;
assert(connectStatic.getRequireJsConfig().baseUrlLoadBalancers);
register(null, {
"unpacked_helper": {}
});
}
|
"use strict";
plugin.consumes = [
"db", "connect.static"
];
plugin.provides = [
"unpacked_helper"
];
module.exports = plugin;
function plugin(options, imports, register) {
var connectStatic = imports["connect.static"];
var assert = require("assert");
var baseUrl = options.baseUrl;
var ideBaseUrl = options.ideBaseUrl;
assert(options.baseUrl, "baseUrl must be set");
assert(options.ideBaseUrl, "ideBaseUrl must be set");
var balancers = [
baseUrl + "/uph",
];
if (!options.avoidSubdomains)
balancers.push(
ideBaseUrl
// We could include others but dogfooding URLs like
// vfs.newclient-lennartcl.c9.io don't have a cert, so
// let's not
// apiBaseUrl + "/uph",
// vfsBaseUrl + "/uph"
);
connectStatic.getRequireJsConfig().baseUrlLoadBalancers = balancers;
assert(connectStatic.getRequireJsConfig().baseUrlLoadBalancers);
register(null, {
"unpacked_helper": {}
});
}
|
Add a constructor for a component of the load-button
|
(function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var Button = app.Button || require('./button.js');
var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js');
var LoadButton = helper.inherits(function(props) {
LoadButton.super_.call(this, props);
}, Button);
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.element = this.prop(props.element);
this.sidebarToggleButton = this.prop(new SidebarToggleButton({
element: this.sidebarToggleButtonElement(),
collapser: props.sidebarCollapser,
expander: props.sidebarExpander
}));
this.sidebarToggleButton().registerTapListener();
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.prototype.loadButtonElement = function() {
return dom.child(this.element(), 1);
};
ContentHeader.prototype.saveButtonElement = function() {
return dom.child(this.element(), 2);
};
ContentHeader.prototype.redraw = function() {
this.sidebarToggleButton().redraw();
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
|
(function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js');
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.element = this.prop(props.element);
this.sidebarToggleButton = this.prop(new SidebarToggleButton({
element: this.sidebarToggleButtonElement(),
collapser: props.sidebarCollapser,
expander: props.sidebarExpander
}));
this.sidebarToggleButton().registerTapListener();
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.prototype.loadButtonElement = function() {
return dom.child(this.element(), 1);
};
ContentHeader.prototype.saveButtonElement = function() {
return dom.child(this.element(), 2);
};
ContentHeader.prototype.redraw = function() {
this.sidebarToggleButton().redraw();
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
|
Fix bug with profile loading
|
app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
generic_search: null,
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
self.setMentor = function(mentor){
console.log(mentor.id);
BioFactory.setMentor(mentor);
};
self.getMentors = function() {
console.log(self.newSearch);
var newSearchString = JSON.stringify(self.newSearch);
return $http({
method: 'GET',
url: '/mentor-search/search',
headers: {
newSearchString: newSearchString
}
})
.then(function(response) {
self.mentors = response.data;
console.log("Mentors list:", self.mentors);
}),
function(err) {
console.log("Error with search get request ", err);
};
};
}]);
|
app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
generic_search: null,
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
self.test = function() {
console.log(self.newSearch);
};
self.getMentors = function() {
console.log(self.newSearch);
var newSearchString = JSON.stringify(self.newSearch);
return $http({
method: 'GET',
url: '/mentor-search/search',
headers: {
newSearchString: newSearchString
}
})
.then(function(response) {
self.mentors = response.data;
console.log("Mentors list:", self.mentors);
}),
function(err) {
console.log("Error with search get request ", err);
};
};
}]);
|
Clarify AccessMode alternative in else.
|
package io.collap.bryg.compiler.ast.expression;
import io.collap.bryg.compiler.ast.AccessMode;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.parser.StandardVisitor;
import io.collap.bryg.compiler.expression.Variable;
import static org.objectweb.asm.Opcodes.*;
public class VariableExpression extends Expression {
private Variable variable;
private AccessMode mode;
public VariableExpression (StandardVisitor visitor, Variable variable, AccessMode mode, int line) {
super (visitor);
this.mode = mode;
setLine (line);
this.variable = variable;
setType (variable.getType ());
}
@Override
public void compile () {
BrygMethodVisitor method = visitor.getMethod ();
if (mode == AccessMode.get) {
method.visitVarInsn (type.getAsmType ().getOpcode (ILOAD), variable.getId ());
// -> T
}else { /* AccessMode.set */
method.visitVarInsn (type.getAsmType ().getOpcode (ISTORE), variable.getId ());
// T ->
}
}
public Variable getVariable () {
return variable;
}
public AccessMode getMode () {
return mode;
}
}
|
package io.collap.bryg.compiler.ast.expression;
import io.collap.bryg.compiler.ast.AccessMode;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.parser.StandardVisitor;
import io.collap.bryg.compiler.expression.Variable;
import static org.objectweb.asm.Opcodes.*;
public class VariableExpression extends Expression {
private Variable variable;
private AccessMode mode;
public VariableExpression (StandardVisitor visitor, Variable variable, AccessMode mode, int line) {
super (visitor);
this.mode = mode;
setLine (line);
this.variable = variable;
setType (variable.getType ());
}
@Override
public void compile () {
BrygMethodVisitor method = visitor.getMethod ();
if (mode == AccessMode.get) {
method.visitVarInsn (type.getAsmType ().getOpcode (ILOAD), variable.getId ());
// -> T
}else {
method.visitVarInsn (type.getAsmType ().getOpcode (ISTORE), variable.getId ());
// T ->
}
}
public Variable getVariable () {
return variable;
}
public AccessMode getMode () {
return mode;
}
}
|
Fix zero-length field error when building docs in Python 2.6
|
import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {0}
""".format(release)
exclude_patterns = ['_build']
pygments_style = 'sphinx'
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
html_sidebars = {"**": ['localtoc.html', 'relations.html', 'sourcelink.html',
'searchbox.html', 'links.html']}
latex_elements = {}
latex_documents = [
('index', 'libtaxii.tex', u'libtaxii Documentation',
u'The MITRE Corporation', 'manual'),
]
|
import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {}
""".format(release)
exclude_patterns = ['_build']
pygments_style = 'sphinx'
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
html_sidebars = {"**": ['localtoc.html', 'relations.html', 'sourcelink.html',
'searchbox.html', 'links.html']}
latex_elements = {}
latex_documents = [
('index', 'libtaxii.tex', u'libtaxii Documentation',
u'The MITRE Corporation', 'manual'),
]
|
Use array_walk instead of loop
|
<?php
namespace jjok\Switches\Strategy;
use DateTimeInterface as DateTime;
use jjok\Switches\Period;
use jjok\Switches\SwitchStrategy;
use jjok\Switches\Time;
use function array_walk;
final class DailySchedule implements SwitchStrategy
{
/**
* @var Period[]
*/
private $periods = [];
public function __construct(array $periods)
{
array_walk($periods, [$this, 'addPeriod']);
}
private function addPeriod(Period $period) : void
{
$this->periods[] = $period;
}
public function isOnAt(DateTime $dateTime) : bool
{
$time = Time::fromDateTime($dateTime);
foreach ($this->periods as $period) {
if($time->isDuring($period)) {
return true;
}
}
return false;
}
}
|
<?php
namespace jjok\Switches\Strategy;
use DateTimeInterface as DateTime;
use jjok\Switches\Period;
use jjok\Switches\SwitchStrategy;
use jjok\Switches\Time;
final class DailySchedule implements SwitchStrategy
{
/**
* @var Period[]
*/
private $periods = [];
public function __construct(array $periods)
{
foreach($periods as $period) {
$this->addPeriod($period);
}
}
private function addPeriod(Period $period)
{
$this->periods[] = $period;
}
public function isOnAt(DateTime $dateTime) : bool
{
$time = Time::fromDateTime($dateTime);
foreach ($this->periods as $period) {
// if($period->includes($time)) {
if($time->isDuring($period)) {
return true;
}
}
return false;
}
}
|
Convert Clone from object to function
I find it really annoying that we have to do `NodeGit.Clone.clone` just
to clone a repository. It would be much nicer to get a similar effect
like in C, where you can run `git_clone`. This copies over the effect
of an object, but actually using our `clone` patched function instead.
I've made this commit first to show it does not introduce regressions
with our current clone code.
|
var NodeGit = require("../");
var normalizeOptions = require("./util/normalize_options");
var Clone = NodeGit.Clone;
var clone = Clone.clone;
/**
* Patch repository cloning to automatically coerce objects.
*
* @async
* @param {String} url url of the repository
* @param {String} local_path local path to store repository
* @param {CloneOptions} [options]
* @return {Repository} repo
*/
Clone.clone = function(url, local_path, options) {
var remoteCallbacks;
if (options) {
remoteCallbacks = options.remoteCallbacks;
delete options.remoteCallbacks;
}
options = normalizeOptions(options, NodeGit.CloneOptions);
if (remoteCallbacks) {
options.remoteCallbacks =
normalizeOptions(remoteCallbacks, NodeGit.RemoteCallbacks);
}
// This is required to clean up after the clone to avoid file locking
// issues in Windows and potentially other issues we don't know about.
var freeRepository = function(repository) {
repository.free();
};
// We want to provide a valid repository object, so reopen the repository
// after clone and cleanup.
var openRepository = function() {
return NodeGit.Repository.open(local_path);
};
return clone.call(this, url, local_path, options)
.then(freeRepository)
.then(openRepository);
};
// Inherit directly from the original clone object.
Clone.clone.__proto__ = Clone;
// Ensure we're using the correct prototype.
Clone.clone.prototype = Clone.prototype;
module.exports = Clone.clone;
|
var NodeGit = require("../");
var normalizeOptions = require("./util/normalize_options");
var Clone = NodeGit.Clone;
var clone = Clone.clone;
/**
* Patch repository cloning to automatically coerce objects.
*
* @async
* @param {String} url url of the repository
* @param {String} local_path local path to store repository
* @param {CloneOptions} [options]
* @return {Repository} repo
*/
Clone.clone = function(url, local_path, options) {
var remoteCallbacks;
if (options) {
remoteCallbacks = options.remoteCallbacks;
delete options.remoteCallbacks;
}
options = normalizeOptions(options, NodeGit.CloneOptions);
if (remoteCallbacks) {
options.remoteCallbacks =
normalizeOptions(remoteCallbacks, NodeGit.RemoteCallbacks);
}
// This is required to clean up after the clone to avoid file locking
// issues in Windows and potentially other issues we don't know about.
var freeRepository = function(repository) {
repository.free();
};
// We want to provide a valid repository object, so reopen the repository
// after clone and cleanup.
var openRepository = function() {
return NodeGit.Repository.open(local_path);
};
return clone.call(this, url, local_path, options)
.then(freeRepository)
.then(openRepository);
};
module.exports = Clone;
|
Update Copyright year to 2005
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@325095 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 8de90f5c3893df00b32b3f6cf2ae219fcf488bb6
|
/*
* Copyright 2003-2005 The Apache Software Foundation.
*
* 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.
*
*/
/*
* Created on 02-Oct-2003
*
* This class defines the JMeter version only (moved from JMeterUtils)
*
* Version changes no longer change the JMeterUtils source file
* - easier to spot when JMeterUtils really changes
* - much smaller to download when the version changes
*
*/
package org.apache.jmeter.util;
/**
* Utility class to define the JMeter Version string
*
*/
public class JMeterVersion
{
/*
* The VERSION string is updated by the Ant build file, which looks for the
* pattern: VERSION = <quote>.*<quote>
*
*/
static final String VERSION = "2.1.20041210";
static final String COPYRIGHT = "Copyright (c) 1998-2005 The Apache Software Foundation";
private JMeterVersion() // Not instantiable
{
super();
}
}
|
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* 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.
*
*/
/*
* Created on 02-Oct-2003
*
* This class defines the JMeter version only (moved from JMeterUtils)
*
* Version changes no longer change the JMeterUtils source file
* - easier to spot when JMeterUtils really changes
* - much smaller to download when the version changes
*
*/
package org.apache.jmeter.util;
/**
* Utility class to define the JMeter Version string
*
*/
public class JMeterVersion
{
/*
* The VERSION string is updated by the Ant build file, which looks for the
* pattern: VERSION = <quote>.*<quote>
*
*/
static final String VERSION = "2.1.20041210";
static final String COPYRIGHT = "Copyright (c) 1998-2004 The Apache Software Foundation";
private JMeterVersion() // Not instantiable
{
super();
}
}
|
Add the setting of root element label
|
package editor;
import utility.Observer;
import xml.Element;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
/**
* The ElementTreeView controls the section of the GUI that displays the tree
* representation of an XML element tree.
*/
public class ElementTreeView extends JPanel implements Observer {
private JTree tree;
private Element root;
private DefaultMutableTreeNode treeNode;
private DefaultTreeModel model;
/**
* Create the tree view and associate it with a particular model (root of
* the XML element tree)
* @param root The root element of the XML element tree.
*/
public ElementTreeView(Element root) {
root.registerObserver(this);
this.root = root;
treeNode = new DefaultMutableTreeNode();
tree = new JTree(treeNode);
model = (DefaultTreeModel) tree.getModel();
add(tree);
setVisible(false);
}
/**
* When the associated element tree root has changed, change the view
*/
public void notifyObserver() {
if (root != null) {
// TODO: Change the tree
treeNode.setUserObject("DEBUG_ROOT");
model.nodeChanged(treeNode);
System.out.println("[DEBUG] root has changed");
setVisible(true);
}
}
}
|
package editor;
import utility.Observer;
import xml.Element;
import javax.swing.*;
/**
* The ElementTreeView controls the section of the GUI that displays the tree
* representation of an XML element tree.
*/
public class ElementTreeView extends JPanel implements Observer {
private JTree tree;
private Element root;
/**
* Create the tree view and associate it with a particular model (root of
* the XML element tree)
* @param root The root element of the XML element tree.
*/
public ElementTreeView(Element root) {
root.registerObserver(this);
this.root = root;
tree = new JTree();
add(tree);
setVisible(false);
}
/**
* When the associated element tree root has changed, change the view
*/
public void notifyObserver() {
if (root != null) {
// TODO: Change the tree
System.out.println("[DEBUG] root has changed");
setVisible(true);
}
}
}
|
Make sure small images look good in carousel
Closes #448.
|
import React, { PropTypes } from 'react';
import Carousel from 'react-bootstrap/lib/Carousel';
import { getCaption } from 'utils/imageUtils';
const IMAGE_WIDTH = 700;
const IMAGE_HEIGHT = 420;
function renderCarouselItem(image, altText) {
const imageAlt = getCaption(image) || altText;
const imageSrc = `${image.url}?dim=${IMAGE_WIDTH}x${IMAGE_HEIGHT}`;
return (
<Carousel.Item key={image.url}>
<img
alt={imageAlt}
src={imageSrc}
style={{ backgroundColor: '#ccc', height: IMAGE_HEIGHT, width: IMAGE_WIDTH }}
/>
</Carousel.Item>
);
}
function ImageCarousel({ images, altText }) {
return (
<Carousel
className="image-carousel"
controls={images.length > 1}
indicators={images.length > 1}
interval={7000}
style={{ maxWidth: IMAGE_WIDTH }}
>
{images.map(image => renderCarouselItem(image, altText))}
</Carousel>
);
}
ImageCarousel.propTypes = {
altText: PropTypes.string.isRequired,
images: PropTypes.array.isRequired,
};
export default ImageCarousel;
|
import React, { PropTypes } from 'react';
import Carousel from 'react-bootstrap/lib/Carousel';
import { getCaption } from 'utils/imageUtils';
const IMAGE_WIDTH = 700;
const IMAGE_HEIGHT = 420;
function renderCarouselItem(image, altText) {
const imageAlt = getCaption(image) || altText;
const imageSrc = `${image.url}?dim=${IMAGE_WIDTH}x${IMAGE_HEIGHT}`;
return (
<Carousel.Item key={image.url}>
<img alt={imageAlt} src={imageSrc} />
</Carousel.Item>
);
}
function ImageCarousel({ images, altText }) {
return (
<Carousel
className="image-carousel"
controls={images.length > 1}
indicators={images.length > 1}
interval={7000}
style={{ maxWidth: IMAGE_WIDTH }}
>
{images.map(image => renderCarouselItem(image, altText))}
</Carousel>
);
}
ImageCarousel.propTypes = {
altText: PropTypes.string.isRequired,
images: PropTypes.array.isRequired,
};
export default ImageCarousel;
|
Fix of bug in Python 2.6 with failed isclass check in inspect module
|
"""Utils module."""
from six import class_types
from .errors import Error
def is_provider(instance):
"""Check if instance is provider instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_PROVIDER__'))
def ensure_is_provider(instance):
"""Check if instance is provider instance, otherwise raise and error."""
if not is_provider(instance):
raise Error('Expected provider instance, '
'got {0}'.format(str(instance)))
return instance
def is_injection(instance):
"""Check if instance is injection instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_INJECTION__'))
def is_init_arg_injection(instance):
"""Check if instance is init arg injection instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_INIT_ARG_INJECTION__'))
def is_attribute_injection(instance):
"""Check if instance is attribute injection instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_ATTRIBUTE_INJECTION__'))
def is_method_injection(instance):
"""Check if instance is method injection instance."""
return (not isinstance(instance, class_types) and
hasattr(instance, '__IS_OBJECTS_METHOD_INJECTION__'))
|
"""Utils module."""
from inspect import isclass
from .errors import Error
def is_provider(instance):
"""Check if instance is provider instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_PROVIDER__'))
def ensure_is_provider(instance):
"""Check if instance is provider instance, otherwise raise and error."""
if not is_provider(instance):
raise Error('Expected provider instance, '
'got {0}'.format(str(instance)))
return instance
def is_injection(instance):
"""Check if instance is injection instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_INJECTION__'))
def is_init_arg_injection(instance):
"""Check if instance is init arg injection instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_INIT_ARG_INJECTION__'))
def is_attribute_injection(instance):
"""Check if instance is attribute injection instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_ATTRIBUTE_INJECTION__'))
def is_method_injection(instance):
"""Check if instance is method injection instance."""
return (not isclass(instance) and
hasattr(instance, '__IS_OBJECTS_METHOD_INJECTION__'))
|
Remove dirty lies from doctstring
This was a leftover from wherever I originally copied this config from.
|
"""Configuration for testtube.
Automatically run tests when files change by running: stir
See: https://github.com/thomasw/testtube
For flake8, don't forget to install:
* flake8-quotes
"""
from testtube.helpers import Flake8, Helper, Nosetests
class ScreenClearer(Helper):
command = 'clear'
def success(self, *args):
pass
class Isort(Helper):
command = 'isort'
def get_args(self):
return ['--check']
class UnitTests(Nosetests):
def get_args(self, *args, **kwargs):
return ['-x', '--with-doctest', '--doctest-options=+ELLIPSIS',
'--doctest-extension=rst']
clear = ScreenClearer(all_files=True)
lint_style = Flake8(all_files=True)
unit_tests = UnitTests(all_files=True)
PATTERNS = (
(r'.*\.(py|rst)$', [clear, unit_tests], {'fail_fast': True}),
(r'.*\.py$', [lint_style], {'fail_fast': True}),
)
|
"""Configuration for testtube.
Automatically run tests when files change by running: stir
See: https://github.com/thomasw/testtube
For flake8, don't forget to install:
* flake8-quotes
"""
from testtube.helpers import Flake8, Helper, Nosetests
class ScreenClearer(Helper):
command = 'clear'
def success(self, *args):
pass
class Isort(Helper):
command = 'isort'
def get_args(self):
return ['--check']
class UnitTests(Nosetests):
"""Run test cases in the tests/ directory."""
def get_args(self, *args, **kwargs):
return ['-x', '--with-doctest', '--doctest-options=+ELLIPSIS',
'--doctest-extension=rst']
clear = ScreenClearer(all_files=True)
lint_style = Flake8(all_files=True)
unit_tests = UnitTests(all_files=True)
PATTERNS = (
(r'.*\.(py|rst)$', [clear, unit_tests], {'fail_fast': True}),
(r'.*\.py$', [lint_style], {'fail_fast': True}),
)
|
Change default loadMore and limit configuration
|
Comments.ui = (function () {
Avatar.options = {
defaultImageUrl: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png'
};
Tracker.autorun(function () {
var userId = Meteor.userId();
if (userId) {
Comments.session.set('loginAction', '');
}
});
var config = {
template: 'semantic-ui',
limit: 30,
loadMoreCount: 20
};
return {
config: function (newConfig) {
if (!newConfig) {
return config;
}
config = _.extend(config, newConfig);
},
callIfLoggedIn: function (action, cb) {
if (!Meteor.userId()) {
Comments.session.set('loginAction', action);
} else {
return cb();
}
}
};
})();
|
Comments.ui = (function () {
Avatar.options = {
defaultImageUrl: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png'
};
Tracker.autorun(function () {
var userId = Meteor.userId();
if (userId) {
Comments.session.set('loginAction', '');
}
});
var config = {
template: 'semantic-ui',
limit: 2,
loadMoreCount: 1
};
return {
config: function (newConfig) {
if (!newConfig) {
return config;
}
config = _.extend(config, newConfig);
},
callIfLoggedIn: function (action, cb) {
if (!Meteor.userId()) {
Comments.session.set('loginAction', action);
} else {
return cb();
}
}
};
})();
|
Check script returns an exit code
|
import errno
import sys
class CPUFlags:
def __init__(self):
self.flags = set()
try:
self.flags = self.__parse_cpuinfo()
except IOError as e:
if e.errno == errno.ENOENT:
return
raise
def __contains__(self, name):
return name in self.flags
def __parse_cpuinfo(self):
def get_flags():
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('flags'):
return line
line = get_flags().split()
del line[:2] # remove tokens "flags", ":"
return set(line)
def main():
import sys
flags = CPUFlags()
if len(sys.argv) == 2:
if sys.argv[1] in flags:
print "present"
return 0
return 1
if __name__ == '__main__':
sys.exit(main())
|
import errno
class CPUFlags:
def __init__(self):
self.flags = set()
try:
self.flags = self.__parse_cpuinfo()
except IOError as e:
if e.errno == errno.ENOENT:
return
raise
def __contains__(self, name):
return name in self.flags
def __parse_cpuinfo(self):
def get_flags():
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('flags'):
return line
line = get_flags().split()
del line[:2] # remove tokens "flags", ":"
return set(line)
def main():
import sys
flags = CPUFlags()
if len(sys.argv) == 2:
if sys.argv[1] in flags:
print "present"
if __name__ == '__main__':
main()
|
Switch uuid to original implementation
The original code.google.com go-uuid package has now been migrated to github by Paul Borman, a Googler and a Golang core contributor.
|
package osin
import (
"encoding/base64"
"strings"
"github.com/pborman/uuid"
)
// AuthorizeTokenGenDefault is the default authorization token generator
type AuthorizeTokenGenDefault struct {
}
func removePadding(token string) string {
return strings.TrimRight(token, "=")
}
// GenerateAuthorizeToken generates a base64-encoded UUID code
func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
token := uuid.NewRandom()
return removePadding(base64.URLEncoding.EncodeToString([]byte(token))), nil
}
// AccessTokenGenDefault is the default authorization token generator
type AccessTokenGenDefault struct {
}
// GenerateAccessToken generates base64-encoded UUID access and refresh tokens
func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) {
token := uuid.NewRandom()
return removePadding(base64.URLEncoding.EncodeToString([]byte(token))), nil
if generaterefresh {
rtoken := uuid.NewRandom()
refreshtoken = removePadding(base64.URLEncoding.EncodeToString([]byte(rtoken)))
}
return
}
|
package osin
import (
"encoding/base64"
"strings"
"github.com/satori/go.uuid"
)
// AuthorizeTokenGenDefault is the default authorization token generator
type AuthorizeTokenGenDefault struct {
}
func removePadding(token string) string {
return strings.TrimRight(token, "=")
}
// GenerateAuthorizeToken generates a base64-encoded UUID code
func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error) {
token := uuid.NewV4()
return removePadding(base64.URLEncoding.EncodeToString(token.Bytes())), nil
}
// AccessTokenGenDefault is the default authorization token generator
type AccessTokenGenDefault struct {
}
// GenerateAccessToken generates base64-encoded UUID access and refresh tokens
func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) {
token := uuid.NewV4()
accesstoken = removePadding(base64.URLEncoding.EncodeToString(token.Bytes()))
if generaterefresh {
rtoken := uuid.NewV4()
refreshtoken = removePadding(base64.URLEncoding.EncodeToString(rtoken.Bytes()))
}
return
}
|
Make delete command message more meaningful
|
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
self._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = (
"Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
)
def handle(self, *args, **kwargs):
instance = FindAndDeleteCasesUsingCreationTime()
cases = instance.get_eligible_cases()
if len(args) == 0:
print("Number of cases to be deleted: " + str(cases.count()))
elif args[0] == "test_find":
return cases
elif args[0] == "delete":
instance.run()
|
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
self._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = (
"Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
)
def handle(self, *args, **kwargs):
instance = FindAndDeleteCasesUsingCreationTime()
cases = instance.get_eligible_cases()
if len(args) == 0:
print(cases.count())
elif args[0] == "test_find":
return cases
elif args[0] == "delete":
instance.run()
|
Use lesson names as menu link titles
|
var classNames = require('classnames')
var React = require('react')
require('./LessonMenu.css')
var LessonMenu = React.createClass({
handleSelectLesson(index) {
this.props.selectLesson(index)
},
render() {
var {lessons, currentLessonIndex} = this.props
return <div className="LessonMenu">
{lessons.map((lesson, index) => {
var isActive = index === currentLessonIndex
var linkClassName = classNames('LessonMenu__lesson', {
'LessonMenu__lesson--active': isActive
})
return <a className={linkClassName}
onClick={!isActive && this.handleSelectLesson.bind(this, index)}
title={lesson.name}>
<div>
<span className="LessonMenu__number">{index + 1}</span>
</div>
</a>
})}
</div>
}
})
module.exports = LessonMenu
|
var classNames = require('classnames')
var React = require('react')
require('./LessonMenu.css')
var LessonMenu = React.createClass({
handleSelectLesson(index) {
this.props.selectLesson(index)
},
render() {
var {lessons, currentLessonIndex} = this.props
return <div className="LessonMenu">
{lessons.map((lesson, index) => {
var isActive = index === currentLessonIndex
var linkClassName = classNames('LessonMenu__lesson', {
'LessonMenu__lesson--active': isActive
})
return <a className={linkClassName}
onClick={!isActive && this.handleSelectLesson.bind(this, index)}>
<div>
<span className="LessonMenu__number">{index + 1}</span>
</div>
</a>
})}
</div>
}
})
module.exports = LessonMenu
|
Update version number to 0.1.10.dev0.
PiperOrigin-RevId: 202663603
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.1.10.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.1.9'
|
Refactor for using the new Response class
|
<?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\RetrieveAndRank\V1\RetrieveAndRankService;
class RetrieveAndRankV1Test extends AbstractTestCase
{
/**
* @var RetrieveAndRankService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new RetrieveAndRankService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/retrieve-and-rank/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v1',
$this->service->getVersion()
);
}
public function test_can_list_solr_clusters()
{
$response = $this->service->listSolrClusters();
$this->assertArrayHasKey('clusters', json_decode($response->getContent(), true));
}
}
|
<?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\RetrieveAndRank\V1\RetrieveAndRankService;
class RetrieveAndRankV1Test extends AbstractTestCase
{
/**
* @var RetrieveAndRankService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new RetrieveAndRankService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/retrieve-and-rank/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v1',
$this->service->getVersion()
);
}
public function test_can_list_solr_clusters()
{
$response = $this->service->listSolrClusters();
$this->assertArrayHasKey('clusters', json_decode($response->getBody()->getContents(), true));
}
}
|
Add an extra blank line
|
function autosaveSnippet () {
var $url = $('.edit_snippet')[0].action;
var $data = $('.edit_snippet').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
function autosaveStory () {
var $url = $('.edit_story')[0].action;
var $data = $('.edit_story').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
$(document).ready(function (){
var autosaveOnFocus;
$('.redactor_editor').focus(function() {
if ($('.edit_snippet').length !== 0) {
autosaveOnFocus = setInterval(autosaveSnippet, 5000);
}
else {
autosaveOnFocus = setInterval(autosaveStory, 5000);
}
});
$('.redactor_editor').blur(function() {
console.log(autosaveOnFocus);
clearInterval(autosaveOnFocus);
console.log(autosaveOnFocus);
})
});
|
function autosaveSnippet () {
var $url = $('.edit_snippet')[0].action;
var $data = $('.edit_snippet').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
function autosaveStory () {
var $url = $('.edit_story')[0].action;
var $data = $('.edit_story').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
$(document).ready(function (){
var autosaveOnFocus;
$('.redactor_editor').focus(function() {
if ($('.edit_snippet').length !== 0) {
autosaveOnFocus = setInterval(autosaveSnippet, 5000);
}
else {
autosaveOnFocus = setInterval(autosaveStory, 5000);
}
});
$('.redactor_editor').blur(function() {
console.log(autosaveOnFocus);
clearInterval(autosaveOnFocus);
console.log(autosaveOnFocus);
})
});
|
Fix document query for existing documents
|
from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import logging
from scrapi import events
from scrapi.processing.base import BaseProcessor
from api.webview.models import Document
logger = logging.getLogger(__name__)
class PostgresProcessor(BaseProcessor):
NAME = 'postgres'
@events.logged(events.PROCESSING, 'raw.postgres')
def process_raw(self, raw_doc):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.raw = raw_doc.attributes
document.save()
@events.logged(events.PROCESSING, 'normalized.postgres')
def process_normalized(self, raw_doc, normalized):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.normalized = normalized.attributes
document.providerUpdatedDateTime = normalized['providerUpdatedDateTime']
document.save()
def _get_by_source_id(self, model, source, docID):
try:
return Document.objects.filter(source=source, docID=docID)[0]
except IndexError:
return None
|
from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
# import django
import logging
from scrapi import events
from scrapi.processing.base import BaseProcessor
from api.webview.models import Document
# django.setup()
logger = logging.getLogger(__name__)
class PostgresProcessor(BaseProcessor):
NAME = 'postgres'
@events.logged(events.PROCESSING, 'raw.postgres')
def process_raw(self, raw_doc):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.raw = raw_doc.attributes
document.save()
@events.logged(events.PROCESSING, 'normalized.postgres')
def process_normalized(self, raw_doc, normalized):
source, docID = raw_doc['source'], raw_doc['docID']
document = self._get_by_source_id(Document, source, docID) or Document(source=source, docID=docID)
document.normalized = normalized.attributes
document.providerUpdatedDateTime = normalized['providerUpdatedDateTime']
document.save()
def _get_by_source_id(self, model, source, docID):
return Document.objects.filter(source=source, docID=docID)[0]
|
Add correct localhost port to test
|
//test-name.spec.js
/*
Acceptance Criteria:
I can:
-Navigate to this page according to the site map url
-See that the page looks like the mockup
-View the page at different resolutions and the content is laid out logically
*/
/* global casper */
casper.test.begin('Contact page navigates to home page ', 2,
function suite(test) {
casper.start('http://localhost:3000/contact.html', function () {
test.assertTitle('Contact Us', 'contact us page title good');
test.assertExists('a[href="index.html"]', 'link found');
});
//casper.start('http://localhost:3000/contact.html', function(){
casper.then(function () {
this.click('a[href="index.html"]');
});
casper.run(function () {
test.done();
});
});
|
//test-name.spec.js
/*
Acceptance Criteria:
I can:
-Navigate to this page according to the site map url
-See that the page looks like the mockup
-View the page at different resolutions and the content is laid out logically
*/
/* global casper */
casper.test.begin('Contact page navigates to home page ', 2,
function suite(test) {
casper.start('http://localhost:63342/fullstack-project-01/neukinnis/client/contactus.html', function () {
test.assertTitle('Contact Us', 'contact us page title good');
test.assertExists('a[href="index.html"]', 'link found');
});
//casper.start('http://localhost:3000/contact.html', function(){
casper.then(function () {
this.click('a[href="index.html"]');
});
casper.run(function () {
test.done();
});
});
|
Fix handler module path check, was broken for module not found in handler
|
'use strict'
module.exports = class InProcessRunner {
constructor(functionName, handlerPath, handlerName) {
this._functionName = functionName
this._handlerName = handlerName
this._handlerPath = handlerPath
}
run(event, context, callback) {
// check if the handler module path exists
if (!require.resolve(this._handlerPath)) {
throw new Error(
`Could not find handler module '${this._handlerPath}' for function '${this._functionName}'.`,
)
}
// lazy load handler with first usage
const handler = require(this._handlerPath)[this._handlerName] // eslint-disable-line
if (typeof handler !== 'function') {
throw new Error(
`offline: handler '${this._handlerName}' in ${this._handlerPath} is not a function`,
)
}
return handler(event, context, callback)
}
}
|
'use strict'
const serverlessLog = require('../serverlessLog.js')
module.exports = class InProcessRunner {
constructor(functionName, handlerPath, handlerName) {
this._functionName = functionName
this._handlerName = handlerName
this._handlerPath = handlerPath
}
run(event, context, callback) {
// TODO error handling? when module and/or function is not found
// lazy load handler with first usage
let handler
try {
handler = require(this._handlerPath)[this._handlerName] // eslint-disable-line
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
serverlessLog.errorLog(
`Could not find handler module '${this._handlerPath}' for function '${this._functionName}'.`,
)
}
throw err
}
if (typeof handler !== 'function') {
throw new Error(
`offline: handler '${this._handlerName}' in ${this._handlerPath} is not a function`,
)
}
return handler(event, context, callback)
}
}
|
Fix update-schema JSON for Storyboard 2
|
import fs from 'fs-extra';
import path from 'path';
import { addListener, mainStory, chalk } from 'storyboard';
import consoleListener from 'storyboard/lib/listeners/console';
import Promise from 'bluebird';
import * as gqlServer from './gqlServer';
addListener(consoleListener);
const outputPath = path.join(__dirname, '../common/');
gqlServer.init();
Promise.resolve()
.then(() => {
mainStory.info('gqlUpdate', 'Introspecting...');
return gqlServer.runIntrospect();
})
.then(result => {
let filePath = path.join(outputPath, 'gqlSchema.json');
mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`);
fs.writeFileSync(filePath, JSON.stringify(result, null, 2));
filePath = path.join(outputPath, 'gqlSchema.graphql');
mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`);
fs.writeFileSync(filePath, gqlServer.getSchemaShorthand());
mainStory.info('gqlUpdate', 'Done!');
});
|
import fs from 'fs-extra';
import path from 'path';
import { mainStory, chalk } from 'storyboard';
import Promise from 'bluebird';
import * as gqlServer from './gqlServer';
const outputPath = path.join(__dirname, '../common/');
gqlServer.init();
Promise.resolve()
.then(() => {
mainStory.info('gqlUpdate', 'Introspecting...');
return gqlServer.runIntrospect();
})
.then(result => {
let filePath = path.join(outputPath, 'gqlSchema.json');
mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`);
fs.writeFileSync(filePath, JSON.stringify(result, null, 2));
filePath = path.join(outputPath, 'gqlSchema.graphql');
mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`);
fs.writeFileSync(filePath, gqlServer.getSchemaShorthand());
mainStory.info('gqlUpdate', 'Done!');
});
|
Fix sniffer test, rename stop to delete
|
from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint)
self.source_ip = '147.102.239.229'
self.destination_host = 'dionyziz.com'
@patch('breach.sniffer.requests')
def test_sniffer_start(self, requests):
self.sniffer.start(self.source_ip, self.destination_host)
self.assertTrue(requests.post.called)
@patch('breach.sniffer.requests')
def test_sniffer_read(self, requests):
self.sniffer.read(self.source_ip, self.destination_host)
self.assertTrue(requests.get.called)
@patch('breach.sniffer.requests')
def test_sniffer_delete(self, requests):
self.sniffer.delete(self.source_ip, self.destination_host)
self.assertTrue(requests.post.called)
|
from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint)
self.source_ip = '147.102.239.229'
self.destination_host = 'dionyziz.com'
@patch('breach.sniffer.requests')
def test_sniffer_start(self, requests):
self.sniffer.start(self.source_ip, self.destination_host)
self.assertTrue(requests.post.called)
@patch('breach.sniffer.requests')
def test_sniffer_read(self, requests):
self.sniffer.read(self.source_ip, self.destination_host)
self.assertTrue(requests.get.called)
@patch('breach.sniffer.requests')
def test_sniffer_stop(self, requests):
self.sniffer.stop(self.source_ip, self.destination_host)
self.assertTrue(requests.post.called)
|
Fix documentation example showing use of ReadStruct
Logic flow was inverted. Example was printing the result when an
error was occurring and using panic when no error.
|
package xlsx
import "fmt"
func ExampleRow_ReadStruct() {
//example type
type structTest struct {
IntVal int `xlsx:"0"`
StringVal string `xlsx:"1"`
FloatVal float64 `xlsx:"2"`
IgnoredVal int `xlsx:"-"`
BoolVal bool `xlsx:"4"`
}
structVal := structTest{
IntVal: 16,
StringVal: "heyheyhey :)!",
FloatVal: 3.14159216,
IgnoredVal: 7,
BoolVal: true,
}
//create a new xlsx file and write a struct
//in a new row
f := NewFile()
sheet, _ := f.AddSheet("TestRead")
row := sheet.AddRow()
row.WriteStruct(&structVal, -1)
//read the struct from the same row
readStruct := &structTest{}
err := row.ReadStruct(readStruct)
if err != nil {
panic(err)
} else {
fmt.Println(readStruct)
}
}
|
package xlsx
import "fmt"
func ExampleRow_ReadStruct() {
//example type
type structTest struct {
IntVal int `xlsx:"0"`
StringVal string `xlsx:"1"`
FloatVal float64 `xlsx:"2"`
IgnoredVal int `xlsx:"-"`
BoolVal bool `xlsx:"4"`
}
structVal := structTest{
IntVal: 16,
StringVal: "heyheyhey :)!",
FloatVal: 3.14159216,
IgnoredVal: 7,
BoolVal: true,
}
//create a new xlsx file and write a struct
//in a new row
f := NewFile()
sheet, _ := f.AddSheet("TestRead")
row := sheet.AddRow()
row.WriteStruct(&structVal, -1)
//read the struct from the same row
readStruct := &structTest{}
err := row.ReadStruct(readStruct)
if err != nil {
fmt.Println(readStruct)
} else {
panic(err)
}
}
|
Migrate implementation to Java 8
|
package org.mkonrad.fizzbuzz;
import java.io.PrintStream;
import java.util.stream.IntStream;
/**
* @author Markus Konrad
*/
public final class FizzBuzz {
private final PrintStream printStream;
public FizzBuzz(PrintStream printStream) {
this.printStream = printStream;
}
public final void run(int numberOfRounds){
if (numberOfRounds < 1) {
printStream.println("Please specify a positive value for the parameter \"numberOfRounds\"");
return;
}
IntStream.range(1, numberOfRounds + 1)
.mapToObj(i -> {
if (i % 3 == 0) {
if (i % 5 == 0) {
return "FizzBuzz";
}
return "Fizz";
}
if (i % 5 == 0) {
return "Buzz";
}
return String.valueOf(i);
})
.forEach(printStream::println);
}
public static void main(String[] args) {
new FizzBuzz(System.out).run(100);
}
}
|
package org.mkonrad.fizzbuzz;
import java.io.PrintStream;
import java.util.stream.IntStream;
/**
* @author Markus Konrad
*/
public final class FizzBuzz {
private final PrintStream printStream;
public FizzBuzz(PrintStream printStream) {
this.printStream = printStream;
}
public final void run(int numberOfRounds){
if (numberOfRounds < 1) {
printStream.println("Please specify a positive value for the parameter \"numberOfRounds\"");
return;
}
IntStream.range(1, numberOfRounds + 1).mapToObj(i -> {
if (i % 3 == 0) {
if (i % 5 == 0) {
return "FizzBuzz";
}
return "Fizz";
}
if (i % 5 == 0) {
return "Buzz";
}
return String.valueOf(i);
}).forEach(printStream::println);
}
public static void main(String[] args) {
new FizzBuzz(System.out).run(100);
}
}
|
Add description to channel response
|
<?php
/**
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Transformers\API\Chat;
use App\Models\Event;
use League\Fractal;
use App\Models\Chat\Channel;
class ChannelTransformer extends Fractal\TransformerAbstract
{
public function transform(Channel $channel)
{
return [
'channel_id' => $channel->channel_id,
'name' => $channel->name,
'description' => $channel->description,
'type' => $channel->type,
];
}
}
|
<?php
/**
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Transformers\API\Chat;
use App\Models\Event;
use League\Fractal;
use App\Models\Chat\Channel;
class ChannelTransformer extends Fractal\TransformerAbstract
{
public function transform(Channel $channel)
{
return [
'channel_id' => $channel->channel_id,
'name' => $channel->name,
'type' => $channel->type,
];
}
}
|
Correct the namespace in the template file.
|
<?php
class <CLASS> extends Tivoh\Torm\Model {
const table = '<TABLE>';
const primaryKey = '<PRIMARY KEY>';
<FIELD>
protected $<PROPERTY NAME>;
</FIELD>
protected static $fields = [
<FIELD NAMES>
];
<GETTER>
public function get<METHOD NAME>() {
return $this-><PROPERTY NAME>;
}
</GETTER>
<FOREIGN>
public function get<METHOD NAME>() {
if ($this-><PROPERTY NAME> == null) {
$objects = <FOREIGN CLASS>::find(['<FOREIGN KEY>' => $this->get<BY METHOD NAME>()], 1);
if ($objects) {
$this-><PROPERTY NAME> = $objects[0];
}
}
return $this-><PROPERTY NAME>;
}
</FOREIGN>
<SETTER>
public function set<METHOD NAME>($value) {
$this-><PROPERTY NAME> = $value;
}
</SETTER>
<FINDER>
public static function findOneBy<METHOD NAME>($value) {
$objects = static::find(['<FIELD NAME>' => $value], 1);
if ($objects) {
return $objects[0];
}
}
public static function findBy<METHOD NAME>($value) {
return static::find(['<FIELD NAME>' => $value]);
}
</FINDER>
}
|
<?php
class <CLASS> extends Torm\Model {
const table = '<TABLE>';
const primaryKey = '<PRIMARY KEY>';
<FIELD>
protected $<PROPERTY NAME>;
</FIELD>
protected static $fields = [
<FIELD NAMES>
];
<GETTER>
public function get<METHOD NAME>() {
return $this-><PROPERTY NAME>;
}
</GETTER>
<FOREIGN>
public function get<METHOD NAME>() {
if ($this-><PROPERTY NAME> == null) {
$objects = <FOREIGN CLASS>::find(['<FOREIGN KEY>' => $this->get<BY METHOD NAME>()], 1);
if ($objects) {
$this-><PROPERTY NAME> = $objects[0];
}
}
return $this-><PROPERTY NAME>;
}
</FOREIGN>
<SETTER>
public function set<METHOD NAME>($value) {
$this-><PROPERTY NAME> = $value;
}
</SETTER>
<FINDER>
public static function findOneBy<METHOD NAME>($value) {
$objects = static::find(['<FIELD NAME>' => $value], 1);
if ($objects) {
return $objects[0];
}
}
public static function findBy<METHOD NAME>($value) {
return static::find(['<FIELD NAME>' => $value]);
}
</FINDER>
}
|
Use classic array declaration instead of the short one
Use this notation to be compatible with php >=5.3.3
|
<?php
namespace Payum\PayumModule\Registry;
use Payum\PayumModule\Action\GetHttpRequestAction;
use Payum\PayumModule\Options\PayumOptions;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class RegistryFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var PayumOptions $options */
$options = $serviceLocator->get('payum.options');
$registry = new ServiceLocatorAwareRegistry(
$options->getGateways(),
$options->getStorages(),
array()
);
//TODO: quick fix. we should avoid early init of services. has to be reworked to be lazy
$registry->setServiceLocator($serviceLocator);
$getHttpRequestAction = new GetHttpRequestAction($serviceLocator);
foreach ($registry->getGateways() as $gateway) {
$gateway->addAction($getHttpRequestAction);
}
return $registry;
}
}
|
<?php
namespace Payum\PayumModule\Registry;
use Payum\PayumModule\Action\GetHttpRequestAction;
use Payum\PayumModule\Options\PayumOptions;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class RegistryFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var PayumOptions $options */
$options = $serviceLocator->get('payum.options');
$registry = new ServiceLocatorAwareRegistry(
$options->getGateways(),
$options->getStorages(),
[]
);
//TODO: quick fix. we should avoid early init of services. has to be reworked to be lazy
$registry->setServiceLocator($serviceLocator);
$getHttpRequestAction = new GetHttpRequestAction($serviceLocator);
foreach ($registry->getGateways() as $gateway) {
$gateway->addAction($getHttpRequestAction);
}
return $registry;
}
}
|
Remove Email module - missed tests
|
<?php namespace CodeIgniter\Config;
use Config\Email;
class ConfigTest extends \CIUnitTestCase
{
public function testCreateSingleInstance()
{
$Config = Config::get('Format', false);
$NamespaceConfig = Config::get('Config\\Format', false);
$this->assertInstanceOf(Format::class, $Config);
$this->assertInstanceOf(Format::class, $NamespaceConfig);
}
public function testCreateInvalidInstance()
{
$Config = Config::get('gfnusvjai', false);
$this->assertNull($Config);
}
public function testCreateSharedInstance()
{
$Config = Config::get('Format' );
$Config2 = Config::get('Config\\Format');
$this->assertTrue($Config === $Config2);
}
public function testCreateNonConfig()
{
$Config = Config::get('Constants', false);
$this->assertNull($Config);
}
}
|
<?php namespace CodeIgniter\Config;
use Config\Email;
class ConfigTest extends \CIUnitTestCase
{
public function testCreateSingleInstance()
{
$Config = Config::get('Format', false);
$NamespaceConfig = Config::get('Config\\Format', false);
$this->assertInstanceOf(Email::class, $Config);
$this->assertInstanceOf(Email::class, $NamespaceConfig);
}
public function testCreateInvalidInstance()
{
$Config = Config::get('gfnusvjai', false);
$this->assertNull($Config);
}
public function testCreateSharedInstance()
{
$Config = Config::get('Format' );
$Config2 = Config::get('Config\\Format');
$this->assertTrue($Config === $Config2);
}
public function testCreateNonConfig()
{
$Config = Config::get('Constants', false);
$this->assertNull($Config);
}
}
|
[Form] Add options with_minutes to DateTimeType & TimeType
|
<?php if ($widget == 'single_text'): ?>
<?php echo $view['form']->block($form, 'form_widget_simple'); ?>
<?php else: ?>
<div <?php echo $view['form']->block($form, 'widget_container_attributes') ?>>
<?php
// There should be no spaces between the colons and the widgets, that's why
// this block is written in a single PHP tag
echo $view['form']->widget($form['hour'], array('attr' => array('size' => 1)));
if ($with_minutes) {
echo ':';
echo $view['form']->widget($form['minute'], array('attr' => array('size' => 1)));
}
if ($with_seconds) {
echo ':';
echo $view['form']->widget($form['second'], array('attr' => array('size' => 1)));
}
?>
</div>
<?php endif ?>
|
<?php if ($widget == 'single_text'): ?>
<?php echo $view['form']->block($form, 'form_widget_simple'); ?>
<?php else: ?>
<div <?php echo $view['form']->block($form, 'widget_container_attributes') ?>>
<?php
// There should be no spaces between the colons and the widgets, that's why
// this block is written in a single PHP tag
echo $view['form']->widget($form['hour'], array('attr' => array('size' => 1)));
echo ':';
echo $view['form']->widget($form['minute'], array('attr' => array('size' => 1)));
if ($with_seconds) {
echo ':';
echo $view['form']->widget($form['second'], array('attr' => array('size' => 1)));
}
?>
</div>
<?php endif ?>
|
Check for any overflow scroll style on parent node.
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* @fileOverview Find scroll parent
*/
exports.default = function (node) {
if (!node) {
return document.documentElement;
}
var excludeStaticParent = node.style.position === 'absolute';
var overflowRegex = /(scroll|auto)/;
var parent = node;
while (parent) {
if (!parent.parentNode) {
return node.ownerDocument || document.documentElement;
}
var style = window.getComputedStyle(parent);
var position = style.position;
var overflow = style.overflow;
var overflowX = style['overflow-x'];
var overflowY = style['overflow-y'];
if (position === 'static' && excludeStaticParent) {
parent = parent.parentNode;
continue;
}
if (overflowRegex.test(overflow) || overflowRegex.test(overflowX) || overflowRegex.test(overflowY)) {
return parent;
}
parent = parent.parentNode;
}
return node.ownerDocument || node.documentElement || document.documentElement;
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* @fileOverview Find scroll parent
*/
exports.default = function (node) {
if (!node) {
return document.documentElement;
}
var excludeStaticParent = node.style.position === 'absolute';
var overflowRegex = /(scroll|auto)/;
var parent = node;
while (parent) {
if (!parent.parentNode) {
return node.ownerDocument || document.documentElement;
}
var style = window.getComputedStyle(parent);
var position = style.position;
var overflow = style.overflow;
var overflowX = style['overflow-x'];
var overflowY = style['overflow-y'];
if (position === 'static' && excludeStaticParent) {
parent = parent.parentNode;
continue;
}
if (overflowRegex.test(overflow) && overflowRegex.test(overflowX) && overflowRegex.test(overflowY)) {
return parent;
}
parent = parent.parentNode;
}
return node.ownerDocument || node.documentElement || document.documentElement;
};
|
Improve error logging during authentication
|
"use strict";
const github = require("simple-github");
const auth = require("./auth");
class GithubAPI {
constructor(pr, options) {
this.pr = pr;
this.options = options || {};
}
requestAuthHeaders() {
return auth(this.pr.installation, { debug: this.options.debug });
}
setAuthHeaders(headers) {
this._gh = github({ headers: headers, debug: this.options.debug });
}
request(url, options, body) {
return this._gh.request(url, this.getRequestOptions(options, body));
}
getRequestOptions(_options, body) {
_options = _options || {};
let options = {
owner: this.pr.owner,
repo: this.pr.repo,
number: this.pr.number
};
for (var k in _options) {
options[k] = _options[k];
}
if (body) {
options.body = body;
}
return options;
}
}
module.exports = GithubAPI;
|
"use strict";
const github = require("simple-github");
const auth = require("./auth");
class GithubAPI {
constructor(pr, options) {
this.pr = pr;
this.options = options || {};
}
requestAuthHeaders() {
return auth(this.pr.installation);
}
setAuthHeaders(headers) {
this._gh = github({ headers: headers, debug: this.options.debug });
}
request(url, options, body) {
return this._gh.request(url, this.getRequestOptions(options, body));
}
getRequestOptions(_options, body) {
_options = _options || {};
let options = {
owner: this.pr.owner,
repo: this.pr.repo,
number: this.pr.number
};
for (var k in _options) {
options[k] = _options[k];
}
if (body) {
options.body = body;
}
return options;
}
}
module.exports = GithubAPI;
|
Fix deprecated Twig class usage
|
<?php
namespace Devture\Bundle\UserBundle\Twig;
use Devture\Bundle\UserBundle\AccessControl\AccessControl;
class UserExtension extends \Twig_Extension {
private $control;
public function __construct(AccessControl $control) {
$this->control = $control;
}
public function getName() {
return 'devture_user_user_extension';
}
public function getFunctions() {
return array(
new \Twig_SimpleFunction('get_user', array($this, 'getUser')),
new \Twig_SimpleFunction('is_logged_in', array($this, 'isLoggedIn')),
new \Twig_SimpleFunction('is_granted', array($this, 'isGranted')),
);
}
/**
* @return \Devture\Bundle\UserBundle\Model\User|NULL
*/
public function getUser() {
return $this->control->getUser();
}
/**
* @return boolean
*/
public function isLoggedIn() {
return $this->control->isLoggedIn();
}
/**
* @param string $role
* @return boolean
*/
public function isGranted($role) {
return $this->control->isGranted($role);
}
}
|
<?php
namespace Devture\Bundle\UserBundle\Twig;
use Devture\Bundle\UserBundle\AccessControl\AccessControl;
class UserExtension extends \Twig_Extension {
private $control;
public function __construct(AccessControl $control) {
$this->control = $control;
}
public function getName() {
return 'devture_user_user_extension';
}
public function getFunctions() {
return array(
'get_user' => new \Twig_Function_Method($this, 'getUser'),
'is_logged_in' => new \Twig_Function_Method($this, 'isLoggedIn'),
'is_granted' => new \Twig_Function_Method($this, 'isGranted'),
);
}
/**
* @return \Devture\Bundle\UserBundle\Model\User|NULL
*/
public function getUser() {
return $this->control->getUser();
}
/**
* @return boolean
*/
public function isLoggedIn() {
return $this->control->isLoggedIn();
}
/**
* @param string $role
* @return boolean
*/
public function isGranted($role) {
return $this->control->isGranted($role);
}
}
|
Update up to changes in memoizee package
|
'use strict';
var noop = require('es5-ext/function/noop')
, assign = require('es5-ext/object/assign')
, memoize = require('memoizee')
, ee = require('event-emitter')
, eePipe = require('event-emitter/pipe')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.__memoized__) return fn;
memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = eePipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.deleteRef.apply(this, args)) watcher.close();
};
return emitter;
};
factory.clear = memoized.delete;
factory.__memoized__ = true;
return factory;
};
|
'use strict';
var noop = require('es5-ext/function/noop')
, assign = require('es5-ext/object/assign')
, memoize = require('memoizee')
, ee = require('event-emitter')
, eePipe = require('event-emitter/pipe')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.memoized) return fn;
memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = eePipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) watcher.close();
};
return emitter;
};
factory.clear = memoized.clear;
factory.memoized = true;
return factory;
};
|
Change template for the ranking route
|
var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
},
fastRender: true
});
Router.route('/ranking', {
name: 'rankingWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/championship', {
name: 'ChampionshipWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/search', {
name: 'search',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/account', {
name: 'accountWrapper',
fastRender: true
});
|
var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'home',
waitOn: function() {
return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
},
fastRender: true
});
Router.route('/ranking', {
name: 'ranking',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/championship', {
name: 'ChampionshipWrapper',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/search', {
name: 'search',
/*waitOn: function() {
return subscriptions.subscribe('');
},*/
fastRender: true
});
Router.route('/account', {
name: 'accountWrapper',
fastRender: true
});
|
Fix bug on account update
|
var mongo = require('./mongo');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var uuid = require('uuid');
passport.use(new FacebookStrategy({
clientID: process.env.FB_APP_ID,
clientSecret: process.env.FB_APP_SECRET,
callbackURL: 'http://localhost:18000/auth/facebook/callback',
enableProof: false
}, function (accessToken, refreshToken, profile, done) {
mongo.Account.findOneAndUpdate({
facebookId: profile.id
}, {
displayName: profile.displayName
}, {
upsert: true
}).exec().then(function (account) {
if (!account.id) {
account.id = uuid.v4();
}
return account.psave().then(function () {
done(null, account);
});
}, function (err) {
done(err);
});
}));
module.exports = passport;
|
var mongo = require('./mongo');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var uuid = require('uuid');
passport.use(new FacebookStrategy({
clientID: process.env.FB_APP_ID,
clientSecret: process.env.FB_APP_SECRET,
callbackURL: 'http://localhost:18000/auth/facebook/callback',
enableProof: false
}, function (accessToken, refreshToken, profile, done) {
mongo.Account.findOneAndUpdate({
facebookId: profile.id
}, {
id: uuid.v4(),
displayName: profile.displayName
}, {
upsert: true
}).exec().then(function (account) {
done(null, account);
}, function (err) {
done(err);
});
}));
module.exports = passport;
|
demo: Put the nested ThemeProvider inside a parent Consumer (still works!)
|
import { createElement, Component, createContext, Fragment } from 'ceviche';
const { Provider, Consumer } = createContext();
class ThemeProvider extends Component {
state = {
value: this.props.value
};
componentDidMount() {
setTimeout(() => {
this.setState({
value: this.props.next
});
}, 3000);
}
render() {
console.log(this.state);
return <Provider value={this.state.value}>
{this.props.children}
</Provider>
}
}
class Child extends Component {
shouldComponentUpdate() {
//return false;
}
render() {
return <>
<p>ok this is cool</p>
{this.props.children}
</>
}
}
export default class extends Component {
render(props, state) {
return (
<ThemeProvider value="blue" next="red">
<Child>
<Consumer>
{data => (
<div>
<p>current theme: {data}</p>
<ThemeProvider value="black" next="white">
<Consumer>
{data => <p>current sub theme: {data}</p>}
</Consumer>
</ThemeProvider>
</div>
)}
</Consumer>
</Child>
</ThemeProvider>
)
}
}
|
import { createElement, Component, createContext, Fragment } from 'ceviche';
const { Provider, Consumer } = createContext();
class ThemeProvider extends Component {
state = {
value: this.props.value
};
componentDidMount() {
setTimeout(() => {
this.setState({
value: this.props.next
});
}, 3000);
}
render() {
console.log(this.state);
return <Provider value={this.state.value}>
{this.props.children}
</Provider>
}
}
class Child extends Component {
shouldComponentUpdate() {
//return false;
}
render() {
return <>
<p>ok this is cool</p>
{this.props.children}
</>
}
}
export default class extends Component {
render(props, state) {
return (
<ThemeProvider value="blue" next="red">
<Child>
<Consumer>
{data => <p>current theme: {data}</p>}
</Consumer>
<ThemeProvider value="black" next="white">
<Consumer>
{data => <p>current sub theme: {data}</p>}
</Consumer>
</ThemeProvider>
</Child>
</ThemeProvider>
)
}
}
|
Fix typo in install bundle script
|
'use strict';
const fs = require('fs');
const cp = require('child_process');
const os = require('os');
const commander = require('commander');
const parse = require('git-url-parse');
const gitRoot = cp.execSync('git rev-parse --show-toplevel').toString('utf8').trim();
process.chdir(gitRoot);
commander.command('install-bundle <remote url>');
commander.parse(process.argv);
if (commander.args.length < 1) {
console.error(`Syntax: ${process.argv0} <remote url>`);
process.exit(0);
}
const [remote] = commander.args;
if (fs.existsSync(gitRoot + `/bundles/${remote}`)) {
console.error('Bundle already installed');
process.exit(0);
}
try {
cp.execSync(`git ls-remote ${remote}`);
} catch (err) {
process.exit(0);
}
const { name } = parse(remote);
console.log("Adding bundle...");
cp.execSync(`git submodule add ${remote} bundles/${name}`);
console.log("Installing deps...")
if (fs.existsSync(`${gitRoot}/bundles/${name}/package.json`)) {
const npmCmd = os.platform().startsWith('win') ? 'npm.cmd' : 'npm';
cp.spawnSync(npmCmd, ['install', '--no-audit'], {
cwd: `${gitRoot}/bundles/${name}`
});
}
console.log(`Bundle installed. Commit the bundle with: git commit -m \"Added ${name} bundle\"");
|
'use strict';
const fs = require('fs');
const cp = require('child_process');
const os = require('os');
const commander = require('commander');
const parse = require('git-url-parse');
const gitRoot = cp.execSync('git rev-parse --show-toplevel').toString('utf8').trim();
process.chdir(gitRoot);
commander.command('install-bundle <remote url>');
commander.parse(process.argv);
if (commander.args.length < 1) {
console.error(`Syntax: ${process.argv0} <remote url>`);
process.exit(0);
}
const [remote] = commander.args;
if (fs.existsSync(gitRoot + `/bundles/${remote}`)) {
console.error('Bundle already installed');
process.exit(0);
}
try {
cp.execSync(`git ls-remote ${remote}`);
} catch (err) {
process.exit(0);
}
const { name } = parse(remote);
console.log("Adding bundle...");
cp.execSync(`git submodule add ${remote} bundles/${name}`);
console.log("Installing deps...")
if (fs.existsSync(`${gitRoot}/bundles/${name}/package.json`)) {
const npmCmd = os.platform().startsWith('win') ? 'npm.cmd' : 'npm';
cp.spawnSync(npmCmd, ['install', '--no-audit'], {
cwd: `${gitRoot}/bundles/${name}`
});
}
console.log("Bundle installed. Commit the bundle with `git commit -m \"Added ${name} bundle\"`");
|
Fix spark mode (faulty shutdown conditional logic)
|
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
info['cleanup_spark'] = True
def pyspark_run_cleanup(event):
if event.info.get('cleanup_spark'):
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
|
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
def pyspark_run_cleanup(event):
if SC_KEY in event.info['kwargs']:
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
|
Fix interface that cannot reference to self
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Db\Adapter;
use Zend\Db\ResultSet;
/**
*
* @property Driver\DriverInterface $driver
* @property Platform\PlatformInterface $platform
*/
interface AdapterInterface
{
/**
* @return Driver\DriverInterface
*/
public function getDriver();
/**
* @return Platform\PlatformInterface
*/
public function getPlatform();
/**
* query() is a convenience function
*
* @param string $sql
* @param string|array|ParameterContainer $parametersOrQueryMode
* @param \Zend\Db\ResultSet\ResultSetInterface $resultPrototype
* @throws Exception\InvalidArgumentException
* @return Driver\StatementInterface|ResultSet\ResultSet
*/
public function query($sql, $parametersOrQueryMode, ResultSet\ResultSetInterface $resultPrototype = null);
}
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Db\Adapter;
use Zend\Db\ResultSet;
/**
*
* @property Driver\DriverInterface $driver
* @property Platform\PlatformInterface $platform
*/
interface AdapterInterface
{
/**
* @return Driver\DriverInterface
*/
public function getDriver();
/**
* @return Platform\PlatformInterface
*/
public function getPlatform();
/**
* query() is a convenience function
*
* @param string $sql
* @param string|array|ParameterContainer $parametersOrQueryMode
* @param \Zend\Db\ResultSet\ResultSetInterface $resultPrototype
* @throws Exception\InvalidArgumentException
* @return Driver\StatementInterface|ResultSet\ResultSet
*/
public function query($sql, $parametersOrQueryMode = self::QUERY_MODE_PREPARE, ResultSet\ResultSetInterface $resultPrototype = null);
}
|
Add a property to set the default enablement
Set '-Dorg.showshortcuts.enabled=false' to e.g. disable the tool by
default.
|
package org.showshortcuts.internal;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* Initializer for shortcut visualizer preferences
*
* @author d031150
*/
public class ShortcutPreferenceInitializer extends AbstractPreferenceInitializer {
public static final String PREF_KEY_SHORTCUTS_ENABLED = "enabled"; //$NON-NLS-1$
private static final String PREF_DEFAULT_SHORTCUTS_ENABLED = Activator.PLUGIN_ID + "." + PREF_KEY_SHORTCUTS_ENABLED; //$NON-NLS-1$
public static final String PREF_KEY_MOUSE_TRIGGER_ENABLED = "enabled_mouseTrigger"; //$NON-NLS-1$
public static final String PREF_KEY_TIME_TO_CLOSE = "timeToClose"; //$NON-NLS-1$
public static final String PREF_KEY_SHOW_DESCRIPTION = "showCommandDescription"; //$NON-NLS-1$
static final String THEME_CATEGORY = Activator.PLUGIN_ID + ".theme"; //$NON-NLS-1$
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
boolean enabledDefault = Boolean.parseBoolean(System.getProperty(PREF_DEFAULT_SHORTCUTS_ENABLED, "true")); //$NON-NLS-1$
store.setDefault(PREF_KEY_SHORTCUTS_ENABLED, enabledDefault);
store.setDefault(PREF_KEY_MOUSE_TRIGGER_ENABLED, false);
store.setDefault(PREF_KEY_TIME_TO_CLOSE, 5000);
store.setDefault(PREF_KEY_SHOW_DESCRIPTION, true);
}
}
|
package org.showshortcuts.internal;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* Initializer for shortcut visualizer preferences
*
* @author d031150
*/
public class ShortcutPreferenceInitializer extends AbstractPreferenceInitializer {
public static final String PREF_KEY_SHORTCUTS_ENABLED = "enabled"; //$NON-NLS-1$
public static final String PREF_KEY_MOUSE_TRIGGER_ENABLED = "enabled_mouseTrigger"; //$NON-NLS-1$
public static final String PREF_KEY_TIME_TO_CLOSE = "timeToClose"; //$NON-NLS-1$
public static final String PREF_KEY_SHOW_DESCRIPTION = "showCommandDescription"; //$NON-NLS-1$
static final String THEME_CATEGORY = Activator.PLUGIN_ID + ".theme"; //$NON-NLS-1$
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PREF_KEY_SHORTCUTS_ENABLED, true);
store.setDefault(PREF_KEY_MOUSE_TRIGGER_ENABLED, false);
store.setDefault(PREF_KEY_TIME_TO_CLOSE, 5000);
store.setDefault(PREF_KEY_SHOW_DESCRIPTION, true);
}
}
|
Reset search query on location change
|
import { LOCATION_CHANGE } from 'react-router-redux';
import {
SEARCH_QUERY,
} from '../constants';
export const initialState = {
searchQuery: '',
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case LOCATION_CHANGE:
return {
...state,
searchQuery: initialState.searchQuery
};
case SEARCH_QUERY:
return {
...state,
searchQuery: action.payload,
};
default:
return state;
}
}
|
import {
SEARCH_QUERY,
FETCH_ENDPOINTS_START,
FETCH_OAUTH_SERVERS_LIST_START,
} from '../constants';
export const initialState = {
searchQuery: '',
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case FETCH_ENDPOINTS_START:
case FETCH_OAUTH_SERVERS_LIST_START:
return {
...state,
searchQuery: initialState.searchQuery
};
case SEARCH_QUERY:
return {
...state,
searchQuery: action.payload,
};
default:
return state;
}
}
|
Use a bounding box to limit search results
See issue #7
[@wwared, @brunoendo]
|
/*
Copyright © 2015 Biciguia Team
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
function getGeocoderURLFromAddress(address) {
if (address.match('^ *$')) {
return undefined;
}
var geoCoderURL = "http://nominatim.openstreetmap.org/search?format=json";
geoCoderURL += "&city=" + encodeURIComponent("São Paulo");
geoCoderURL += "&state=" + encodeURIComponent("São Paulo");
geoCoderURL += "&country=Brasil";
geoCoderURL += "&street=" + encodeURIComponent(address);
geoCoderURL += "&viewbox=-47.357,-23.125,-45.863,-24.317&bounded=1";
return geoCoderURL;
}
function getAddressListHTML(addresses, source) {
var list = [];
for (var i = 0; i < addresses.length; i++) {
var display_name = addresses[i].display_name;
var itemHtml = "<li class='pure-menu-item'>";
itemHtml += "<a href='#' id='"+source+"-"+i+"' class='pure-menu-link "+source+"-suggestion-item'>";
itemHtml += display_name+"</a></li>";
list.push(itemHtml);
}
return list;
}
|
/*
Copyright © 2015 Biciguia Team
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
function getGeocoderURLFromAddress(address) {
if (address.match('^ *$')) {
return undefined;
}
var geoCoderURL = "http://nominatim.openstreetmap.org/search?format=json";
geoCoderURL += "&city=" + encodeURIComponent("São Paulo");
geoCoderURL += "&state=" + encodeURIComponent("São Paulo");
geoCoderURL += "&country=Brasil";
geoCoderURL += "&street=" + encodeURIComponent(address);
return geoCoderURL;
}
function getAddressListHTML(addresses, source) {
var list = [];
for (var i = 0; i < addresses.length; i++) {
var display_name = addresses[i].display_name;
var itemHtml = "<li class='pure-menu-item'>";
itemHtml += "<a href='#' id='"+source+"-"+i+"' class='pure-menu-link "+source+"-suggestion-item'>";
itemHtml += display_name+"</a></li>";
list.push(itemHtml);
}
return list;
}
|
Use actual binary name instead of hardcoding it
Signed-off-by: Radek Simko <c0f89f684c2e56811603206eabe5a4cea7f58f3e@gmail.com>
|
package main
import (
"os"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
func main() {
for _, f := range os.Args {
if f == "-D" || f == "--debug" || f == "-debug" {
os.Setenv("DEBUG", "1")
initLogging(log.DebugLevel)
}
}
app := cli.NewApp()
app.Name = os.Args[0]
app.Commands = Commands
app.CommandNotFound = cmdNotFound
app.Usage = "Create and manage machines running Docker."
app.Version = VERSION
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, D",
Usage: "Enable debug mode",
},
cli.StringFlag{
EnvVar: "MACHINE_STORAGE_PATH",
Name: "storage-path",
Usage: "Configures storage path",
},
}
app.Run(os.Args)
}
|
package main
import (
"os"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
func main() {
for _, f := range os.Args {
if f == "-D" || f == "--debug" || f == "-debug" {
os.Setenv("DEBUG", "1")
initLogging(log.DebugLevel)
}
}
app := cli.NewApp()
app.Name = "machine"
app.Commands = Commands
app.CommandNotFound = cmdNotFound
app.Usage = "Create and manage machines running Docker."
app.Version = VERSION
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, D",
Usage: "Enable debug mode",
},
cli.StringFlag{
EnvVar: "MACHINE_STORAGE_PATH",
Name: "storage-path",
Usage: "Configures storage path",
},
}
app.Run(os.Args)
}
|
[kurento-client] Call disconnected event when reconnecting
Change-Id: I0f0388f281fa80a1333f6bd18e60e563d4694cf3
|
package org.kurento.client;
import org.kurento.jsonrpc.client.JsonRpcWSConnectionListener;
public class JsonRpcConnectionListenerKurento implements JsonRpcWSConnectionListener {
private KurentoConnectionListener listener;
public JsonRpcConnectionListenerKurento(KurentoConnectionListener listener) {
this.listener = listener;
}
@Override
public void connectionFailed() {
listener.connectionFailed();
}
@Override
public void connected() {
listener.connected();
}
@Override
public void disconnected() {
listener.disconnected();
}
@Override
public void reconnected(boolean sameServer) {
listener.reconnected(sameServer);
}
public static JsonRpcWSConnectionListener create(KurentoConnectionListener listener) {
if (listener == null) {
return null;
}
return new JsonRpcConnectionListenerKurento(listener);
}
@Override
public void reconnecting() {
listener.disconnected();
}
}
|
package org.kurento.client;
import org.kurento.jsonrpc.client.JsonRpcWSConnectionListener;
public class JsonRpcConnectionListenerKurento implements JsonRpcWSConnectionListener {
private KurentoConnectionListener listener;
public JsonRpcConnectionListenerKurento(KurentoConnectionListener listener) {
this.listener = listener;
}
@Override
public void connectionFailed() {
listener.connectionFailed();
}
@Override
public void connected() {
listener.connected();
}
@Override
public void disconnected() {
listener.disconnected();
}
@Override
public void reconnected(boolean sameServer) {
listener.reconnected(sameServer);
}
public static JsonRpcWSConnectionListener create(KurentoConnectionListener listener) {
if (listener == null) {
return null;
}
return new JsonRpcConnectionListenerKurento(listener);
}
@Override
public void reconnecting() {
}
}
|
Remove redundant promise chain block
|
/**
* Created by Tomasz Gabrysiak @ Infermedica on 02/02/2017.
*/
export default class InfermedicaApi {
constructor (appId, appKey, apiModel = 'infermedica-en', apiUrl = 'https://api.infermedica.com/v2/') {
this.appId = appId;
this.appKey = appKey;
this.apiUrl = apiUrl;
this.apiModel = apiModel;
}
_req (method, url, data) {
let headers = new Headers();
headers.append('app-id', this.appId);
headers.append('app-key', this.appKey);
headers.append('model', this.apiModel);
headers.append('content-type', 'application/json');
return fetch(this.apiUrl + url, {
method,
headers,
body: data
}).then((response) => {
return response.json();
});
}
_get (url) {
return this._req('GET', url);
}
_post (url, data) {
return this._req('POST', url, data);
}
getSymptoms () {
return this._get('symptoms');
}
getRiskFactors () {
return this._get('risk_factors');
}
parse (text) {
return this._post('parse', JSON.stringify({'text': text}));
}
diagnosis (data) {
return this._post('diagnosis', JSON.stringify(data));
}
explain (data) {
return this._post('explain', JSON.stringify(data));
}
}
|
/**
* Created by Tomasz Gabrysiak @ Infermedica on 02/02/2017.
*/
export default class InfermedicaApi {
constructor (appId, appKey, apiModel = 'infermedica-en', apiUrl = 'https://api.infermedica.com/v2/') {
this.appId = appId;
this.appKey = appKey;
this.apiUrl = apiUrl;
this.apiModel = apiModel;
}
_req (method, url, data) {
let headers = new Headers();
headers.append('app-id', this.appId);
headers.append('app-key', this.appKey);
headers.append('model', this.apiModel);
headers.append('content-type', 'application/json');
return fetch(this.apiUrl + url, {
method,
headers,
body: data
}).then((response) => {
return response.json();
}).then((json) => {
return json;
});
}
_get (url) {
return this._req('GET', url);
}
_post (url, data) {
return this._req('POST', url, data);
}
getSymptoms () {
return this._get('symptoms');
}
getRiskFactors () {
return this._get('risk_factors');
}
parse (text) {
return this._post('parse', JSON.stringify({'text': text}));
}
diagnosis (data) {
return this._post('diagnosis', JSON.stringify(data));
}
explain (data) {
return this._post('explain', JSON.stringify(data));
}
}
|
Add missing user_id_seq in migration script
|
from sqlalchemy.sql import text
from c2corg_api.scripts.migration.migrate_base import MigrateBase
class UpdateSequences(MigrateBase):
sequences = [
('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'),
('guidebook', 'documents', 'document_id', 'documents_document_id_seq'),
('guidebook', 'documents_geometries_archives', 'id',
'documents_geometries_archives_id_seq'),
('guidebook', 'documents_locales_archives', 'id',
'documents_locales_archives_id_seq'),
('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'),
('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'),
('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'),
('users', 'user', 'id', 'user_id_seq'),
]
def migrate(self):
self.start('sequences')
stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));"
for schema, table, field, sequence in UpdateSequences.sequences:
self.session_target.execute(text(
stmt.format(schema, sequence, field, table)))
self.stop()
|
from sqlalchemy.sql import text
from c2corg_api.scripts.migration.migrate_base import MigrateBase
class UpdateSequences(MigrateBase):
sequences = [
('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'),
('guidebook', 'documents', 'document_id', 'documents_document_id_seq'),
('guidebook', 'documents_geometries_archives', 'id',
'documents_geometries_archives_id_seq'),
('guidebook', 'documents_locales_archives', 'id',
'documents_locales_archives_id_seq'),
('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'),
('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'),
('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'),
]
def migrate(self):
self.start('sequences')
stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));"
for schema, table, field, sequence in UpdateSequences.sequences:
self.session_target.execute(text(
stmt.format(schema, sequence, field, table)))
self.stop()
|
Return empty response on login page.
|
<?php
namespace Lucianux\SpaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* Class SpaController
*
* Single page application controller. Sends out our SPA html layout and handles login
*
* @package Lucianux\SpaBundle\Controller
*/
class SpaController extends Controller
{
/**
* Main SPA app shell page
*
* @Route("/", name="_index")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
return array();
}
/**
* Login page
*
* @Route("/login", name="_login")
* @Method("GET")
*/
public function loginAction()
{
return new Response();
}
/**
* @Route("/api/v1/login_check", name="_security_check")
*/
public function securityCheckAction()
{
// Intercepted by security service
}
/**
* @Route("/logout", name="_logout")
*/
public function logoutAction()
{
// Intercepted by security service
}
}
|
<?php
namespace Lucianux\SpaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* Class SpaController
*
* Single page application controller. Sends out our SPA html layout and handles login
*
* @package Lucianux\SpaBundle\Controller
*/
class SpaController extends Controller
{
/**
* Main SPA app shell page
*
* @Route("/", name="_index")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
return array();
}
/**
* Login page
*
* @Route("/login", name="_login")
* @Method("GET")
*/
public function loginAction()
{
return array();
}
/**
* @Route("/api/v1/login_check", name="_security_check")
*/
public function securityCheckAction()
{
// Intercepted by security service
}
/**
* @Route("/logout", name="_logout")
*/
public function logoutAction()
{
// Intercepted by security service
}
}
|
Fix typo in validation message template.
|
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
/**
* Works like the standard {@link javax.validation.constraints.Pattern @Pattern} but applies to any
* type of object, converting to {@link String} as necessary via {@link Object#toString}, and recursing
* on collection types.
*/
@Documented
@Constraint(validatedBy = PatternValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface Pattern {
String message() default "Does not match the pattern \"{regexp}\"";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Regular expression that must be matched.
*/
String regexp();
/**
* Regular expression flags.
*/
javax.validation.constraints.Pattern.Flag[] flags() default {};
}
|
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
/**
* Works like the standard {@link javax.validation.constraints.Pattern @Pattern} but applies to any
* type of object, converting to {@link String} as necessary via {@link Object#toString}, and recursing
* on collection types.
*/
@Documented
@Constraint(validatedBy = PatternValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface Pattern {
String message() default "Does not match the pattern \"{regex}\"";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Regular expression that must be matched.
*/
String regexp();
/**
* Regular expression flags.
*/
javax.validation.constraints.Pattern.Flag[] flags() default {};
}
|
Fix getting basic auth credentials for installing bundles
|
package com.github.dynamicextensionsalfresco.gradle.configuration;
import java.util.Base64;
import javax.inject.Inject;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
/**
* @author Laurent Van der Linden
*/
public class Authentication {
private final Property<String> username;
private final Property<String> password;
private final Provider<String> basic;
@Inject
public Authentication(ObjectFactory objectFactory, ProviderFactory providerFactory) {
username = objectFactory.property(String.class);
password = objectFactory.property(String.class);
username.set("admin");
password.set("admin");
basic = providerFactory.provider(() -> {
return Base64.getEncoder().encodeToString((username.get()+":"+password.get()).getBytes());
});
}
public Property<String> getUsername() {
return username;
}
public Property<String> getPassword() {
return password;
}
public Provider<String> getBasic() {
return basic;
}
}
|
package com.github.dynamicextensionsalfresco.gradle.configuration;
import java.util.Base64;
import javax.inject.Inject;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
/**
* @author Laurent Van der Linden
*/
public class Authentication {
private final Property<String> username;
private final Property<String> password;
private final Provider<String> basic;
@Inject
public Authentication(ObjectFactory objectFactory, ProviderFactory providerFactory) {
username = objectFactory.property(String.class);
password = objectFactory.property(String.class);
username.set("admin");
password.set("admin");
basic = providerFactory.provider(() -> {
return Base64.getEncoder().encodeToString((username+":"+password).getBytes());
});
}
public Property<String> getUsername() {
return username;
}
public Property<String> getPassword() {
return password;
}
public Provider<String> getBasic() {
return basic;
}
}
|
Kill process to end browserify compile test
|
var amok = require('../');
var test = require('tape');
var fs = require('fs');
test('compile with browserify', function(t) {
var args = [
'test/fixture/bundle.js'
];
var exe = amok.compile('browserify', args);
exe.stderr.on('data', function(data) {
data = data.toString();
t.fail(data);
});
exe.on('ready', function(scripts) {
var filenames = Object.keys(scripts);
t.equal(filenames.length, 1);
var stats = fs.statSync(filenames[0]);
t.ok(stats.size > 1);
var pathnames = filenames.map(function(filename) {
return scripts[filename];
});
t.equal(pathnames.length, 1);
t.equal(pathnames[0], 'test/fixture/bundle.js');
exe.kill();
});
exe.on('close', function(code, signal) {
t.end();
});
});
|
var amok = require('../');
var test = require('tape');
var fs = require('fs');
test('compile with browserify', function(t) {
var args = [
'test/fixture/bundle.js'
];
var exe = amok.compile('browserify', args);
exe.stderr.on('data', function(data) {
data = data.toString();
t.fail(data);
});
exe.on('ready', function(scripts) {
var filenames = Object.keys(scripts);
t.equal(filenames.length, 1);
var stats = fs.statSync(filenames[0]);
t.ok(stats.size > 1);
var pathnames = filenames.map(function(filename) {
return scripts[filename];
});
t.equal(pathnames.length, 1);
t.equal(pathnames[0], 'test/fixture/bundle.js');
});
exe.on('close', function(code, signal) {
t.end();
});
});
|
[BUGFIX] Set the new name for the css compile task in teh default grunt task array
|
module.exports = function(grunt) {
"use strict";
// Display the execution time of grunt tasks
require("time-grunt")(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require("load-grunt-configs")(grunt, {
"config" : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('jit-grunt')(grunt, {
replace: 'grunt-text-replace',
cssmetrics: 'grunt-css-metrics',
bower: 'grunt-bower-task'
});
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask("default", function() {
grunt.task.run(["compile:css", "jshint"]);
});
/**
* Travis CI task
* Test all specified grunt tasks.
*/
grunt.registerTask("travis", function() {
grunt.task.run(["init", "replace:init", "jshint", "deploy", "undeploy"]);
});
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks("Build/Grunt-Tasks/Compilers");
grunt.loadTasks("Build/Grunt-Tasks");
};
|
module.exports = function(grunt) {
"use strict";
// Display the execution time of grunt tasks
require("time-grunt")(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require("load-grunt-configs")(grunt, {
"config" : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('jit-grunt')(grunt, {
replace: 'grunt-text-replace',
cssmetrics: 'grunt-css-metrics',
bower: 'grunt-bower-task'
});
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask("default", function() {
grunt.task.run(["css", "jshint"]);
});
/**
* Travis CI task
* Test all specified grunt tasks.
*/
grunt.registerTask("travis", function() {
grunt.task.run(["init", "replace:init", "jshint", "deploy", "undeploy"]);
});
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks("Build/Grunt-Tasks/Compilers");
grunt.loadTasks("Build/Grunt-Tasks");
};
|
Include plot title to plots
|
from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
out = []
for d in dashboards:
dashboard = d.to_dict()
for i, plot in enumerate(dashboard['plots']):
dashboard['plots'][i]['title'] = d.plots[i].title
out.append(dashboard)
return out
|
from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
'plots': [{'title': plot.title, 'scenario':
plot.parameters['scenario-name'] if 'scenario-name' in plot.parameters.keys() else None}
for plot in d.plots]} for d in dashboards]
|
Set flash message to platform update method.
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\BackUpSettingsValidator;
use Illuminate\Http\Request;
use App\Http\Requests;
/**
*
*/
class SettingsController extends Controller
{
/**
* SettingsController constructor
*/
public function __construct()
{
$this->middleware('lang');
$this->middleware('auth');
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view();
}
/**
* [METHOD]: Update the general application settings.
*
* @url:platform POST:
* @see:phpunit Write phpunit test -> when validation fails.
* @see:phpunit Write phpunit test -> when validation passes.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function updatePlatformSettings()
{
session()->flash('class', 'alert alert-success');
session()->flash('message', '');
return redirect()->back();
}
/**
* @param BackUpSettingsValidator $input
* @return \Illuminate\Http\RedirectResponse
*/
public function updateBackUpSettings(BackUpSettingsValidator $input)
{
dd($input->all()); // For debugging propose
session()->flash('class', '');
session()->flash('message', '');
return redirect()->back();
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\BackUpSettingsValidator;
use Illuminate\Http\Request;
use App\Http\Requests;
/**
*
*/
class SettingsController extends Controller
{
/**
* SettingsController constructor
*/
public function __construct()
{
$this->middleware('lang');
$this->middleware('auth');
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view();
}
/**
* [METHOD]: Update the general application settings.
*
* @url:platform POST:
* @see:phpunit Write phpunit test -> when validation fails.
* @see:phpunit Write phpunit test -> when validation passes.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function updatePlatformSettings()
{
return redirect()->back();
}
/**
* @param BackUpSettingsValidator $input
* @return \Illuminate\Http\RedirectResponse
*/
public function updateBackUpSettings(BackUpSettingsValidator $input)
{
dd($input->all()); // For debugging propose
session()->flash('class', '');
session()->flash('message', '');
return redirect()->back();
}
}
|
Update URL for baseline images
|
import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.1.x+... contain changes that will only
# be included in the 3.2.x release, so we update this here.
if MPL_VERSION[:3] == '3.1' and '+' in MPL_VERSION:
MPL_VERSION = '3.2'
ROOT = "http://{server}/testing/astropy/2019-08-02T11:38:58.288466/{mpl_version}/"
IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))
def ignore_matplotlibrc(func):
# This is a decorator for tests that use matplotlib but not pytest-mpl
# (which already handles rcParams)
@wraps(func)
def wrapper(*args, **kwargs):
with plt.style.context({}, after_reset=True):
return func(*args, **kwargs)
return wrapper
|
import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.1.x+... contain changes that will only
# be included in the 3.2.x release, so we update this here.
if MPL_VERSION[:3] == '3.1' and '+' in MPL_VERSION:
MPL_VERSION = '3.2'
ROOT = "http://{server}/testing/astropy/2018-10-24T12:38:34.134556/{mpl_version}/"
IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))
def ignore_matplotlibrc(func):
# This is a decorator for tests that use matplotlib but not pytest-mpl
# (which already handles rcParams)
@wraps(func)
def wrapper(*args, **kwargs):
with plt.style.context({}, after_reset=True):
return func(*args, **kwargs)
return wrapper
|
CRM-1835: Create B2B customer identity
- minor bug fixes
|
<?php
namespace Oro\Bundle\IntegrationBundle\Migrations\Schema\v1_6;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroIntegrationBundle implements Migration
{
/**
* @inheritdoc
*/
public function up(Schema $schema, QueryBag $queries)
{
self::modifyChannelTable($schema);
}
/**
* Change oro_integration_channel table
*
* @param Schema $schema
*/
public static function modifyChannelTable(Schema $schema)
{
$table = $schema->getTable('oro_integration_channel');
$table->addColumn('edit_mode', 'integer', ['notnull' => true]);
}
}
|
<?php
namespace Oro\Bundle\IntegrationBundle\Migrations\Schema\v1_6;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroIntegrationBundle implements Migration
{
/**
* @inheritdoc
*/
public function up(Schema $schema, QueryBag $queries)
{
self::modifyChannelTable($schema);
}
/**
* Change oro_integration_channel table
*
* @param Schema $schema
*/
public static function modifyChannelTable(Schema $schema)
{
$table = $schema->getTable('oro_integration_channel');
$table->addColumn('edit_mode', 'smallint', ['notnull' => true]);
}
}
|
Make test results not sticky
|
// CHANGELOG check
const hasAppChanges = _.filter(git.modified_files, function(path) {
return _.includes(path, 'lib/');
}).length > 0
if (hasAppChanges && _.includes(git.modified_files, "CHANGELOG.md") === false) {
fail("No CHANGELOG added.")
}
const testFiles = _.filter(git.modified_files, function(path) {
return _.includes(path, '__tests__/');
})
const logicalTestPaths = _.map(testFiles, function(path) {
// turns "lib/__tests__/i-am-good-tests.js" into "lib/i-am-good.js"
return path.replace(/__tests__\//, '').replace(/-tests\./, '.')
})
const sourcePaths = _.filter(git.modified_files, function(path) {
return _.includes(path, 'lib/') && !_.includes(path, '__tests__/');
})
// Check that any new file has a corresponding tests file
const untestedFiles = _.difference(sourcePaths, logicalTestPaths)
if (untestedFiles.length > 0) {
warn("The following files do not have tests: " + github.html_link(untestedFiles), false)
}
|
// CHANGELOG check
const hasAppChanges = _.filter(git.modified_files, function(path) {
return _.includes(path, 'lib/');
}).length > 0
if (hasAppChanges && _.includes(git.modified_files, "CHANGELOG.md") === false) {
fail("No CHANGELOG added.")
}
const testFiles = _.filter(git.modified_files, function(path) {
return _.includes(path, '__tests__/');
})
const logicalTestPaths = _.map(testFiles, function(path) {
// turns "lib/__tests__/i-am-good-tests.js" into "lib/i-am-good.js"
return path.replace(/__tests__\//, '').replace(/-tests\./, '.')
})
const sourcePaths = _.filter(git.modified_files, function(path) {
return _.includes(path, 'lib/') && !_.includes(path, '__tests__/');
})
// Check that any new file has a corresponding tests file
const untestedFiles = _.difference(sourcePaths, logicalTestPaths)
if (untestedFiles.length > 0) {
warn("The following files do not have tests: " + github.html_link(untestedFiles))
}
|
Fix Shell tests according to css changes
|
"""
@given:
-------
@when:
------
I type the "{command}" shell command --> shell_command
@then:
------
I should see the "{command}" result in shell output --> shell_output
------
"""
@when(u'I type the "{command}" shell command')
def shell_command(context, command):
shell_input = context.browser.find_by_css('#shell-input input')
shell_input.type(command)
shell_enter = context.browser.find_by_css('#shell-submit .ui-btn')
shell_enter.click()
@then(u'I should see the "{command}" result in shell output')
def shell_output(context, command):
shell_output = context.browser.find_by_css('#shell-return h3')
for output in shell_output:
if command in output.text:
return
assert False, u'Could not find the output of %s command' % command
|
"""
@given:
-------
@when:
------
I type the "{command}" shell command --> shell_command
@then:
------
I should see the "{command}" result in shell output --> shell_output
------
"""
@when(u'I type the "{command}" shell command')
def shell_command(context, command):
shell_input = context.browser.find_by_css('#shell-input input')
shell_input.type(command)
shell_enter = context.browser.find_by_css('#shell-submit .ui-btn')
shell_enter.click()
@then(u'I should see the "{command}" result in shell output')
def shell_output(context, command):
shell_output = context.browser.find_by_css('#shell-response .ui-btn')
for output in shell_output:
if command in output.text:
return
assert False, u'Could not find the output of %s command' % command
|
Use the renamed 'branding' section of the settings
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isNil } from 'lodash-es'
import girderClient from '@openchemistry/girder-client';
import {
selectors
} from '@openchemistry/redux';
import FooterComponent from '../../components/footer';
class FooterContainer extends Component {
render() {
return (<FooterComponent {...this.props}></FooterComponent>);
}
}
function mapStateToProps(state, _ownProps) {
const { branding } = selectors.configuration.getConfiguration(state) || {};
let props = {};
if (!isNil(branding)) {
const { privacy, license, footerLogoFileId, footerLogoUrl } = branding;
let footerLogoImageUrl = null;
if (!isNil(footerLogoFileId)) {
const baseUrl = girderClient().getBaseURL();
footerLogoImageUrl = `${baseUrl}/file/${footerLogoFileId}/download`
}
props = { privacy, license, footerLogoImageUrl, footerLogoUrl };
}
return props;
}
export default connect(mapStateToProps)(FooterContainer);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isNil } from 'lodash-es'
import girderClient from '@openchemistry/girder-client';
import {
selectors
} from '@openchemistry/redux';
import FooterComponent from '../../components/footer';
class FooterContainer extends Component {
render() {
return (<FooterComponent {...this.props}></FooterComponent>);
}
}
function mapStateToProps(state, _ownProps) {
const { configuration } = selectors.configuration.getConfiguration(state) || {};
let props = {};
if (!isNil(configuration)) {
const { privacy, license, footerLogoFileId, footerLogoUrl } = configuration;
let footerLogoImageUrl = null;
if (!isNil(footerLogoFileId)) {
const baseUrl = girderClient().getBaseURL();
footerLogoImageUrl = `${baseUrl}/file/${footerLogoFileId}/download`
}
props = { privacy, license, footerLogoImageUrl, footerLogoUrl };
}
return props;
}
export default connect(mapStateToProps)(FooterContainer);
|
Replace deprecate code in JUnit call
Summary:
To make code compatible with JUnit 4.13 (following diff).
`createTestClass` function is deprecated, javadoc suggest replacing a call with a constructor, which is what I did.
Note this is a buck-self-test-only change.
Reviewed By: mykola-semko
shipit-source-id: 64158afd8a45fdefdd44c69df4f3103705b25748
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.jvm.java.testutil.compiler;
import org.junit.runners.Parameterized;
/**
* Parameterized test runner that enables tests to work with the Compiler Tree API implementation
* corresponding to the compiler returned by {@link
* javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
* rt.jar and thus are not usually on the classpath.
*/
public class CompilerTreeApiParameterized extends Parameterized {
public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
super(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(klass));
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.jvm.java.testutil.compiler;
import org.junit.runners.Parameterized;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;
/**
* Parameterized test runner that enables tests to work with the Compiler Tree API implementation
* corresponding to the compiler returned by {@link
* javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
* rt.jar and thus are not usually on the classpath.
*/
public class CompilerTreeApiParameterized extends Parameterized {
public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
super(klass);
}
@Override
protected TestClass createTestClass(Class<?> testClass) {
try {
return new TestClass(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(testClass));
} catch (InitializationError initializationError) {
throw new AssertionError(initializationError);
}
}
}
|
Revert "[tmp commit] add example transforms to ./lib/ Plotly for testing"
This reverts commit a06441a2b32bf42334cd65bb397eec0d3c6d84fb.
|
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/*
* This file is browserify'ed into a standalone 'Plotly' object.
*/
var Core = require('./core');
// Load all trace modules
Core.register([
require('./bar'),
require('./box'),
require('./heatmap'),
require('./histogram'),
require('./histogram2d'),
require('./histogram2dcontour'),
require('./pie'),
require('./contour'),
require('./scatter3d'),
require('./surface'),
require('./mesh3d'),
require('./scattergeo'),
require('./choropleth'),
require('./scattergl'),
require('./scatterternary')
]);
module.exports = Core;
|
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/*
* This file is browserify'ed into a standalone 'Plotly' object.
*/
var Core = require('./core');
// Load all trace modules
Core.register([
require('./bar'),
require('./box'),
require('./heatmap'),
require('./histogram'),
require('./histogram2d'),
require('./histogram2dcontour'),
require('./pie'),
require('./contour'),
require('./scatter3d'),
require('./surface'),
require('./mesh3d'),
require('./scattergeo'),
require('./choropleth'),
require('./scattergl'),
require('./scatterternary')
]);
// add filter plugin
Core.register([
require('../test/jasmine/assets/transforms/filter'),
require('../test/jasmine/assets/transforms/groupby')
]);
module.exports = Core;
|
Throw error when cookie is missing
|
const { denodeify, err, xml } = require('./util')
const request = require('request')
const util = require('request/lib/helpers')
// Promisified request.
export const requestPromise = Object.assign(denodeify(request), request)
// Request with bound credentials.
export const requestAuth = ({ request, user, pass }) =>
request.defaults({
auth: { user, pass },
})
// Apply base path to given options.
const optionsPage = (base, options) =>
Object.assign({}, options, { uri: base + (options.uri || options.url) })
// Request relative to base path.
export const requestPage = ({ request, base }) =>
Object.assign(
(...args) =>
request(
optionsPage(base, util.constructOptionsFrom(...args)),
util.filterForCallback(args)
),
request
)
// Wrap a request to parse XML.
export const requestXml = ({ request }) =>
Object.assign(
(...args) =>
request(...args)
.then(async response =>
Object.assign(response, { body: await xml(response.body) })
),
request
)
// Request with bound cookie.
export const requestCookie = ({ request, cookie }) => {
if (!cookie) {
throw err('You must be logged in.')
}
return request.defaults({
headers: { cookie },
})
}
|
const { denodeify, xml } = require('./util')
const request = require('request')
const util = require('request/lib/helpers')
// Promisified request.
export const requestPromise = Object.assign(denodeify(request), request)
// Request with bound credentials.
export const requestAuth = ({ request, user, pass }) =>
request.defaults({
auth: { user, pass },
})
// Apply base path to given options.
const optionsPage = (base, options) =>
Object.assign({}, options, { uri: base + (options.uri || options.url) })
// Request relative to base path.
export const requestPage = ({ request, base }) =>
Object.assign(
(...args) =>
request(
optionsPage(base, util.constructOptionsFrom(...args)),
util.filterForCallback(args)
),
request
)
// Wrap a request to parse XML.
export const requestXml = ({ request }) =>
Object.assign(
(...args) =>
request(...args)
.then(async response =>
Object.assign(response, { body: await xml(response.body) })
),
request
)
// Request with bound cookie.
export const requestCookie = ({ request, cookie }) =>
request.defaults({
headers: { cookie },
})
|
Revert back to using urllib to encode params
But take a snippet from #69 which decodes the response back to unicode.
Fixes #67
|
import requests
import time
import urlparse
import urllib
from paypal import exceptions
def post(url, params):
"""
Make a POST request to the URL using the key-value pairs. Return
a set of key-value pairs.
:url: URL to post to
:params: Dict of parameters to include in post payload
"""
# Ensure all values are bytestrings before passing to urllib
for k in params.keys():
if type(params[k]) == unicode:
params[k] = params[k].encode('utf-8')
payload = urllib.urlencode(params.items())
start_time = time.time()
response = requests.post(
url, payload,
headers={'content-type': 'text/namevalue; charset=utf-8'})
if response.status_code != requests.codes.ok:
raise exceptions.PayPalError("Unable to communicate with PayPal")
# Convert response into a simple key-value format
pairs = {}
for key, values in urlparse.parse_qs(response.content).items():
pairs[key.decode('utf-8')] = values[0].decode('utf-8')
# Add audit information
pairs['_raw_request'] = payload
pairs['_raw_response'] = response.content
pairs['_response_time'] = (time.time() - start_time) * 1000.0
return pairs
|
import requests
import time
import urlparse
from paypal import exceptions
def post(url, params):
"""
Make a POST request to the URL using the key-value pairs. Return
a set of key-value pairs.
:url: URL to post to
:params: Dict of parameters to include in post payload
"""
for k in params.keys():
if type(params[k]) == unicode:
params[k] = params[k].encode('utf-8')
# PayPal is not expecting urlencoding (e.g. %, +), therefore don't use
# urllib.urlencode().
payload = '&'.join(['%s=%s' % (key, val) for (key, val) in params.items()])
start_time = time.time()
response = requests.post(
url, payload,
headers={'content-type': 'text/namevalue; charset=utf-8'})
if response.status_code != requests.codes.ok:
raise exceptions.PayPalError("Unable to communicate with PayPal")
# Convert response into a simple key-value format
pairs = {}
for key, values in urlparse.parse_qs(response.content).items():
pairs[key] = values[0]
# Add audit information
pairs['_raw_request'] = payload
pairs['_raw_response'] = response.content
pairs['_response_time'] = (time.time() - start_time) * 1000.0
return pairs
|
Add metrics page to webpack instead of main metrics js script
|
var webpack = require('webpack');
var path = require('path');
var common = require('../webpack.common.config.js');
var assign = require('object-assign');
var BundleTracker = require('webpack-bundle-tracker');
var websiteRoot = path.join(__dirname, '..', 'website', 'static');
var adminRoot = path.join(__dirname, 'static');
var staticAdminPath = function(dir) {
return path.join(adminRoot, dir);
};
// Adding bundle tracker to plugins
var plugins = common.plugins.concat([
// for using webpack with Django
new BundleTracker({filename: './webpack-stats.json'}),
]);
common.output = {
path: './static/public/js/',
// publicPath: '/static/', // used to generate urls to e.g. images
filename: '[name].js',
sourcePrefix: ''
};
var config = assign({}, common, {
entry: {
'admin-base-page': staticAdminPath('js/pages/base-page.js'),
'prereg-admin-page': staticAdminPath('js/pages/prereg-admin-page.js'),
'admin-registration-edit-page': staticAdminPath('js/pages/admin-registration-edit-page.js'),
'dashboard': staticAdminPath('js/sales_analytics/dashboard.js'),
'metrics-page': staticAdminPath('js/pages/metrics-page.js'),
},
plugins: plugins,
debug: true,
devtool: 'source-map',
});
config.resolve.root = [websiteRoot, adminRoot];
module.exports = config;
|
var webpack = require('webpack');
var path = require('path');
var common = require('../webpack.common.config.js');
var assign = require('object-assign');
var BundleTracker = require('webpack-bundle-tracker');
var websiteRoot = path.join(__dirname, '..', 'website', 'static');
var adminRoot = path.join(__dirname, 'static');
var staticAdminPath = function(dir) {
return path.join(adminRoot, dir);
};
// Adding bundle tracker to plugins
var plugins = common.plugins.concat([
// for using webpack with Django
new BundleTracker({filename: './webpack-stats.json'}),
]);
common.output = {
path: './static/public/js/',
// publicPath: '/static/', // used to generate urls to e.g. images
filename: '[name].js',
sourcePrefix: ''
};
var config = assign({}, common, {
entry: {
'admin-base-page': staticAdminPath('js/pages/base-page.js'),
'prereg-admin-page': staticAdminPath('js/pages/prereg-admin-page.js'),
'admin-registration-edit-page': staticAdminPath('js/pages/admin-registration-edit-page.js'),
'dashboard': staticAdminPath('js/sales_analytics/dashboard.js'),
'metrics': staticAdminPath('js/metrics/metrics.js'),
},
plugins: plugins,
debug: true,
devtool: 'source-map',
});
config.resolve.root = [websiteRoot, adminRoot];
module.exports = config;
|
Update blender plugin version to the next release number
|
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,3,0),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_operators import register as importer_register
from .rna import register as rna_register
from .panels import register as panels_register
rna_register()
panels_register()
importer_register()
def unregister():
from .io_operators import unregister as importer_unregister
from .rna import unregister as rna_unregister
from .panels import unregister as panels_unregister
importer_unregister()
panels_unregister()
rna_unregister()
if __name__ == "__main__":
register()
except ImportError:
# Allow for now, as we might just want to import the sub-package
pass
|
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,0,1),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_operators import register as importer_register
from .rna import register as rna_register
from .panels import register as panels_register
rna_register()
panels_register()
importer_register()
def unregister():
from .io_operators import unregister as importer_unregister
from .rna import unregister as rna_unregister
from .panels import unregister as panels_unregister
importer_unregister()
panels_unregister()
rna_unregister()
if __name__ == "__main__":
register()
except ImportError:
# Allow for now, as we might just want to import the sub-package
pass
|
Use addModuleIncludeMatcher instead of prototype mutation.
|
/* globals jQuery,QUnit */
jQuery(document).ready(function() {
var TestLoaderModule = require('ember-cli/test-loader');
var TestLoader = TestLoaderModule['default'];
var addModuleIncludeMatcher = TestLoaderModule['addModuleIncludeMatcher'];
function moduleMatcher(moduleName) {
return moduleName.match(/\/.*[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/));
}
if (addModuleIncludeMatcher) {
addModuleIncludeMatcher(moduleMatcher);
} else {
TestLoader.prototype.shouldLoadModule = moduleMatcher;
}
TestLoader.prototype.moduleLoadFailure = function(moduleName, error) {
QUnit.module('TestLoader Failures');
QUnit.test(moduleName + ': could not be loaded', function() {
throw error;
});
};
var autostart = QUnit.config.autostart !== false;
QUnit.config.autostart = false;
setTimeout(function() {
TestLoader.load();
if (autostart) {
QUnit.start();
}
}, 250);
});
|
/* globals jQuery,QUnit */
jQuery(document).ready(function() {
var TestLoader = require('ember-cli/test-loader')['default'];
TestLoader.prototype.shouldLoadModule = function(moduleName) {
return moduleName.match(/\/.*[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/));
};
TestLoader.prototype.moduleLoadFailure = function(moduleName, error) {
QUnit.module('TestLoader Failures');
QUnit.test(moduleName + ': could not be loaded', function() {
throw error;
});
};
var autostart = QUnit.config.autostart !== false;
QUnit.config.autostart = false;
setTimeout(function() {
TestLoader.load();
if (autostart) {
QUnit.start();
}
}, 250);
});
|
remove: Use native base64 instead of angular module
|
/**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
import KongDash from './kongdash.js';
import FooterController from './controllers/footer.js';
import BootstrapController from './controllers/bootstrap.js';
const {ipcRenderer} = require('electron');
/**
* Initializes the REST provider.
*
* @param {K_RESTProvider} restProvider - An instance of REST provider constructor.
*/
function initRESTProvider(restProvider) {
const kongConfig = ipcRenderer.sendSync('get-config', 'kong');
if (typeof kongConfig.username === 'string') {
restProvider.setBasicAuth(kongConfig.username, kongConfig.password || '');
}
}
KongDash.config(['restProvider', initRESTProvider]);
KongDash.controller('BootstrapController', ['$scope', '$element', 'rest', 'viewFrame', 'toast', BootstrapController]);
KongDash.controller('FooterController', ['$window', '$scope', '$http', 'viewFrame', 'toast', 'logger', FooterController]);
|
/**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
import KongDash from './kongdash.js';
import FooterController from './controllers/footer.js';
import BootstrapController from './controllers/bootstrap.js';
const {ipcRenderer} = require('electron');
/**
* Initializes the REST provider.
*
* @param {K_RESTProvider} restProvider - An instance of REST provider constructor.
*/
function initRESTProvider(restProvider) {
const kongConfig = ipcRenderer.sendSync('get-config', 'kong');
if (typeof kongConfig.username === 'string') {
restProvider.setBasicAuth(kongConfig.username, kongConfig.password || '');
}
}
KongDash.config(['restProvider', initRESTProvider]);
KongDash.controller('BootstrapController', ['$scope', '$element', '$base64', 'ajax', 'viewFrame', 'toast', BootstrapController]);
KongDash.controller('FooterController', ['$window', '$scope', '$http', 'viewFrame', 'toast', 'logger', FooterController]);
|
Add optional key for setReleaseFromArray
|
<?php
namespace MusicBrainz\Value\Property;
use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\Release;
/**
* Provides a getter for a release.
*/
trait ReleaseTrait
{
/**
* The release number
*
* @var Release
*/
public $release;
/**
* Returns the release.
*
* @return Release
*/
public function getRelease(): Release
{
return $this->release;
}
/**
* Sets the release by extracting it from a given input array.
*
* @param array $input An array returned by the webservice
* @param null|string $key Optional array key (default: "release")
* Use first array dimension for null
*
* @return void
*/
private function setReleaseFromArray(array $input, ?string $key = 'release'): void
{
if (is_null($key)) {
$this->release = new Release($input);
return;
}
$this->release = is_null($release = ArrayAccess::getArray($input, $key))
? new Release
: new Release($release);
}
}
|
<?php
namespace MusicBrainz\Value\Property;
use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\Release;
/**
* Provides a getter for a release.
*/
trait ReleaseTrait
{
/**
* The release number
*
* @var Release
*/
public $release;
/**
* Returns the release.
*
* @return Release
*/
public function getRelease(): Release
{
return $this->release;
}
/**
* Sets the release by extracting it from a given input array.
*
* @param array $input An array returned by the webservice
*
* @return void
*/
private function setReleaseFromArray(array $input): void
{
$this->release = is_null($release = ArrayAccess::getArray($input, 'release'))
? new Release
: new Release($release);
}
}
|
Use event delegation for form submissions
|
$(document).ready(function() {
// This is called after the document has loaded in its entirety
// This guarantees that any elements we bind to will exist on the page
// when we try to bind to them
// See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
$('#content').on('submit', 'form.toggle_form', function (event) {
event.preventDefault();
var $target = $(event.target);
var $complete_btn = $target.children('input[type=submit]');
$complete_btn.attr("disabled", true);
$.ajax({
//url: '/task/' + task_id + '/toggle_complete'
url: $target.attr('action'),
type: 'PUT'
}).done(function (response) {
$target.closest('.task').replaceWith(response);
// $target.closest('.task').find('p.description').first().toggleClass('strikethrough');
// // Deal with the button
// var text = $complete_btn.val() == "Complete" ? "Uncomplete" : "Complete";
// $complete_btn.val(text);
// $complete_btn.attr("disabled", false);
})
})
});
|
$(document).ready(function() {
// This is called after the document has loaded in its entirety
// This guarantees that any elements we bind to will exist on the page
// when we try to bind to them
// See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
$('.toggle_form').submit(function (event) {
event.preventDefault();
var $target = $(event.target);
var $complete_btn = $target.children('input[type=submit]');
$complete_btn.attr("disabled", true);
$.ajax({
//url: '/task/' + task_id + '/toggle_complete'
url: $target.attr('action'),
type: 'PUT'
}).done(function (response) {
$target.closest('.task').replaceWith(response);
// $target.closest('.task').find('p.description').first().toggleClass('strikethrough');
// // Deal with the button
// var text = $complete_btn.val() == "Complete" ? "Uncomplete" : "Complete";
// $complete_btn.val(text);
// $complete_btn.attr("disabled", false);
})
})
});
|
Add test deps on nose, mock.
|
from setuptools import setup
import sys
sys.path.insert(0, 'src')
from rosdep2 import __version__
setup(name='rosdep',
version= __version__,
packages=['rosdep2', 'rosdep2.platforms'],
package_dir = {'':'src'},
# data_files=[('man/man1', ['doc/man/rosdep.1'])],
install_requires = ['rospkg'],
setup_requires = ['nose>=1.0'],
test_suite = 'nose.collector',
test_requires = ['mock'],
scripts = [
'scripts/rosdep',
'scripts/rosdep-gbp-brew',
'scripts/rosdep-source',
],
author = "Tully Foote, Ken Conley",
author_email = "foote@willowgarage.com, kwc@willowgarage.com",
url = "http://www.ros.org/wiki/rosdep",
download_url = "http://pr.willowgarage.com/downloads/rosdep/",
keywords = ["ROS"],
classifiers = [
"Programming Language :: Python",
"License :: OSI Approved :: BSD License" ],
description = "rosdep system dependency installation tool",
long_description = """\
Command-line tool for installing system dependencies on a variety of platforms.
""",
license = "BSD"
)
|
from setuptools import setup
import sys
sys.path.insert(0, 'src')
from rosdep2 import __version__
setup(name='rosdep',
version= __version__,
packages=['rosdep2', 'rosdep2.platforms'],
package_dir = {'':'src'},
# data_files=[('man/man1', ['doc/man/rosdep.1'])],
install_requires = ['rospkg'],
scripts = [
'scripts/rosdep',
'scripts/rosdep-gbp-brew',
'scripts/rosdep-source',
],
author = "Tully Foote, Ken Conley",
author_email = "foote@willowgarage.com, kwc@willowgarage.com",
url = "http://www.ros.org/wiki/rosdep",
download_url = "http://pr.willowgarage.com/downloads/rosdep/",
keywords = ["ROS"],
classifiers = [
"Programming Language :: Python",
"License :: OSI Approved :: BSD License" ],
description = "rosdep system dependency installation tool",
long_description = """\
Command-line tool for installing system dependencies on a variety of platforms.
""",
license = "BSD"
)
|
Switch to module imports for readability.
|
"""Test the conductor REST module."""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from _pytest.python import raises
from future import standard_library
standard_library.install_aliases()
import responses
import pytest
from gobble.config import OS_URL
from gobble.conductor import API, build_api_request
request_functions = [
('authorize_user', '/user/authorize', 'GET'),
('oauth_callback', '/oauth/callback', 'GET'),
('update_user', '/user/update', 'POST'),
('search_users', '/search/user', 'GET'),
('search_packages', '/search/package', 'GET'),
('prepare_upload', '/datastore/', 'POST')
]
@responses.activate
@pytest.mark.parametrize('function, endpoint, verb', request_functions)
def test_api_requests_hit_correct_endpoints(function, endpoint, verb):
endpoint_url = OS_URL + endpoint
# Mock the request with responses
responses.add(verb, endpoint_url, status=200)
response = getattr(API, function)()
assert response.status_code == 200
def test_passing_endpoint_item_not_string_raises_type_error():
with raises(TypeError):
build_api_request('GET', 1000)()
def test_build_api_request_with_invalid_verb_raise_assertion_error():
with raises(AssertionError):
build_api_request('BAR', 'foo')
|
"""Test the conductor REST module."""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from _pytest.python import raises
from future import standard_library
standard_library.install_aliases()
from responses import activate, GET, POST, add
from pytest import mark
from gobble.config import OS_URL
from gobble.conductor import API, build_api_request
request_functions = [
('authorize_user', '/user/authorize', GET),
('oauth_callback', '/oauth/callback', GET),
('update_user', '/user/update', POST),
('search_users', '/search/user', GET),
('search_packages', '/search/package', GET),
('prepare_upload', '/datastore/', POST)
]
@activate
@mark.parametrize('function, endpoint, verb', request_functions)
def test_api_requests_hit_correct_endpoints(function, endpoint, verb):
endpoint_url = OS_URL + endpoint
# Mock the request with responses
add(verb, endpoint_url, status=200)
response = getattr(API, function)()
assert response.status_code == 200
def test_passing_endpoint_item_not_string_raises_type_error():
with raises(TypeError):
build_api_request('GET', 1000)()
def test_build_api_request_with_invalid_verb_raise_assertion_error():
with raises(AssertionError):
build_api_request('BAR', 'foo')
|
Remove router, we just have ONE GET, nothing more.
|
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var spotify = require('spotify-node-applescript');
var SpotifyRemoteServer = require('./lib/spotify_remote_server');
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 1);
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function() {
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
server.listen(app.get('port'), function() {
console.log('Your spotify remote is awaiting commands on: http://localhost:' + app.get('port'));
});
new SpotifyRemoteServer(io, spotify);
|
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var spotify = require('spotify-node-applescript');
var SpotifyRemoteServer = require('./lib/spotify_remote_server');
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 1);
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function() {
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
server.listen(app.get('port'), function() {
console.log('Your spotify remote is awaiting commands on: http://localhost:' + app.get('port'));
});
new SpotifyRemoteServer(io, spotify);
|
Include provides even if it not deferred.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
class MemoryServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.memory'] = $this->app->share(function($app)
{
return new MemoryManager($app);
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('orchestra/memory', 'orchestra/memory');
$this->registerMemoryEvents();
}
/**
* Register the events needed for memory.
*
* @return void
*/
protected function registerMemoryEvents()
{
$app = $this->app;
$app->after(function($request, $response) use ($app)
{
$app->make('orchestra.memory')->shutdown();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.memory');
}
}
|
<?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
class MemoryServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.memory'] = $this->app->share(function($app)
{
return new MemoryManager($app);
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('orchestra/memory', 'orchestra/memory');
$this->registerMemoryEvents();
}
/**
* Register the events needed for memory.
*
* @return void
*/
protected function registerMemoryEvents()
{
$app = $this->app;
$app->after(function($request, $response) use ($app)
{
$app->make('orchestra.memory')->shutdown();
});
}
}
|
Break name and path into separate fields
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateImagesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function(Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->string('name');
$table->integer('imageable_id')->unsigned();
$table->string('imageable_type');
$table->string('caption')->nullable();
$table->string('alt_text')->nullable();
$table->timestamps();
$table->index(['imageable_id', 'imageable_type']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('images');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateImagesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function(Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->integer('imageable_id')->unsigned();
$table->string('imageable_type');
$table->string('caption')->nullable();
$table->string('alt_text')->nullable();
$table->timestamps();
$table->index(['imageable_id', 'imageable_type']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('images');
}
}
|
Split python 3 and python 2 requirements
|
from sys import version_info
from setuptools import setup, find_packages
BASE_REQUIREMENTS = [
'pymorphy2'
]
BACKPORT_REQUIREMENTS = [
'enum34',
'backports.functools-lru-cache',
]
if version_info.major == 2 or (version_info.major == 3 and version_info.minor < 4):
BASE_REQUIREMENTS.append(BACKPORT_REQUIREMENTS)
setup(
name='yargy',
version='0.4.0',
description='Tiny rule-based facts extraction package',
url='https://github.com/bureaucratic-labs/yargy',
author='Dmitry Veselov',
author_email='d.a.veselov@yandex.ru',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7'
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='natural language processing, russian morphology, tomita',
packages=find_packages(),
install_requires=BASE_REQUIREMENTS,
)
|
from setuptools import setup, find_packages
setup(
name='yargy',
version='0.4.0',
description='Tiny rule-based facts extraction package',
url='https://github.com/bureaucratic-labs/yargy',
author='Dmitry Veselov',
author_email='d.a.veselov@yandex.ru',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7'
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='natural language processing, russian morphology, tomita',
packages=find_packages(),
install_requires=[
'pymorphy2',
'enum34',
'backports.functools-lru-cache',
],
)
|
Use variables instead of os.Args
Instead of using the index of an array, use clear names to show what the
index of os.Args should be holding.
|
package main
import (
"fmt"
"os"
"os/user"
"strconv"
"strings"
"syscall"
)
func checkError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(111)
}
}
func main() {
username := os.Args[1]
program := os.Args[2]
user, err := user.Lookup(username)
checkError(err)
uid, err := strconv.Atoi(user.Uid)
checkError(err)
gid, err := strconv.Atoi(user.Gid)
checkError(err)
err = syscall.Setuid(uid)
checkError(err)
err = syscall.Setgid(gid)
checkError(err)
if strings.HasPrefix(program, "/") {
err := syscall.Exec(program, os.Args[2:], os.Environ())
checkError(err)
}
}
|
package main
import (
"fmt"
"os"
"os/user"
"strconv"
"strings"
"syscall"
)
func checkError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(111)
}
}
func main() {
//path := os.Getenv("PATH")
user, err := user.Lookup(os.Args[1])
checkError(err)
uid, err := strconv.Atoi(user.Uid)
checkError(err)
gid, err := strconv.Atoi(user.Gid)
checkError(err)
err = syscall.Setuid(uid)
checkError(err)
err = syscall.Setgid(gid)
checkError(err)
if strings.HasPrefix(os.Args[2], "/") {
err := syscall.Exec(os.Args[2], os.Args[2:], os.Environ())
checkError(err)
}
}
|
Add new Hooks. Not yet called into code
|
package fr.treeptik.cloudunit.hooks;
/**
* Created by nicolas on 19/04/2016.
*/
public enum HookAction {
APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"),
APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"),
APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"),
APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"),
SNAPSHOT_PRE_ACTION("Before Snapshot", "/cloudunit/appconf/hooks/snapshot-pre-action.sh"),
SNAPSHOT_POST_ACTION("After Snapshot", "/cloudunit/appconf/hooks/snapshot-post-action.sh"),
CLONE_PRE_ACTION("Before restoring an application", "/cloudunit/appconf/hooks/clone-pre-action.sh"),
CLONE_POST_ACTION("After restoring an application", "/cloudunit/appconf/hooks/clone-post-action.sh");
private final String label;
private final String command;
HookAction(String label, String command) {
this.label = label;
this.command = command;
}
public String getLabel() {
return label;
}
public String[] getCommand() {
String[] commandBash = new String[2];
commandBash[0] = "bash";
commandBash[1] = command;
return commandBash;
}
}
|
package fr.treeptik.cloudunit.hooks;
/**
* Created by nicolas on 19/04/2016.
*/
public enum HookAction {
APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"),
APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"),
APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"),
APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh");
private final String label;
private final String command;
HookAction(String label, String command) {
this.label = label;
this.command = command;
}
public String getLabel() {
return label;
}
public String[] getCommand() {
String[] commandBash = new String[2];
commandBash[0] = "bash";
commandBash[1] = command;
return commandBash;
}
}
|
Change image form type "file" field type to "file".
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Form\Type;
use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Image form type
*/
class ImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'file', array(
'label' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => AbstractImage::CLASS_NAME,
'intention' => md5(__FILE__),
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_image_image';
}
}
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ImageBundle\Form\Type;
use Darvin\ImageBundle\Entity\Image\AbstractImage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Image form type
*/
class ImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'vich_image', array(
'label' => false,
'required' => false,
));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => AbstractImage::CLASS_NAME,
'intention' => md5(__FILE__),
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'darvin_image_image';
}
}
|
Exit with log.Fatal instead of os.Exit
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
)
func ListRepos(config *Config) {
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: config.OauthToken},
}
client := github.NewClient(t.Client())
// list all repositories for the authenticated user
repos, _, err := client.Repositories.ListByOrg(config.Organization, nil)
if err != nil {
fmt.Println(err)
}
//fmt.Println(github.Stringify(repos))
fmt.Println("Repositories")
for _, repo := range repos {
fmt.Printf(" %s\n", *repo.Name)
}
}
func main() {
file, e := ioutil.ReadFile("./privy.cfg")
if e != nil {
log.Fatal("File error: ", e)
}
var config Config
json.Unmarshal(file, &config)
fmt.Printf("Config: %v\n", config)
ListRepos(&config)
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
)
func ListRepos(config *Config) {
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: config.OauthToken},
}
client := github.NewClient(t.Client())
// list all repositories for the authenticated user
repos, _, err := client.Repositories.ListByOrg(config.Organization, nil)
if err != nil {
fmt.Println(err)
}
//fmt.Println(github.Stringify(repos))
fmt.Println("Repositories")
for _, repo := range repos {
fmt.Printf(" %s\n", *repo.Name)
}
}
func main() {
file, e := ioutil.ReadFile("./privy.cfg")
if e != nil {
fmt.Printf("File error: %v\n", e)
os.Exit(1)
}
var config Config
json.Unmarshal(file, &config)
fmt.Printf("Config: %v\n", config)
ListRepos(&config)
}
|
Remove unused import of pytest
|
from serfclient import result
class TestSerfResult(object):
def test_initialises_to_none(self):
r = result.SerfResult()
assert r.head is None
assert r.body is None
def test_provides_a_pretty_printed_form_for_repl_use(self):
r = result.SerfResult(head={"a": 1}, body=('foo', 'bar'))
assert str(r) == \
"SerfResult<head={'a': 1},body=('foo', 'bar')>"
def test_can_convert_to_list(self):
r = result.SerfResult(head=1, body=2)
assert sorted(list(r)) == [1, 2]
def test_can_convert_to_tuple(self):
r = result.SerfResult(head=1, body=2)
assert sorted(tuple(r)) == [1, 2]
|
import pytest
from serfclient import result
class TestSerfResult(object):
def test_initialises_to_none(self):
r = result.SerfResult()
assert r.head is None
assert r.body is None
def test_provides_a_pretty_printed_form_for_repl_use(self):
r = result.SerfResult(head={"a": 1}, body=('foo', 'bar'))
assert str(r) == \
"SerfResult<head={'a': 1},body=('foo', 'bar')>"
def test_can_convert_to_list(self):
r = result.SerfResult(head=1, body=2)
assert sorted(list(r)) == [1, 2]
def test_can_convert_to_tuple(self):
r = result.SerfResult(head=1, body=2)
assert sorted(tuple(r)) == [1, 2]
|
Add redirect for old hotlinks
|
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import RedirectView
from django.contrib.auth.views import login, logout_then_login
from keyform import views
urlpatterns = [
url(r'^$', views.HomeView.as_view(), name='home'),
url(r'^table.php$', RedirectView.as_view(pattern_name='home', permanent=True)),
url(r'^contact$', views.ContactView.as_view(), name='contact'),
url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'),
url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'),
url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'),
url(r'^create$', views.KeyRequest.as_view(), name='create'),
url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'),
url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}),
url(r'^logout$', logout_then_login, name='logout'),
]
|
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import login, logout_then_login
from keyform import views
urlpatterns = [
url(r'^$', views.HomeView.as_view(), name='home'),
url(r'^contact$', views.ContactView.as_view(), name='contact'),
url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'),
url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'),
url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'),
url(r'^create$', views.KeyRequest.as_view(), name='create'),
url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'),
url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}),
url(r'^logout$', logout_then_login, name='logout'),
]
|
Add logging info for request
|
const config = require('./config');
const express = require('express');
const cors = require('cors');
const importer = require('./middleware/importer');
const mongoose = require('mongoose');
const dbHelper = require('./lib/db');
const tools = require('./lib/tools');
// import routers
const bitcoinRouter = require('./router/bitcoin');
const defaultRouter = require('./router/default');
// activate configured cron jobs
const updateDataCronJobs = require('./cronjobs/updateData');
const deleteOldDataCronJobs = require('./cronjobs/deleteOldData');
// create Express server
var server = express();
// add CORS middleware
server.use(cors());
// connect to MongoDB
var mongoDbUri = dbHelper.getMongoDbUri(config.dbParams);
var mongoDbOptions = {
useMongoClient: true
};
mongoose.connect(mongoDbUri, mongoDbOptions);
// Check if there is a need for data import/sync initiation
// (initiated if number of months is more than the monthly averages in the DB)
importer.checkDBcompleteness();
// log time and ip address of request
server.use(function(req, res, next) {
console.log(tools.getCurrentDatetimeString(), req.ip);
next();
});
// apply /bitcoin routes
server.use(config.urlPrefix + '/bitcoin', bitcoinRouter);
// apply default router to catch ANY other requested route
server.use(config.urlPrefix + '/', defaultRouter);
// start the server
server.listen(config.serverPort, function () {
console.log('Server is running on port: ' + config.serverPort);
});
|
const config = require('./config');
const express = require('express');
const cors = require('cors');
const importer = require('./middleware/importer');
const mongoose = require('mongoose');
const dbHelper = require('./lib/db');
// import routers
const bitcoinRouter = require('./router/bitcoin');
const defaultRouter = require('./router/default');
// activate configured cron jobs
const updateDataCronJobs = require('./cronjobs/updateData');
const deleteOldDataCronJobs = require('./cronjobs/deleteOldData');
// create Express server
var server = express();
// add CORS middleware
server.use(cors());
// connect to MongoDB
var mongoDbUri = dbHelper.getMongoDbUri(config.dbParams);
var mongoDbOptions = {
useMongoClient: true
};
mongoose.connect(mongoDbUri, mongoDbOptions);
// Check if there is a need for data import/sync initiation
// (initiated if number of months is more than the monthly averages in the DB)
importer.checkDBcompleteness();
// apply /bitcoin routes
server.use(config.urlPrefix + '/bitcoin', bitcoinRouter);
// apply default router to catch ANY other requested route
server.use(config.urlPrefix + '/', defaultRouter);
// start the server
server.listen(config.serverPort, function () {
console.log('Server is running on port: ' + config.serverPort);
});
|
Add admin routes and layout management
|
var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
});
Router.route('/', {
name: 'home',
waitOn: function() {
return subscriptions.subscribe('allVolunteers');
},
fastRender: true
});
Router.route('/myProfile', {
name: 'myProfile',
fastRender: false,
waitOn: function() {
return subscriptions.subscribe('oneQuestionAtATime', Meteor.userId());
},
data: function() {
return UserQuestions.findOne({
userId: Meteor.userId(),
answered: false,
deprecated: false
}, {
sort: {
level: 1,
version: 1
}
});
}
});
Router.route('/myDay', {
name: 'myDay',
fastRender: false
});
Router.route('/meeting', {
name: 'meeting',
fastRender: false
});
Router.route('/admin', {
layoutTemplate: 'adminLayout',
name: 'admin',
waitOn: function() {
return [subscriptions.subscribe('allUniverses'), subscriptions.subscribe('allWorkshops')];
},
fastRender: true
});
Router.route('/admin/universes/new', {
layoutTemplate: 'adminLayout',
name: 'newUniverse',
fastRender: false
});
|
var subscriptions = new SubsManager();
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
});
Router.route('/', {
name: 'home',
waitOn: function() {
return subscriptions.subscribe('allVolunteers');
},
fastRender: true
});
Router.route('/myProfile', {
name: 'myProfile',
fastRender: false,
waitOn: function() {
return subscriptions.subscribe('oneQuestionAtATime', Meteor.userId());
},
data: function() {
return UserQuestions.findOne({
userId: Meteor.userId(),
answered: false,
deprecated: false
}, {
sort: {
level: 1,
version: 1
}
});
}
});
Router.route('/myDay', {
name: 'myDay',
fastRender: false
});
Router.route('/meeting', {
name: 'meeting',
fastRender: false
});
|
Add dependencies on hr_contract as it should have been done
|
# -*- coding: utf-8 -*-
{
'name': 'Human Employee Streamline',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Human Resources',
'description': """ enchancements to the hr module to
streamline its usage
""",
'website': 'http://www.openerp-experts.com',
'depends': [
'base',
'hr',
'hr_contract',
],
'data': [
'security/ir.model.access.csv',
'security/record_rules.xml',
'admin_doc.xml',
'hr_employee.xml',
],
'test': [
],
'installable': True,
}
|
# -*- coding: utf-8 -*-
{
'name': 'Human Employee Streamline',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Human Resources',
'description': """ enchancements to the hr module to
streamline its usage
""",
'website': 'http://www.openerp-experts.com',
'depends': [
'base',
'hr',
],
'data': [
'security/ir.model.access.csv',
'security/record_rules.xml',
'admin_doc.xml',
'hr_employee.xml',
],
'test': [
],
'installable': True,
}
|
Return the mail function result.
http://php.net/manual/en/function.mail.php
> Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
return mail($to, $email_subject, $email_body, $headers);
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Move getRestfulContext() from superclass to this.
|
package com.atg.openssp.common.cache.broker;
import com.atg.openssp.common.configuration.ContextCache;
import com.atg.openssp.common.configuration.ContextProperties;
import com.atg.openssp.common.exception.EmptyHostException;
import restful.client.JsonDataProviderConnector;
import restful.context.PathBuilder;
import restful.exception.RestException;
/**
* Generic Broker to connect to a remote webservice.
*
* @author André Schmer
*
*/
public abstract class AbstractDataBroker<T> extends DataBrokerObserver {
protected T connect(final Class<T> clazz) throws RestException, EmptyHostException {
return new JsonDataProviderConnector<>(clazz).connectDataProvider(getRestfulContext());
}
protected PathBuilder getDefaulPathBuilder() {
final PathBuilder pathBuilder = new PathBuilder();
pathBuilder.setMaster_pw(ContextCache.instance.get(ContextProperties.MASTER_PW));
pathBuilder.setMaster_user(ContextCache.instance.get(ContextProperties.MASTER_USER));
pathBuilder.setServer(ContextCache.instance.get(ContextProperties.DATA_PROVIDER_URL));
return pathBuilder;
}
/**
* @return the context of the restful service to connect with {see PathBuilder}.
* @throws EmptyHostException
*/
public abstract PathBuilder getRestfulContext() throws EmptyHostException;
}
|
package com.atg.openssp.common.cache.broker;
import com.atg.openssp.common.configuration.ContextCache;
import com.atg.openssp.common.configuration.ContextProperties;
import com.atg.openssp.common.exception.EmptyHostException;
import restful.client.JsonDataProviderConnector;
import restful.context.PathBuilder;
import restful.exception.RestException;
/**
* Generic Broker to connect to a remote webservice.
*
* @author André Schmer
*
*/
public abstract class AbstractDataBroker<T> extends DataBrokerObserver {
protected T connect(final Class<T> clazz) throws RestException, EmptyHostException {
return new JsonDataProviderConnector<>(clazz).connectDataProvider(getRestfulContext());
}
protected PathBuilder getDefaulPathBuilder() {
final PathBuilder pathBuilder = new PathBuilder();
pathBuilder.setMaster_pw(ContextCache.instance.get(ContextProperties.MASTER_PW));
pathBuilder.setMaster_user(ContextCache.instance.get(ContextProperties.MASTER_USER));
pathBuilder.setServer(ContextCache.instance.get(ContextProperties.DATA_PROVIDER_URL));
return pathBuilder;
}
}
|
Update the named of a renamed React check
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/jsx-wrap-multilines": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/self-closing-comp": 2
}
};
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.