text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Remove unused var to flags test.
|
package flags_test
import (
"github.com/cloudfoundry/bosh-bootloader/flags"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Flags", func() {
var (
f flags.Flags
stringVal string
)
BeforeEach(func() {
f = flags.New("test")
f.String(&stringVal, "string", "")
})
Describe("Parse", func() {
It("can parse strings fields from flags", func() {
err := f.Parse([]string{"--string", "string_value"})
Expect(err).NotTo(HaveOccurred())
Expect(stringVal).To(Equal("string_value"))
})
})
Describe("Args", func() {
It("returns the remainder of unparsed arguments", func() {
err := f.Parse([]string{"some-command", "--some-flag"})
Expect(err).NotTo(HaveOccurred())
Expect(f.Args()).To(Equal([]string{"some-command", "--some-flag"}))
})
})
})
|
package flags_test
import (
"github.com/cloudfoundry/bosh-bootloader/flags"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Flags", func() {
var (
f flags.Flags
// boolVal bool
stringVal string
)
BeforeEach(func() {
f = flags.New("test")
f.String(&stringVal, "string", "")
})
Describe("Parse", func() {
It("can parse strings fields from flags", func() {
err := f.Parse([]string{"--string", "string_value"})
Expect(err).NotTo(HaveOccurred())
Expect(stringVal).To(Equal("string_value"))
})
})
Describe("Args", func() {
It("returns the remainder of unparsed arguments", func() {
err := f.Parse([]string{"some-command", "--some-flag"})
Expect(err).NotTo(HaveOccurred())
Expect(f.Args()).To(Equal([]string{"some-command", "--some-flag"}))
})
})
})
|
Check if callback before invoking it
|
//
// Copyright (c) Microsoft and contributors. 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.
//
/**
* Creates a that handles server redirects;
*/
exports.create = function (maximumRetries) {
return function handle (resource, next, callback) {
var currentRetries = 0;
function handleRedirect(err, response, body) {
if (response && response.headers &&
response.headers.location &&
response.statusCode >= 300 &&
response.statusCode < 400 &&
(!maximumRetries ||
currentRetries < maximumRetries)) {
currentRetries++;
resource.url = response.headers.location;
next(resource, handleRedirect);
} else if (callback) {
callback(err, response, body);
}
}
return next(resource, handleRedirect);
};
};
|
//
// Copyright (c) Microsoft and contributors. 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.
//
/**
* Creates a that handles server redirects;
*/
exports.create = function (maximumRetries) {
return function handle (resource, next, callback) {
var currentRetries = 0;
function handleRedirect(err, response, body) {
if (response && response.headers &&
response.headers.location &&
response.statusCode >= 300 &&
response.statusCode < 400 &&
(!maximumRetries ||
currentRetries < maximumRetries)) {
currentRetries++;
resource.url = response.headers.location;
next(resource, handleRedirect);
} else {
callback(err, response, body);
}
}
return next(resource, handleRedirect);
};
};
|
Add a wait to get authorize response before initial trade page
|
import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import BinarySocket from '_common/base/socket_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
BinarySocket.wait('authorize').then(() => {
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
});
};
export default initApp;
|
import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
};
export default initApp;
|
Add value fallback to empty string
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// Prevents the defaultValue/defaultChecked fields from rendering with value/checked
class ComponentWrapper extends Component {
render() {
/* eslint-disable no-unused-vars */
const {
defaultValue,
defaultChecked,
component,
getRef,
...otherProps,
} = this.props;
/* eslint-enable */
if (getRef) {
otherProps.ref = getRef;
}
if (!otherProps.value) {
otherProps.value = '';
}
const WrappedComponent = component;
return <WrappedComponent {...otherProps} />;
}
}
ComponentWrapper.propTypes = {
component: PropTypes.any,
defaultValue: PropTypes.any,
defaultChecked: PropTypes.any,
getRef: PropTypes.func,
};
export default ComponentWrapper;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// Prevents the defaultValue/defaultChecked fields from rendering with value/checked
class ComponentWrapper extends Component {
render() {
/* eslint-disable no-unused-vars */
const {
defaultValue,
defaultChecked,
component,
getRef,
...otherProps,
} = this.props;
/* eslint-enable */
if (getRef) {
otherProps.ref = getRef;
}
const WrappedComponent = component;
return <WrappedComponent {...otherProps} />;
}
}
ComponentWrapper.propTypes = {
component: PropTypes.any,
defaultValue: PropTypes.any,
defaultChecked: PropTypes.any,
getRef: PropTypes.func,
};
export default ComponentWrapper;
|
Add more variables and bug fixes
|
__author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines():
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "r") as cad:
lines = []
for line in cad:
ip_str, port = line.split(":")
if ip_str == str(ip):
lines.append(line)
def chunk_number(i):
if i == 0 or i == 1:
return 0
else:
return i - 1
def chunk_count(i):
with open(cad_file) as cad:
for i, l in enumerate(cad):
pass
return i + 1 - 2
|
__author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines(i):
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "r") as cad:
lines = []
for line in cad:
ip_str, port = line.split(":")
if ip_str == str(ip):
lines.append(line)
def chunk_number(i):
if i == 0 or i == 1:
return 0
else:
return i -1
def chunk_count(i):
with open(cad_file) as cad:
for i, l in enumerate(cad):
pass
return i + 1 - 2
|
Remove broken logic from controller.
|
'use strict';
angular.module('fivefifteenApp')
.controller('MainCtrl', function ($scope, $routeParams, Data, Steps) {
// Simple Data service to persist form values.
$scope.data = Data;
$scope.steps = Steps.data;
if (angular.isDefined($routeParams.stepName)) {
$scope.path = $routeParams.stepName;
}
})
// scope data is not persistent across views so we use a simple service.
.factory('Data', function () {
// This variable holds all of the text used on the site.
return {};
})
.factory('Steps', function($firebase) {
var url = new Firebase("https://fivefifteen.firebaseio.com/steps"),
promise = $firebase(url),
factory = { "data": [] };
promise.$on('loaded', function(values) {
// If we get values, store it both in the scope and Steps.
if (!angular.isDefined(values)) {
return;
}
factory.rawData = values;
for (var key in values) {
var stepNumber = values[key].stepNumber;
factory.data[stepNumber] = values[key];
}
});
return factory;
});
|
'use strict';
angular.module('fivefifteenApp')
.controller('MainCtrl', function ($scope, $routeParams, Data, Steps) {
// Simple Data service to persist form values.
$scope.data = Data;
if (angular.isDefined($routeParams.stepName)) {
$scope.path = $routeParams.stepName;
$scope.step = Steps.rawData[$scope.path];
}
$scope.steps = Steps.data;
})
// scope data is not persistent across views so we use a simple service.
.factory('Data', function () {
// This variable holds all of the text used on the site.
return {};
})
.factory('Steps', function($firebase) {
var url = new Firebase("https://fivefifteen.firebaseio.com/steps"),
promise = $firebase(url),
factory = { "data": [] };
promise.$on('loaded', function(values) {
// If we get values, store it both in the scope and Steps.
if (!angular.isDefined(values)) {
return;
}
factory.rawData = values;
for (var key in values) {
var stepNumber = values[key].stepNumber;
factory.data[stepNumber] = values[key];
}
});
return factory;
});
|
[Utils] Allow colons in filenames for now
|
# coding=utf-8
import string
from numbers import Number
__author__ = 'Gareth Coles'
FILENAME_SAFE_CHARS = (
"/\\-_.()#:" +
string.digits +
string.letters +
string.whitespace
)
class EmptyStringFormatter(string.Formatter):
"""
EmptyStringFormatter - The same as the normal string formatter, except
this one replaces missing tokens with empty strings.
Use this just like you would a normal formatter. For example:
>>> formatter = EmptyStringFormatter()
>>> formatter.format("... {RED} {YELLOW} ...", RED="red")
'... red ...'
"""
def get_value(self, key, args, kwargs):
try:
# if hasattr(key, "__mod__"):
if isinstance(key, Number):
return args[key]
else:
return kwargs[key]
except (KeyError, IndexError):
return ""
def to_filename(_string):
return filter(
lambda x: x in FILENAME_SAFE_CHARS,
_string
)
|
# coding=utf-8
import string
from numbers import Number
__author__ = 'Gareth Coles'
FILENAME_SAFE_CHARS = (
"/\\-_.()#" +
string.digits +
string.letters +
string.whitespace
)
class EmptyStringFormatter(string.Formatter):
"""
EmptyStringFormatter - The same as the normal string formatter, except
this one replaces missing tokens with empty strings.
Use this just like you would a normal formatter. For example:
>>> formatter = EmptyStringFormatter()
>>> formatter.format("... {RED} {YELLOW} ...", RED="red")
'... red ...'
"""
def get_value(self, key, args, kwargs):
try:
# if hasattr(key, "__mod__"):
if isinstance(key, Number):
return args[key]
else:
return kwargs[key]
except (KeyError, IndexError):
return ""
def to_filename(_string):
return filter(
lambda x: x in FILENAME_SAFE_CHARS,
_string
)
|
Update findDomNode to react 0.14 style
|
var React = require('react')
var cx = require('./cx')
var Toggle = React.createClass({
componentDidMount() {
// ensure ratchet toggles initialised
require('../vendor/toggles')
React.findDOMNode(this.refs.toggle).addEventListener('toggle', this.handleToggle)
},
componentWillUnmount() {
React.findDOMNode(this.refs.toggle).removeEventListener('toggle', this.handleToggle)
},
handleToggle(e) {
var inverse = !this.props.active
if (e.detail.isActive == inverse) {
this.props.onToggle(inverse)
}
},
render() {
var extraClasses = []
if (this.props.active) extraClasses.push('active')
var className = cx.apply(null, [this.props.className, "toggle"].concat(extraClasses))
return (
<div {...this.props} className={className} ref="toggle">
<div className="toggle-handle" />
</div>
)
}
})
module.exports = Toggle
|
var React = require('react')
var cx = require('./cx')
var Toggle = React.createClass({
componentDidMount() {
// ensure ratchet toggles initialised
require('../vendor/toggles')
this.refs.toggle.getDOMNode().addEventListener('toggle', this.handleToggle)
},
componentWillUnmount() {
this.refs.toggle.getDOMNode().removeEventListener('toggle', this.handleToggle)
},
handleToggle(e) {
var inverse = !this.props.active
if (e.detail.isActive == inverse) {
this.props.onToggle(inverse)
}
},
render() {
var extraClasses = []
if (this.props.active) extraClasses.push('active')
var className = cx.apply(null, [this.props.className, "toggle"].concat(extraClasses))
return (
<div {...this.props} className={className} ref="toggle">
<div className="toggle-handle" />
</div>
)
}
})
module.exports = Toggle
|
Add name to api-token-auth url endpoint.
|
from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all_views as munigeo_views
# from django.contrib import admin
# admin.autodiscover()
router = routers.DefaultRouter()
registered_api_views = set()
for view in services_views + munigeo_views + observations_views:
kwargs = {}
if view['name'] in registered_api_views:
continue
else:
registered_api_views.add(view['name'])
if 'base_name' in view:
kwargs['base_name'] = view['base_name']
router.register(view['name'], view['class'], **kwargs)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'smbackend.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^', include(v1_api.urls)),
# url(r'^admin/', include(admin.site.urls)),
url(r'^open311/', 'services.views.post_service_request', name='services'),
url(r'^v1/', include(router.urls)),
url(r'^v1/api-token-auth/', obtain_auth_token, name='api-auth-token')
)
|
from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all_views as munigeo_views
# from django.contrib import admin
# admin.autodiscover()
router = routers.DefaultRouter()
registered_api_views = set()
for view in services_views + munigeo_views + observations_views:
kwargs = {}
if view['name'] in registered_api_views:
continue
else:
registered_api_views.add(view['name'])
if 'base_name' in view:
kwargs['base_name'] = view['base_name']
router.register(view['name'], view['class'], **kwargs)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'smbackend.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^', include(v1_api.urls)),
# url(r'^admin/', include(admin.site.urls)),
url(r'^open311/', 'services.views.post_service_request', name='services'),
url(r'^v1/', include(router.urls)),
url(r'^v1/api-token-auth/', obtain_auth_token)
)
|
Remove "cast" from Promise test
Promise.resolve now behaves as Promise.cast
|
/*!
{
"name": "ES6 Promises",
"property": "promises",
"caniuse": "promises",
"polyfills": ["es6promises"],
"authors": ["Krister Kari", "Jake Archibald"],
"tags": ["es6"],
"notes": [{
"name": "The ES6 promises spec",
"href": "https://github.com/domenic/promises-unwrapping"
},{
"name": "Chromium dashboard - ES6 Promises",
"href": "http://www.chromestatus.com/features/5681726336532480"
},{
"name": "JavaScript Promises: There and back again - HTML5 Rocks",
"href": "http://www.html5rocks.com/en/tutorials/es6/promises/"
}]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Promises per specification.
*/
define(['Modernizr'], function( Modernizr ) {
Modernizr.addTest('promises', function() {
return 'Promise' in window &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
'resolve' in window.Promise &&
'reject' in window.Promise &&
'all' in window.Promise &&
'race' in window.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new window.Promise(function(r) { resolve = r; });
return typeof resolve === 'function';
}());
});
});
|
/*!
{
"name": "ES6 Promises",
"property": "promises",
"caniuse": "promises",
"polyfills": ["es6promises"],
"authors": ["Krister Kari", "Jake Archibald"],
"tags": ["es6"],
"notes": [{
"name": "The ES6 promises spec",
"href": "https://github.com/domenic/promises-unwrapping"
},{
"name": "Chromium dashboard - ES6 Promises",
"href": "http://www.chromestatus.com/features/5681726336532480"
},{
"name": "JavaScript Promises: There and back again - HTML5 Rocks",
"href": "http://www.html5rocks.com/en/tutorials/es6/promises/"
}]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Promises per specification.
*/
define(['Modernizr'], function( Modernizr ) {
Modernizr.addTest('promises', function() {
return 'Promise' in window &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
'cast' in window.Promise &&
'resolve' in window.Promise &&
'reject' in window.Promise &&
'all' in window.Promise &&
'race' in window.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new window.Promise(function(r) { resolve = r; });
return typeof resolve === 'function';
}());
});
});
|
Add minor spaces to docblock
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
/*
|--------------------------------------------------------------------------
| Orchestra Library
|--------------------------------------------------------------------------
|
| Map Orchestra Library using PSR-0 standard namespace.
|
*/
Autoloader::namespaces(array(
'Orchestra\Model' => Bundle::path('orchestra').'models'.DS,
'Orchestra' => Bundle::path('orchestra').'libraries'.DS,
));
Autoloader::map(array(
'Orchestra' => Bundle::path('orchestra').'orchestra'.EXT,
));
/*
|--------------------------------------------------------------------------
| Orchestra Dependencies
|--------------------------------------------------------------------------
|
| Add Orchestra helpers function and dependencies.
|
*/
include_once Bundle::path('orchestra').'helpers'.EXT;
include_once Bundle::path('orchestra').'includes'.DS.'dependencies'.EXT;
/*
|--------------------------------------------------------------------------
| Orchestra Events Listener
|--------------------------------------------------------------------------
|
| Lets listen to when Orchestra bundle is started.
|
*/
Event::listen('laravel.done', function ()
{
Orchestra\Core::shutdown();
});
Event::listen('orchestra.started: backend', function ()
{
Orchestra\View::$theme = 'backend';
});
/*
|--------------------------------------------------------------------------
| Let's Start
|--------------------------------------------------------------------------
*/
Orchestra\Core::start();
Orchestra\Core::asset();
|
<?php
/*
|--------------------------------------------------------------------------
| Orchestra Library
|--------------------------------------------------------------------------
|
| Map Orchestra Library using PSR-0 standard namespace.
*/
Autoloader::namespaces(array(
'Orchestra\Model' => Bundle::path('orchestra').'models'.DS,
'Orchestra' => Bundle::path('orchestra').'libraries'.DS,
));
Autoloader::map(array(
'Orchestra' => Bundle::path('orchestra').'orchestra'.EXT,
));
/*
|--------------------------------------------------------------------------
| Orchestra Dependencies
|--------------------------------------------------------------------------
|
| Add Orchestra helpers function and dependencies
*/
include_once Bundle::path('orchestra').'helpers'.EXT;
include_once Bundle::path('orchestra').'includes'.DS.'dependencies'.EXT;
/*
|--------------------------------------------------------------------------
| Orchestra Events Listener
|--------------------------------------------------------------------------
|
| Lets listen to when Orchestra bundle is started.
*/
Event::listen('laravel.done', function ()
{
Orchestra\Core::shutdown();
});
Event::listen('orchestra.started: backend', function ()
{
Orchestra\View::$theme = 'backend';
});
Orchestra\Core::start();
Orchestra\Core::asset();
|
Add icon to represent successful and failed requests
|
package main
import (
"flag"
"fmt"
)
func main() {
tester, err := NewTTFB()
if err != nil {
fmt.Println(err)
return
}
flag.Parse()
results, err := tester.Report(flag.Arg(0))
if err != nil {
fmt.Println(err)
return
}
var icon string
fmt.Printf("@ Testing domain '%s'\n", tester.domain)
fmt.Printf(" Status: Connection Time, First Byte Time, Total Time\n")
for _, data := range results {
if data.Status == 1 {
icon = "\033[0;92m\u2714\033[0m"
} else {
icon = "\033[0;91m\u2718\033[0m"
}
fmt.Printf("%s %s -> %s, %s, %s %s\n",
icon,
data.Output.ServerID,
data.Output.ConnectTime,
data.Output.FirstbyteTime,
data.Output.TotalTime,
data.Output.ServerTitle)
}
fmt.Println(" Finished")
}
|
package main
import (
"flag"
"fmt"
)
func main() {
tester, err := NewTTFB()
if err != nil {
fmt.Println(err)
return
}
flag.Parse()
results, err := tester.Report(flag.Arg(0))
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("@ Testing domain '%s'\n", tester.domain)
fmt.Printf(" Status: Connection Time, First Byte Time, Total Time\n")
for _, data := range results {
fmt.Printf("- %s -> %s, %s, %s %s\n",
data.Output.ServerID,
data.Output.ConnectTime,
data.Output.FirstbyteTime,
data.Output.TotalTime,
data.Output.ServerTitle)
}
fmt.Println(" Finished")
}
|
Fix matching users against R: extbans
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class AccountExtban(ModuleData):
implements(IPlugin, IModuleData)
name = "AccountExtban"
def actions(self):
return [ ("usermatchban-R", 1, self.matchBan),
("usermetadataupdate", 10, self.updateBansOnAccountChange) ]
def matchBan(self, user, matchNegated, mask):
if not user.metadataKeyExists("account"):
return matchNegated
userAccount = ircLower(user.metadataValue("account"))
lowerMask = ircLower(mask)
if fnmatchcase(userAccount, lowerMask):
return not matchNegated
return matchNegated
def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
if key != "account":
return
self.ircd.runActionStandard("updateuserbancache", user)
matchExtban = AccountExtban()
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class AccountExtban(ModuleData):
implements(IPlugin, IModuleData)
name = "AccountExtban"
def actions(self):
return [ ("usermatchban-R", 1, self.matchBan),
("usermetadataupdate", 10, self.updateBansOnAccountChange) ]
def matchBan(self, user, matchNegated, mask):
if not user.metadataKeyExists("account"):
return matchNegated
userAccount = ircLower(user.metadataValue("account"))
if fnmatchcase(userAccount, mask):
return not matchNegated
return matchNegated
def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
if key != "account":
return
self.ircd.runActionStandard("updateuserbancache", user)
matchExtban = AccountExtban()
|
Support static references of getVetoLayer
|
package infn.bed.util;
import infn.bed.geometry.GeometricConstants;
/**
* Returns the layer of a veto.
*
* @author Angelo Licastro
*/
public class GetVetoLayer {
/**
* Returns the layer of a veto.
*
* @param veto The number of a veto in one-based indexing.
* @return The layer of the veto.
* If the veto is a crystal, then 1 is returned.
* If the veto is an internal veto, then 2 is returned.
* If the veto is an external veto, then 3 is returned.
* If the veto does not exist, then -1 is returned.
*/
public static int getVetoLayer(int veto) {
if (veto > 0 && veto <= GeometricConstants.VETOES) {
if (veto <= GeometricConstants.CRYSTALS) {
return 1;
} else if (veto <= GeometricConstants.INTERNAL_VETOES + 1) {
return 2;
} else if (veto <= GeometricConstants.VETOES) {
return 3;
}
}
return -1;
}
}
|
package infn.bed.util;
import infn.bed.geometry.GeometricConstants;
/**
* Returns the layer of a veto.
*
* @author Angelo Licastro
*/
public class GetVetoLayer {
/**
* Returns the layer of a veto.
*
* @param veto The number of a veto in one-based indexing.
* @return The layer of the veto.
* If the veto is a crystal, then 1 is returned.
* If the veto is an internal veto, then 2 is returned.
* If the veto is an external veto, then 3 is returned.
* If the veto does not exist, then -1 is returned.
*/
public int getVetoLayer(int veto) {
if (veto > 0 && veto <= GeometricConstants.VETOES) {
if (veto <= GeometricConstants.CRYSTALS) {
return 1;
} else if (veto <= GeometricConstants.INTERNAL_VETOES) {
return 2;
} else if (veto <= GeometricConstants.VETOES) {
return 3;
}
}
return -1;
}
}
|
Move pages to root URL
Fixes #1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Glowstone Organization'
SITENAME = 'Glowstone'
SITEURL = ''
PATH = 'content'
PAGE_PATHS = ['']
PAGE_URL = '{slug}/'
PAGE_SAVE_AS = '{slug}/index.html'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
THEME = "theme"
# Blogroll
LINKS = (('Pelican', 'https://getpelican.com/'),
('Python.org', 'https://www.python.org/'),
('Jinja2', 'https://palletsprojects.com/p/jinja/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Glowstone Organization'
SITENAME = 'Glowstone'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'UTC'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
THEME = "theme"
# Blogroll
LINKS = (('Pelican', 'https://getpelican.com/'),
('Python.org', 'https://www.python.org/'),
('Jinja2', 'https://palletsprojects.com/p/jinja/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
Support `page` parameter in stream API.
|
package tw.wancw.curator.api;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
public class CuratorApi {
private static final String API_END_POINT = "http://curator.im/api/";
private static final AsyncHttpClient client = new AsyncHttpClient();
private final String token;
public CuratorApi(String token) {
this.token = token;
}
public void stream(final MeiZiCardsResponseHandler handler) {
stream(1, handler);
}
public void stream(final int page, final MeiZiCardsResponseHandler handler) {
final String path = "stream/";
RequestParams params = new RequestParams();
params.put("token", token);
params.put("page", String.valueOf(page));
client.get(API_END_POINT + path, params, new StreamResponseHandler(handler));
}
}
|
package tw.wancw.curator.api;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
public class CuratorApi {
private static final String API_END_POINT = "http://curator.im/api/";
private static final AsyncHttpClient client = new AsyncHttpClient();
private final String token;
public CuratorApi(String token) {
this.token = token;
}
public void stream(MeiZiCardsResponseHandler handler) {
final String path = "stream/";
RequestParams params = new RequestParams();
params.put("token", token);
params.put("page", 1);
client.get(API_END_POINT + path, params, new StreamResponseHandler(handler));
}
}
|
Update test suite to ensure spinner and spinner options are rendered as expected
|
/** @jsx React.DOM */
var React = require('react');
var Loader = require('../../lib/react-loader');
var expect = require('chai').expect;
describe('Loader', function () {
var testCases = [{
description: 'loading is in progress',
options: { loaded: false },
expectedOutput: /<div class="loader".*<div class="spinner"/
},
{
description: 'loading is in progress with spinner options',
options: { loaded: false, radius: 17, width: 900 },
expectedOutput: /<div class="loader"[^>]*?><div class="spinner"[^>]*?>.*translate\(17px, 0px\).*style="[^"]*?height: 900px;/
},
{
describe: 'loading is complete',
options: { loaded: true },
expectedOutput: /<div[^>]*>Welcome<\/div>/
}];
testCases.forEach(function (testCase) {
describe(testCase.description, function () {
beforeEach(function () {
var loader = new Loader(testCase.options, 'Welcome');
React.renderComponent(loader, document.body);
});
it('renders the correct output', function () {
expect(document.body.innerHTML).to.match(testCase.expectedOutput);
})
});
});
});
|
/** @jsx React.DOM */
var React = require('react');
var Loader = require('../../lib/react-loader');
var expect = require('chai').expect;
var loader;
describe('Loader', function () {
describe('before loaded', function () {
beforeEach(function () {
loader = <Loader loaded={false}>Welcome</Loader>;
React.renderComponent(loader, document.body);
});
it('renders the loader', function () {
expect(document.body.innerHTML).to.match(/<div class="loader"/);
});
it('does not render the content', function () {
expect(document.body.innerHTML).to.not.match(/Welcome/);
});
});
describe('after loaded', function () {
beforeEach(function () {
loader = <Loader loaded={true}>Welcome</Loader>;
React.renderComponent(loader, document.body);
});
it('does not render the loader', function () {
expect(document.body.innerHTML).to.not.match(/<div class="loader"/);
});
it('renders the content', function () {
expect(document.body.innerHTML).to.match(/Welcome/);
});
});
});
|
Add packages for ecoapi e xapi
|
#!/usr/bin/env python
""" Setup to allow pip installs of pok-eco module """
from setuptools import setup
setup(
name='pok-eco',
version='0.1.0',
description='POK-ECO Integrations ',
author='METID - Politecnico di Milano',
url='http://www.metid.polimi.it',
license='AGPL',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=['oai', 'ecoapi', 'xapi'],
dependency_links=["https://github.com/infrae/pyoai/archive/2.4.4.zip#egg=pyoai==2.4.4"],
install_requires=[
"Django >= 1.4, < 1.5",
"django-celery==3.1.16"
]
)
|
#!/usr/bin/env python
""" Setup to allow pip installs of pok-eco module """
from setuptools import setup
setup(
name='pok-eco',
version='0.1.0',
description='POK-ECO Integrations ',
author='METID - Politecnico di Milano',
url='http://www.metid.polimi.it',
license='AGPL',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=['oai'],
dependency_links=["https://github.com/infrae/pyoai/archive/2.4.4.zip#egg=pyoai==2.4.4"],
install_requires=[
"Django >= 1.4, < 1.5",
"django-celery==3.1.16"
]
)
|
Remove unsued code until configuration is defined
|
<?php
/*
* This file is part of the WobbleCodeRestBundle package.
*
* (c) WobbleCode <http://www.wobblecode.com/>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
namespace WobbleCode\RestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your
* app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*
* @todo Create configuration tree for RestBundle
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
return $treeBuilder;
}
}
|
<?php
/*
* This file is part of the WobbleCodeRestBundle package.
*
* (c) WobbleCode <http://www.wobblecode.com/>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
namespace WobbleCode\RestBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your
* app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('wobblecode_rest', 'array');
/**
* @todo Create configuration tree for RestBundle
*/
return $treeBuilder;
}
}
|
Comment out dotenv for heroku deployment
|
'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
// require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretJcsgithubNightlifeapp',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var bodyParser = require('body-parser')
var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
// Configure server to parse JSON for us
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use(session({
secret: 'secretJcsgithubNightlifeapp',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
Add OCA as author of OCA addons
In order to get visibility on https://www.odoo.com/apps the OCA board has
decided to add the OCA as author of all the addons maintained as part of the
association.
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2012-2013 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Automatically select invoicing partner on invoice",
"version": "0.2",
"author": "Therp BV,Odoo Community Association (OCA)",
"category": 'Accounting & Finance',
'website': 'https://github.com/OCA/account-invoicing',
'license': 'AGPL-3',
'depends': ['account'],
'installable': True,
}
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2012-2013 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Automatically select invoicing partner on invoice",
"version": "0.2",
"author": "Therp BV",
"category": 'Accounting & Finance',
'website': 'https://github.com/OCA/account-invoicing',
'license': 'AGPL-3',
'depends': ['account'],
'installable': True,
}
|
Fix stupid mistake in reexports.
|
export { setResolver, getResolver } from './resolver';
export { setApplication } from './application';
export {
default as setupContext,
getContext,
setContext,
unsetContext,
pauseTest,
resumeTest,
} from './setup-context';
export { default as teardownContext } from './teardown-context';
export { default as setupRenderingContext, render, clearRender } from './setup-rendering-context';
export { default as teardownRenderingContext } from './teardown-rendering-context';
export { default as settled, isSettled, getState as getSettledState } from './settled';
export { default as waitUntil } from './wait-until';
export { default as validateErrorHandler } from './validate-error-handler';
// DOM Helpers
export { default as click } from './dom/click';
export { default as focus } from './dom/focus';
export { default as blur } from './dom/blur';
export { default as triggerEvent } from './dom/trigger-event';
export { default as triggerKeyEvent } from './dom/trigger-key-event';
|
export { setResolver, getResolver } from './resolver';
export { setApplication } from './application';
export {
default as setupContext,
getContext,
setContext,
unsetContext,
pauseTest,
resumeTest,
} from './setup-context';
export { default as teardownContext } from './teardown-context';
export { default as setupRenderingContext, render, clearRender } from './setup-rendering-context';
export { default as teardownRenderingContext } from './teardown-rendering-context';
export { default as settled, isSettled, getState as getSettledState } from './settled';
export { default as waitUntil } from './wait-until';
export { default as validateErrorHandler } from './validate-error-handler';
// DOM Helpers
export { default as click } from './dom/click';
export { default as focus } from './dom/focus';
export { default as blur } from './dom/blur';
export { default as triggerEvent } from './dom/blur';
export { default as triggerKeyEvent } from './dom/blur';
|
Remove commented code in wifflechat js
|
if (Meteor.isClient) {
Accounts.ui.config({
passwordSignupFields: 'USERNAME_ONLY'
});
Template.messages.helpers({
messages: function() {
return Messages.find({}, { sort: { time: 1}});
}
});
var scrollPosition = function() {
$('#messages').scrollTop($('#messages')[0].scrollHeight);
};
Template.input.events = {
'keydown input#message' : function (event) {
if (event.which == 13) {
if (Meteor.user())
var name = Meteor.user().username;
else
var name = 'Anonymous';
var message = document.getElementById('message');
if (message.value != '') {
Messages.insert({
name: name,
message: message.value,
time: Date.now(),
});
document.getElementById('message').value = '';
message.value = '';
}
}
}
};
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
}
|
if (Meteor.isClient) {
Accounts.ui.config({
passwordSignupFields: 'USERNAME_ONLY'
});
Template.messages.helpers({
messages: function() {
return Messages.find({}, { sort: { time: 1}});
}
});
var scrollPosition = function() {
$('#messages').scrollTop($('#messages')[0].scrollHeight);
};
Template.input.events = {
'keydown input#message' : function (event) {
if (event.which == 13) { // 13 is the enter key event
if (Meteor.user())
var name = Meteor.user().username;
else
var name = 'Anonymous';
var message = document.getElementById('message');
if (message.value != '') {
Messages.insert({
name: name,
message: message.value,
time: Date.now(),
});
document.getElementById('message').value = '';
message.value = '';
}
}
}
};
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
}
|
Add index on userid to transaction database
|
var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate DATETIME DEFAULT current_timestamp)', [], this);
})
.par(function() {
db.query('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate DATETIME DEFAULT current_timestamp, value REAL)', [], this);
})
.seq(function() {
db.query('CREATE INDEX userId ON transactions(userId)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
|
var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('create table users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate datetime default current_timestamp)', [], this);
})
.par(function() {
db.query('create table transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate datetime default current_timestamp, value REAL)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
|
Fix example test env reference
|
'use strict';
// workflows/createDeployment
var Joi = require('joi');
module.exports = {
schema: Joi.object({
deployerId: Joi.string().required(),
name: Joi.string().min(1).required(),
}).required().unknown(true),
version: '1.0',
decider: function(args) {
return {
createDeploymentDoc: {
activity: 'createDeploymentDoc',
input: (env) => ({}),
output: (env) => ({ theId: env.id })
},
startNewDeployment: {
dependsOn: ['createDeploymentDoc'],
input: (env) => ({ deploymentId: env.theId }),
workflow: 'startDeployment'
},
setDeploymentStateCreated: {
dependsOn: ['startNewDeployment'],
input: (env) => {
return { state: 'Running', id: env.theId };
},
activity: 'setDeploymentDocState',
},
}
},
output: function(results) {
return {
env: {
deployment: results.startNewDeployment
}
};
}
};
|
'use strict';
// workflows/createDeployment
var Joi = require('joi');
module.exports = {
schema: Joi.object({
deployerId: Joi.string().required(),
name: Joi.string().min(1).required(),
}).required().unknown(true),
version: '1.0',
decider: function(args) {
return {
createDeploymentDoc: {
activity: 'createDeploymentDoc',
input: (env) => ({}),
output: (env) => ({ theId: env.id })
},
startNewDeployment: {
dependsOn: ['createDeploymentDoc'],
input: (env) => ({ deploymentId: env.theId }),
workflow: 'startDeployment'
},
setDeploymentStateCreated: {
dependsOn: ['startNewDeployment'],
input: (env) => ({ state: 'Running', id: env.deploymentId }),
activity: 'setDeploymentDocState',
},
}
},
output: function(results) {
return {
env: {
deployment: results.startNewDeployment
}
};
}
};
|
Check for entities ahead before moving forward.
|
package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import java.util.Collection;
/**
* Lua API function to move one block forward.
*/
public class MoveForwardFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());
Collection<Entity> entities = targetLocation.getWorld().getNearbyEntities(targetLocation.getBlock().getLocation().add(0.5, 0.5, 0.5), 0.5, 0.5, 0.5);
if (!targetLocation.getBlock().getType().isSolid()
&& !targetLocation.getBlock().getRelative(BlockFace.UP).getType().isSolid()
&& entities.isEmpty()) {
getApi().getStationaryBehavior().setLocation(targetLocation);
}
return LuaValue.NIL;
}
}
|
package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to move one block forward.
*/
public class MoveForwardFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());
if (!targetLocation.getBlock().getType().isSolid()
&& !targetLocation.getBlock().getRelative(BlockFace.UP).getType().isSolid()) {
getApi().getStationaryBehavior().setLocation(targetLocation);
}
return LuaValue.NIL;
}
}
|
Revert "Implement send message functionality"
|
from lib.config import Config
from slackclient import SlackClient
class Tubey():
def __init__(self, **kwargs):
# cache the client in memory
self._client = None
def send_message(self, message):
raise NotImplemented
def get_client(self):
### Fetch a cached slack client or create one and return it ###
if self._client is not None:
return self._client
token = Config.get_variable('tubey_credentials', 'bot_oauth_token')
sc = SlackClient(token)
self._client = sc
return self._client
if __name__ == "__main__":
# params = {'channel': 'tubeydev', 'text': "Hi everybody! I'm a faige!"}
# client.api_call("chat.postMessage", **params)
|
from lib.config import Config
from slackclient import SlackClient
class Tubey():
def __init__(self, **kwargs):
### Cache the client in memory ###
self._client = None
def get_client(self):
### Fetch a cached slack client or create one and return it ###
if self._client is not None:
return self._client
token = Config.get_variable('tubey_credentials', 'bot_oauth_token')
sc = SlackClient(token)
self._client = sc
return self._client
def send_message(self, message):
### Sends message to the user/channel ###
params = {'channel': 'tubeydev', 'text': message}
#client = get_client(self)
self.get_client().api_call("chat.postMessage", **params)
if __name__ == "__main__":
#tubey = Tubey()
#tubey.send_message("This better work")
# params = {'channel': 'tubeydev', 'text': "Hi everybody! I'm a faige!"}
# client.api_call("chat.postMessage", **params)
|
Update service provider to reflect changes in Laravel.
|
<?php namespace Krucas\Notification;
use Illuminate\Support\ServiceProvider;
class NotificationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('edvinaskrucas/notification');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');
$this->app['notification'] = $this->app->share(function($app)
{
return new Notification($app['config'], $app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
|
<?php namespace Krucas\Notification;
use Illuminate\Support\ServiceProvider;
class NotificationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('edvinaskrucas/notification');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');
$this->app['notification'] = $this->app->share(function($app)
{
return new Notification($app['config'], $app['session']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
|
Add exit step and alter log
|
var Cylon = require('cylon');
var color = require('onecolor');
var config = require('./config.js');
if(config.uuid === "insert uuid here"){
console.log('please identify the bluetooth uuid of your sphero, see the readme!');
return;
}
var log = function(){
if(config.debugger){
console.log(arguments);
}
}
Cylon.robot({
connections: {
bluetooth: {
adaptor: 'central',
uuid: config.uuid,
module: 'cylon-ble'
}
},
devices: {
ollie: { driver: 'ollie'}
},
work: function(my) {
var set_colour = function(i, l){
var j = i;
var k = l;
return function(){
var colour = parseInt(color('hsl(' + Math.ceil(i/l * 360) + ', 80%, 70%)').hex().slice(1), 16)
log(j, colour.toString(16));
my.ollie.setRGB(colour);
if(i === l - 1){
log('END OF RUN');
process.exit();
}
};
};
my.ollie.wake(function(err, data){
log("wake");
for(var i = 1, l = 360; i < l; ++i ){
after((i * 20) + 500, set_colour(i,l));
}
});
}
}).start();
|
var Cylon = require('cylon');
var color = require('onecolor');
var config = require('./config.js');
if(config.uuid === "insert uuid here"){
console.log('please identify the bluetooth uuid of your sphero, see the readme!');
return;
}
var log = function(){
if(config.debugger){
console.log(arguments[0],arguments[1],arguments[2]);
}
}
Cylon.robot({
connections: {
bluetooth: {
adaptor: 'central',
uuid: config.uuid,
module: 'cylon-ble'
}
},
devices: {
ollie: { driver: 'ollie'}
},
work: function(my) {
var set_colour = function(i, l){
var j = i;
var k = l;
return function(){
var colour = parseInt(color('hsl(' + Math.ceil(i/l * 360) + ', 80%, 70%)').hex().slice(1), 16)
log(j, colour.toString(16));
my.ollie.setRGB(colour);
};
};
my.ollie.wake(function(err, data){
log("wake");
for(var i = 1, l = 360; i < l; ++i ){
after((i * 20) + 500, set_colour(i,l));
}
});
}
}).start();
|
Add binding name to route list command
|
<?php
namespace Honeybee\FrameworkBinding\Silex\Console\Command\Route;
use Honeybee\FrameworkBinding\Silex\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListRoutes extends Command
{
protected function configure()
{
$this
->setName('hlx:route:ls')
->setDescription('List registered routes.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getApplication()->getContainer();
foreach ($app['routes']->all() as $binding => $route) {
$methods = implode(',', $route->getMethods());
$output->writeln($binding.' => '.($methods ?: 'ANY').' '.$route->getPath());
}
}
}
|
<?php
namespace Honeybee\FrameworkBinding\Silex\Console\Command\Route;
use Honeybee\FrameworkBinding\Silex\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListRoutes extends Command
{
protected function configure()
{
$this
->setName('hlx:route:ls')
->setDescription('List registered routes.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getApplication()->getContainer();
foreach ($app['routes']->all() as $route) {
$methods = implode(',', $route->getMethods());
$output->writeln(($methods ?: 'ANY').' '.$route->getPath());
}
}
}
|
Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule”
|
# Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-6)
def tzname(self, dt):
return "US/Central"
def dst(self, dt):
return timedelta(0)
cst = CST()
class Schedule_Handler(webapp2.RequestHandler):
def get(self):
schedule = BlockModels.schedule()
tlocal = datetime.now(cst)
formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
template_values = {
'schedule': schedule,
'localtime': formNow,
}
template = jinja_environment.get_template('schedule.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/schedule', Schedule_Handler)
], debug=True)
|
# Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-6)
def tzname(self, dt):
return "US/Central"
def dst(self, dt):
return timedelta(0)
cst = CST()
class MainHandler(webapp2.RequestHandler):
def get(self):
schedule = BlockModels.schedule()
tlocal = datetime.now(cst)
formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
template_values = {
'schedule': schedule,
'localtime': formNow,
}
template = jinja_environment.get_template('Prototype1.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
|
Remove unnecessary push calls to improve readability
|
const isAuthorized = function () {
let isLoggedIn, characterID, isAdmin, isWhitelisted;
isLoggedIn = this.userId;
if (isLoggedIn) {
characterID = Meteor.users.findOne(this.userId).profile.eveOnlineCharacterId
isAdmin = characterID == Meteor.settings.public.adminID;
isWhitelisted = Whitelist.findOne({characterID: String(characterID)});
}
return isLoggedIn && (isAdmin || isWhitelisted);
}
Meteor.publish('authorizedPub', function () {
if (isAuthorized.call(this)) {
let cursors = [
Changes.find({}),
Characters.find({}),
Errors.find({}),
Keys.find({}),
Whitelist.find({}, {fields: {characterID: 1}})
];
return cursors;
}
else {
this.ready();
}
});
|
const isAuthorized = function () {
let isLoggedIn, characterID, isAdmin, isWhitelisted;
isLoggedIn = this.userId;
if (isLoggedIn) {
characterID = Meteor.users.findOne(this.userId).profile.eveOnlineCharacterId
isAdmin = characterID == Meteor.settings.public.adminID;
isWhitelisted = Whitelist.findOne({characterID: String(characterID)});
}
return isLoggedIn && (isAdmin || isWhitelisted);
}
Meteor.publish('authorizedPub', function () {
if (isAuthorized.call(this)) {
let cursors = [];
cursors.push(Changes.find({}));
cursors.push(Characters.find({}));
cursors.push(Errors.find({}));
cursors.push(Keys.find({}));
cursors.push(Whitelist.find({}, {fields: {characterID: 1}}));
return cursors;
}
else {
this.ready();
}
});
|
Update connected_to index from number to string to match the input numbering.
|
<?php
namespace OnlyBits\Outputs;
use OnlyBits\Connectors\WireAbstract;
class BinaryLight extends OutputAbstract
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct(1, false);
$this->state = false;
}
/**
* {@inheritdoc}
*/
public function connect(WireAbstract $wire, $pin = null)
{
$this->inputs["1"] = $wire->getValue();
$this->connected_to["1"] = $wire;
}
/**
* {@inheritdoc}
*/
public function show()
{
if (count($this->connected_to) > 0 && $this->connected_to["1"] instanceof WireAbstract) {
$this->inputs["1"] = $this->connected_to["1"]->getValue();
}
$this->state = $this->inputs["1"];
return $this->state;
}
}
|
<?php
namespace OnlyBits\Outputs;
use OnlyBits\Connectors\WireAbstract;
class BinaryLight extends OutputAbstract
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct(1, false);
$this->state = false;
}
/**
* {@inheritdoc}
*/
public function connect(WireAbstract $wire, $pin = null)
{
$this->inputs["1"] = $wire->getValue();
$this->connected_to[] = $wire;
}
/**
* {@inheritdoc}
*/
public function show()
{
if (count($this->connected_to) > 0 && $this->connected_to[0] instanceof WireAbstract) {
$this->inputs["1"] = $this->connected_to[0]->getValue();
}
$this->state = $this->inputs["1"];
return $this->state;
}
}
|
Rename and reorder CreateIndexes tests
|
<?php
namespace MongoDB\Tests\Operation;
use MongoDB\Operation\CreateIndexes;
class CreateIndexesTest extends TestCase
{
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @expectedExceptionMessage $indexes is not a list (unexpected index: "1")
*/
public function testConstructorIndexesArgumentMustBeAList()
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), [1 => ['key' => ['x' => 1]]]);
}
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @expectedExceptionMessage $indexes is empty
*/
public function testConstructorRequiresAtLeastOneIndex()
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), []);
}
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @dataProvider provideInvalidIndexSpecificationTypes
*/
public function testConstructorRequiresIndexSpecificationsToBeAnArray($index)
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), [$index]);
}
public function provideInvalidIndexSpecificationTypes()
{
return $this->wrapValuesForDataProvider($this->getInvalidArrayValues());
}
}
|
<?php
namespace MongoDB\Tests\Operation;
use MongoDB\Operation\CreateIndexes;
class CreateIndexesTest extends TestCase
{
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @expectedExceptionMessage $indexes is empty
*/
public function testCreateIndexesRequiresAtLeastOneIndex()
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), []);
}
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @expectedExceptionMessage $indexes is not a list (unexpected index: "1")
*/
public function testConstructorIndexesArgumentMustBeAList()
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), [1 => ['key' => ['x' => 1]]]);
}
/**
* @expectedException MongoDB\Exception\InvalidArgumentException
* @dataProvider provideInvalidIndexSpecificationTypes
*/
public function testCreateIndexesRequiresIndexSpecificationsToBeAnArray($index)
{
new CreateIndexes($this->getDatabaseName(), $this->getCollectionName(), [$index]);
}
public function provideInvalidIndexSpecificationTypes()
{
return $this->wrapValuesForDataProvider($this->getInvalidArrayValues());
}
}
|
Increase the pagination amount for blog app
|
"""
Blog App
This module provides generic django URL routing.
"""
from django.conf.urls import patterns, url
from tunobase.blog import views
urlpatterns = patterns('',
url(r'^list/$',
views.BlogList.as_view(
template_name='blog/blog_list.html'
),
name='blog_list'
),
url(r'^detail/(?P<slug>[\w-]+)/$',
views.BlogEntryDetail.as_view(
template_name='blog/blog_entry_detail.html'
),
name='blog_entry_detail'
),
url(r'^(?P<slug>[\w-]+)/$',
views.BlogDetail.as_view(
paginate_by=10,
template_name='blog/blog_detail.html',
partial_template_name='blog/includes/blog_entries.html'
),
name='blog_detail'
),
(r'^feed/$', views.BlogFeed()),
)
|
"""
Blog App
This module provides generic django URL routing.
"""
from django.conf.urls import patterns, url
from tunobase.blog import views
urlpatterns = patterns('',
url(r'^list/$',
views.BlogList.as_view(
template_name='blog/blog_list.html'
),
name='blog_list'
),
url(r'^detail/(?P<slug>[\w-]+)/$',
views.BlogEntryDetail.as_view(
template_name='blog/blog_entry_detail.html'
),
name='blog_entry_detail'
),
url(r'^(?P<slug>[\w-]+)/$',
views.BlogDetail.as_view(
paginate_by=1,
template_name='blog/blog_detail.html',
partial_template_name='blog/includes/blog_entries.html'
),
name='blog_detail'
),
(r'^feed/$', views.BlogFeed()),
)
|
Remove language from HTML tag
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Speedtests</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="icon" href="speedometer_transparent.png">
<link rel="apple-touch-icon" href="speedometer.png">
<!-- Stylesheets -->
<link rel="stylesheet" href="vendor/morris/morris.css">
<link rel="stylesheet" href="vendor/addtohomescreen/addtohomescreen.css">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="speedtest-chart"></div>
<!-- Scripts -->
<script src="vendor/jquery.min.js"></script>
<script src="vendor/raphael-min.js"></script>
<script src="vendor/morris/morris.min.js"></script>
<script src="vendor/addtohomescreen/addtohomescreen.min.js"></script>
<script src="main.js"></script>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Speedtests</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="icon" href="speedometer_transparent.png">
<link rel="apple-touch-icon" href="speedometer.png">
<!-- Stylesheets -->
<link rel="stylesheet" href="vendor/morris/morris.css">
<link rel="stylesheet" href="vendor/addtohomescreen/addtohomescreen.css">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="speedtest-chart"></div>
<!-- Scripts -->
<script src="vendor/jquery.min.js"></script>
<script src="vendor/raphael-min.js"></script>
<script src="vendor/morris/morris.min.js"></script>
<script src="vendor/addtohomescreen/addtohomescreen.min.js"></script>
<script src="main.js"></script>
</body>
</html>
|
Move ecdsa from extras_require to install_requires
|
#from distribute_setup import use_setuptools
#use_setuptools()
from setuptools import setup, find_packages
from os.path import dirname, join
here = dirname(__file__)
setup(
name='btchip-python',
version='0.1.28',
author='BTChip',
author_email='hello@ledger.fr',
description='Python library to communicate with Ledger Nano dongle',
long_description=open(join(here, 'README.md')).read(),
url='https://github.com/LedgerHQ/btchip-python',
packages=find_packages(),
install_requires=['hidapi>=0.7.99', 'ecdsa>=0.9'],
extras_require = {
'smartcard': [ 'python-pyscard>=1.6.12-4build1' ]
},
include_package_data=True,
zip_safe=False,
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X'
]
)
|
#from distribute_setup import use_setuptools
#use_setuptools()
from setuptools import setup, find_packages
from os.path import dirname, join
here = dirname(__file__)
setup(
name='btchip-python',
version='0.1.28',
author='BTChip',
author_email='hello@ledger.fr',
description='Python library to communicate with Ledger Nano dongle',
long_description=open(join(here, 'README.md')).read(),
url='https://github.com/LedgerHQ/btchip-python',
packages=find_packages(),
install_requires=['hidapi>=0.7.99'],
extras_require = {
'smartcard': [ 'python-pyscard>=1.6.12-4build1', 'ecdsa>=0.9' ]
},
include_package_data=True,
zip_safe=False,
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X'
]
)
|
Allow setting hide text related css classes on wrapper
So far the css classes `hide_content_with_text` and
`no_hidden_text_indicator` had to be present on the page's `section`
element. Allowing them also on the `.content_and_background` wrapper
element makes things much easer to control for page types since that
element is rendered by them.
|
(function($) {
$.widget('pageflow.hiddenTextIndicator', {
_create: function() {
var parent = this.options.parent,
that = this;
parent.on('pageactivate', function(event) {
var pageOrPageWrapper = $(event.target).add('.content_and_background', event.target);
that.element.toggleClass('invert', $(event.target).hasClass('invert'));
that.element.toggleClass('hidden',
pageOrPageWrapper.hasClass('hide_content_with_text') ||
pageOrPageWrapper.hasClass('no_hidden_text_indicator'));
});
parent.on('hidetextactivate', function() {
that.element.addClass('visible');
});
parent.on('hidetextdeactivate', function() {
that.element.removeClass('visible');
});
}
});
}(jQuery));
|
(function($) {
$.widget('pageflow.hiddenTextIndicator', {
_create: function() {
var parent = this.options.parent,
that = this;
parent.on('pageactivate', function(event) {
that.element.toggleClass('invert', $(event.target).hasClass('invert'));
that.element.toggleClass('hidden',
$(event.target).hasClass('hide_content_with_text') ||
$(event.target).hasClass('no_hidden_text_indicator'));
});
parent.on('hidetextactivate', function() {
that.element.addClass('visible');
});
parent.on('hidetextdeactivate', function() {
that.element.removeClass('visible');
});
}
});
}(jQuery));
|
Fix login error: password check
|
var response = require('response');
var JSONStream = require('JSONStream');
var formBody = require('body/form');
var redirect = require('../lib/redirect');
exports.install = function (server, prefix) {
var prefix = prefix || '/sessions';
/*
* Create a session
*/
server.route(prefix, function (req, res) {
if (req.method === 'POST') {
formBody(req, res, function (err, body) {
server.accounts.verify('basic', body, function (err, ok, id) {
if (err) {
console.error(err);
} else if (!ok) {
console.error("Password is incorrect!");
} else {
server.auth.login(res, { username: id }, function (loginerr, data) {
if (loginerr) console.error(loginerr);
});
}
redirect(res, '/');
});
});
}
});
/*
* Destroy a session
*/
server.route(prefix + '/destroy', function (req, res) {
server.auth.delete(req, function () {
server.auth.cookie.destroy(res);
redirect(res, '/');
});
});
}
|
var response = require('response');
var JSONStream = require('JSONStream');
var formBody = require('body/form');
var redirect = require('../lib/redirect');
exports.install = function (server, prefix) {
var prefix = prefix || '/sessions';
/*
* Create a session
*/
server.route(prefix, function (req, res) {
if (req.method === 'POST') {
formBody(req, res, function (err, body) {
var creds = { username: body.username, password: body.password };
server.accounts.verify('basic', body, function (err, ok, id) {
if (err) console.error(err);
server.auth.login(res, { username: id }, function (loginerr, data) {
if (loginerr) console.error(loginerr);
redirect(res, '/');
});
});
});
}
});
/*
* Destroy a session
*/
server.route(prefix + '/destroy', function (req, res) {
server.auth.delete(req, function () {
server.auth.cookie.destroy(res);
redirect(res, '/');
});
});
}
|
Update to beautify HTML output from Jade
|
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
// require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.bodyParser()); // get information from html forms
app.set('view engine', 'jade'); // set up ejs for templating
app.locals.pretty = true;
// required for passport
app.use(express.session({ secret: 'iamthebest' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
});
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
|
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
// require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.bodyParser()); // get information from html forms
app.set('view engine', 'jade'); // set up ejs for templating
// required for passport
app.use(express.session({ secret: 'iamthebest' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
});
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
|
Include the new PaymentCondition class in the classinclude file
|
<?php
/*************************************************************************************************
* Copyright 2015 MajorLabel -- This file is a part of MajorLabel coreBOS Customizations.
* Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
* file except in compliance with the License. You can redistribute it and/or modify it
* under the terms of the License. MajorLabel reserves all rights not expressly
* granted by the License. coreBOS distributed by MajorLabel is distributed in
* the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Unless required by
* applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing
* permissions and limitations under the License. You may obtain a copy of the License
* at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
*************************************************************************************************
* Author : MajorLabel, Guido Goluke
*************************************************************************************************/
include('modules/ExactOnline/classes/ExactSettingsDB.class.php');
include('modules/ExactOnline/classes/ExactOAuth.class.php');
include('modules/ExactOnline/classes/ExactApi.class.php');
include('modules/ExactOnline/classes/ExactAccounts.class.php');
include('modules/ExactOnline/classes/ExactItems.class.php');
include('modules/ExactOnline/classes/ExactSalesInvoice.class.php');
include('modules/ExactOnline/classes/ExactPaymentCond.class.php');
?>
|
<?php
/*************************************************************************************************
* Copyright 2015 MajorLabel -- This file is a part of MajorLabel coreBOS Customizations.
* Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
* file except in compliance with the License. You can redistribute it and/or modify it
* under the terms of the License. MajorLabel reserves all rights not expressly
* granted by the License. coreBOS distributed by MajorLabel is distributed in
* the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Unless required by
* applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing
* permissions and limitations under the License. You may obtain a copy of the License
* at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
*************************************************************************************************
* Author : MajorLabel, Guido Goluke
*************************************************************************************************/
include('modules/ExactOnline/classes/ExactSettingsDB.class.php');
include('modules/ExactOnline/classes/ExactOAuth.class.php');
include('modules/ExactOnline/classes/ExactApi.class.php');
include('modules/ExactOnline/classes/ExactAccounts.class.php');
include('modules/ExactOnline/classes/ExactItems.class.php');
include('modules/ExactOnline/classes/ExactSalesInvoice.class.php');
?>
|
Change unicode test string to ascii
|
from django.test import TestCase
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from whats_fresh.models import *
from django.contrib.gis.db import models
import os
import time
import sys
import datetime
class PreparationsTestCase(TestCase):
def setUp(self):
self.expected_fields = {
'name': models.TextField,
'description': models.TextField,
'additional_info': models.TextField,
'id': models.AutoField
}
def test_fields_exist(self):
model = models.get_model('whats_fresh', 'Preparation')
for field, field_type in self.expected_fields.items():
self.assertEqual(
field_type, type(model._meta.get_field_by_name(field)[0]))
def test_no_additional_fields(self):
fields = Vendor._meta.get_all_field_names()
self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys()))
|
from django.test import TestCase
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from whats_fresh.models import *
from django.contrib.gis.db import models
import os
import time
import sys
import datetime
class PreparationsTestCase(TestCase):
def setUp(self):
self.expected_fields = {
'name': models.TextField,
'description': models.TextField,
'additional_info': models.TextField,
u'id': models.AutoField
}
def test_fields_exist(self):
model = models.get_model('whats_fresh', 'Preparation')
for field, field_type in self.expected_fields.items():
self.assertEqual(
field_type, type(model._meta.get_field_by_name(field)[0]))
def test_no_additional_fields(self):
fields = Vendor._meta.get_all_field_names()
self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys()))
|
Check for valid currencies in a file
|
import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5].upper()
to = self.msg[6].upper()
combined = frm, to
## If first value is float and currencies are valid
if isinstance( amount, float ) and frm in open("modules/data/currencies.txt").read():
print("Moi")
frm = urllib.parse.quote(frm)
to = urllib.parse.quote(to)
url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
html = syscmd.getHtml(self, url, True)
else:
self.send_chan("Usage: !currency <amount> <from> <to>")
try:
soup = BeautifulSoup(html)
result = soup.findAll("div", {"id" : "currency_converter_result"})
result = "{0}".format(result[0])
trimmed = re.sub('<[^<]+?>', '', result)
self.send_chan(trimmed)
except:
pass
|
import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
else:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5]
to = self.msg[6]
if isinstance( amount, float ):
frm = urllib.parse.quote(frm)
to = urllib.parse.quote(to)
url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
html = syscmd.getHtml(self, url, True)
try:
soup = BeautifulSoup(html)
result = soup.findAll("div", {"id" : "currency_converter_result"})
result = "{0}".format(result[0])
trimmed = re.sub('<[^<]+?>', '', result)
self.send_chan(trimmed)
except:
pass
|
Update tags for Cache config option
Updated tags for config options consistency [1].
[1] https://wiki.openstack.org/wiki/ConfigOptionsConsistency
Change-Id: I3f82d2b4d60028221bc861bfe0fe5dff6efd971f
Implements: Blueprint centralize-config-options-newton
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2016 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_cache import core
def register_opts(conf):
core.configure(conf)
def list_opts():
return core._opts.list_opts()
|
# needs:fix_opt_description
# needs:check_deprecation_status
# needs:check_opt_group_and_type
# needs:fix_opt_description_indentation
# needs:fix_opt_registration_consistency
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2016 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_cache import core
def register_opts(conf):
core.configure(conf)
def list_opts():
return core._opts.list_opts()
|
Add externs for Polymer template instance properties
This symbols can collide when using the `shadyUpgradeFragment` optimization.
|
/**
* @fileoverview Externs for closure compiler
* @externs
*/
/**
* Block renaming of properties added to Node to
* prevent conflicts with other closure-compiler code.
* @type {Object}
*/
EventTarget.prototype.__handlers;
/** @type {Object} */
Node.prototype.__shady;
/** @interface */
function IWrapper() {}
/** @type {Object} */
IWrapper.prototype._activeElement;
// NOTE: For some reason, Closure likes to remove focus() from the IWrapper
// class. Not yet clear why focus() is affected and not any other methods (e.g.
// blur).
IWrapper.prototype.focus = function() {};
/** @type {!boolean|undefined} */
Event.prototype.__composed;
/** @type {!boolean|undefined} */
Event.prototype.__immediatePropagationStopped;
/** @type {!Node|undefined} */
Event.prototype.__relatedTarget;
/** @type {!Array<!EventTarget>|undefined} */
Event.prototype.__composedPath;
/** @type {!Array<!EventTarget>|undefined} */
Event.prototype.__relatedTargetComposedPath;
/**
* Prevent renaming of this method on ShadyRoot for testing and debugging.
*/
ShadowRoot.prototype._renderSelf = function(){};
// Prevent renaming of properties used by Polymer templates with
// shadyUpgradeFragment optimization
/** @type {!Object} */
DocumentFragment.prototype.$;
/** @type {boolean} */
DocumentFragment.prototype.__noInsertionPoint;
/** @type {!Array<!Node>} */
DocumentFragment.prototype.nodeList;
|
/**
* @fileoverview Externs for closure compiler
* @externs
*/
/**
* Block renaming of properties added to Node to
* prevent conflicts with other closure-compiler code.
* @type {Object}
*/
EventTarget.prototype.__handlers;
/** @type {Object} */
Node.prototype.__shady;
/** @interface */
function IWrapper() {}
/** @type {Object} */
IWrapper.prototype._activeElement;
// NOTE: For some reason, Closure likes to remove focus() from the IWrapper
// class. Not yet clear why focus() is affected and not any other methods (e.g.
// blur).
IWrapper.prototype.focus = function() {};
/** @type {!boolean|undefined} */
Event.prototype.__composed;
/** @type {!boolean|undefined} */
Event.prototype.__immediatePropagationStopped;
/** @type {!Node|undefined} */
Event.prototype.__relatedTarget;
/** @type {!Array<!EventTarget>|undefined} */
Event.prototype.__composedPath;
/** @type {!Array<!EventTarget>|undefined} */
Event.prototype.__relatedTargetComposedPath;
/**
* Prevent renaming of this method on ShadyRoot for testing and debugging.
*/
ShadowRoot.prototype._renderSelf = function(){};
|
Remove prop-types and create-react-class as externals.
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
export default {
entry: 'src/index.js',
plugins: [
commonjs(),
resolve({
customResolveOptions: {
moduleDirectory: 'node_modules',
}
}),
babel({
exclude: 'node_modules/**'
})
],
external: ['knockout', 'react'],
globals: {
knockout: 'ko',
react: 'React'
},
moduleName: 'komx-react',
targets: [
{ dest: 'dist/komx-react.umd.js', format: 'umd' },
{ dest: 'dist/komx-react.es.js', format: 'es' }
],
};
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
export default {
entry: 'src/index.js',
plugins: [
commonjs(),
resolve({
customResolveOptions: {
moduleDirectory: 'node_modules',
}
}),
babel({
exclude: 'node_modules/**'
})
],
external: ['knockout', 'react', 'prop-types', 'create-react-class'],
globals: {
knockout: 'ko',
react: 'React',
'prop-types': 'PropTypes',
'create-react-class': 'createReactClass'
},
moduleName: 'komx-react',
targets: [
{ dest: 'dist/komx-react.umd.js', format: 'umd' },
{ dest: 'dist/komx-react.es.js', format: 'es' }
],
};
|
Update Cloud Files mock to match.
|
// Mock pkgcloud functionality.
var
util = require("util"),
stream = require("stream"),
Writable = stream.Writable,
Readable = stream.Readable;
util.inherits(Sink, Writable);
function Sink(options) {
Writable.call(this, options);
var self = this;
this._write = function (chunk, enc, next) {
next();
};
this.on("finish", function () {
self.emit("success");
});
}
exports.create = function() {
return {
// Internal state, exposed for expectation-writing convenience.
uploaded: [],
downloaded: [],
deleted: [],
content: {},
// Mocked pkgcloud client API.
upload: function (params) {
this.uploaded.push(params);
return new Sink();
},
download: function (params) {
this.downloaded.push(params);
var rs = new Readable();
rs.push(this.content[params.remote]);
rs.push(null);
rs.on('end', function () {
rs.emit('complete', { statusCode: 200 });
});
return rs;
},
removeFile: function (container, name, callback) {
this.deleted.push(name);
delete this.content[name];
callback(null);
}
};
};
|
// Mock pkgcloud functionality.
var
util = require("util"),
stream = require("stream"),
Writable = stream.Writable,
Readable = stream.Readable;
util.inherits(Sink, Writable);
function Sink(options) {
Writable.call(this, options);
var self = this;
this._write = function (chunk, enc, next) {
next();
};
this.on("finish", function () {
self.emit("success");
});
}
exports.create = function() {
return {
// Internal state, exposed for expectation-writing convenience.
uploaded: [],
downloaded: [],
deleted: [],
content: {},
// Mocked pkgcloud client API.
upload: function (params) {
this.uploaded.push(params);
return new Sink();
},
download: function (params) {
this.downloaded.push(params);
var rs = new Readable();
rs.push(this.content[params.remote]);
rs.push(null);
return rs;
},
removeFile: function (container, name, callback) {
this.deleted.push(name);
delete this.content[name];
callback(null);
}
};
};
|
Fix issue with ‘respect user's privacy’ code!
It’s Js and not PHP, stupid!
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
// Respect user's privacy:
// https://blog.j15h.nu/web-analytics-privacy/
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?>
<script>
// Respect user's privacy
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1') {
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview');
}
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'):
// Respect user's privacy (https://blog.j15h.nu/web-analytics-privacy/)
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1'): ?>
<script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php endif; ?>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
Fix player stats not actually working
Fixed what @kayteh broke
|
$(document).ready(function(event){
$('#submit').click(function(event){
getData();
});
$('#formThing').submit(function(event){
event.preventDefault();
getData();
});
});
function getData(){
$.get('https://player.me/api/v1/users/' + $('#inputText').val(), "username=true", function(outer){
var data = outer.results
var avatar = "https://player.me/api/v1/users/" + data['id'] + "/avatars";
var username = data['id']['username'];
var followers = data['followers_count'];
var joined = data['created_at'];
var html = '<center><img src="' + avatar + '"width="100px" height="100px" style="border:3px solid white">';
html += '<h1>' + username + '</h1>';
html += '<br><b>Followers: </b>' + followers;
html += '<br><b>Joined on: </b>' + joined.replace('T', ' at ');
$('.profile').html(html);
});
}
|
$(document).ready(function(event){
$('#submit').click(function(event){
getData();
});
$('#formThing').submit(function(event){
event.preventDefault();
getData();
});
});
function getData(){
$.get('https://player.me/api/v1/users/' + $('#inputText').val(), "?username=true", function(outer){
var data = outer.results
var avatar = "https://player.me/api/v1/users/" + data['id'] + "/avatars";
var username = data['id']['username'];
var followers = data['followers_count'];
var joined = data['created_at'];
var html = '<center><img src="' + avatar + '"width="100px" height="100px" style="border:3px solid white">';
html += '<h1>' + username + '</h1>';
html += '<br><b>Followers: </b>' + followers;
html += '<br><b>Joined on: </b>' + joined.replace('T', ' at ');
$('.profile').html(html);
});
}
|
Fix label of radio field.
|
<div class="{{$config['divClass']}} @if($errors)f-error @endif">
<label>{{$label}}</label>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
@foreach($radios as $radio)
<label for="{{$radio['id']}}">
<input
type="{{$type}}"
id="{{$radio['id']}}"
name="{{$name}}"
@if($value == $radio['value']) checked @endif
@if($radio['value'])value="{{$radio['value']}}" @endif
@if($required)required @endif
@foreach($radio['attr'] as $key => $value)
@if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
@endforeach
>
{{$radio['label']}} @if($required)<i class="f-required">*</i>@endif
</label>
@endforeach
</div>
|
<div class="{{$config['divClass']}} @if($errors)f-error @endif">
<label>{{$label}}</label>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
@foreach($radios as $radio)
<label for="{{$name}}">
<input
type="{{$type}}"
id="{{$radio['id']}}"
name="{{$name}}"
@if($value == $radio['value']) checked @endif
@if($radio['value'])value="{{$radio['value']}}" @endif
@if($required)required @endif
@foreach($radio['attr'] as $key => $value)
@if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
@endforeach
>
{{$radio['label']}} @if($required)<i class="f-required">*</i>@endif
</label>
@endforeach
</div>
|
Reformat output to match other examples.
Signed-off-by: Blaž Hrastnik <e26a9cc74a1e4715764aa09d1071b1ef182b1807@gmail.com>
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/flynn/go-flynn/migrate"
"github.com/flynn/go-flynn/postgres"
)
func main() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
db, err := postgres.Open("", "")
if err != nil {
log.Fatal(err)
}
m := migrate.NewMigrations()
m.Add(1, "CREATE SEQUENCE hits")
if err := m.Migrate(db.DB); err != nil {
log.Fatal(err)
}
stmt, err := db.Prepare("SELECT nextval('hits')")
if err != nil {
log.Fatal(err)
}
port := os.Getenv("PORT")
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
var count int
if err := stmt.QueryRow().Scan(&count); err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
fmt.Fprintf(w, "Hello from Flynn on port %s from container %s\nHits = %d\n", port, os.Getenv("HOSTNAME"), count)
})
fmt.Println("hitcounter listening on port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/flynn/go-flynn/migrate"
"github.com/flynn/go-flynn/postgres"
)
func main() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
db, err := postgres.Open("", "")
if err != nil {
log.Fatal(err)
}
m := migrate.NewMigrations()
m.Add(1, "CREATE SEQUENCE hits")
if err := m.Migrate(db.DB); err != nil {
log.Fatal(err)
}
stmt, err := db.Prepare("SELECT nextval('hits')")
if err != nil {
log.Fatal(err)
}
port := os.Getenv("PORT")
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
var count int
if err := stmt.QueryRow().Scan(&count); err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
fmt.Fprintf(w, "Hello from Go+PostgreSQL on Flynn: port=%s hits=%d container=%s\n", port, count, os.Getenv("HOSTNAME"))
})
fmt.Println("hitcounter listening on port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
|
Read "autofmt" option from storage
|
import browser from 'webextension-polyfill';
import render from '../../common/popup/render';
import enhance from '../../common/enhance';
import '../../common/popup/popup.scss';
import store from '../store';
const background = browser.extension.getBackgroundPage();
function pbcopy(text) {
const input = document.createElement('textarea');
input.textContent = text;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
function close() {
window.close();
}
function grab(text) {
pbcopy(text);
close();
}
function openext() {
return true;
}
async function load() {
const { tickets, errors } = await background.getTickets();
const { options, templates } = await store.get(null);
const enhancer = enhance(templates, options.autofmt);
render(tickets.map(enhancer), errors, { grab, openext });
}
window.onload = load;
|
import browser from 'webextension-polyfill';
import render from '../../common/popup/render';
import enhance from '../../common/enhance';
import '../../common/popup/popup.scss';
import store from '../store';
const background = browser.extension.getBackgroundPage();
function pbcopy(text) {
const input = document.createElement('textarea');
input.textContent = text;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
function close() {
window.close();
}
function grab(text) {
pbcopy(text);
close();
}
function openext() {
return true;
}
async function load() {
const { tickets, errors } = await background.getTickets();
const { templates } = await store.get(null);
const enhancer = enhance(templates);
render(tickets.map(enhancer), errors, { grab, openext });
}
window.onload = load;
|
Clean up warnings in test fixture
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.testfixture.aot.generator.visibility;
import org.springframework.core.ResolvableType;
public class PublicFactoryBean<T> {
PublicFactoryBean(Class<T> type) {
}
public static PublicFactoryBean<ProtectedType> protectedTypeFactoryBean() {
return new PublicFactoryBean<>(ProtectedType.class);
}
public static ResolvableType resolveToProtectedGenericParameter() {
return ResolvableType.forClassWithGenerics(PublicFactoryBean.class, ProtectedType.class);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.testfixture.aot.generator.visibility;
import org.springframework.core.ResolvableType;
public class PublicFactoryBean<T> {
private final Class<T> type;
public PublicFactoryBean(Class<T> type) {
this.type = type;
}
public static PublicFactoryBean<ProtectedType> protectedTypeFactoryBean() {
return new PublicFactoryBean<>(ProtectedType.class);
}
public static ResolvableType resolveToProtectedGenericParameter() {
return ResolvableType.forClassWithGenerics(PublicFactoryBean.class, ProtectedType.class);
}
}
|
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
|
"""
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
SESSION_COOKIE_SAMESITE = 'Lax'
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
BABEL_DEFAULT_LOCALE = LOCALE
BABEL_DEFAULT_TIMEZONE = TIMEZONE
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
"""
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
BABEL_DEFAULT_LOCALE = LOCALE
BABEL_DEFAULT_TIMEZONE = TIMEZONE
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
Prepend '-S rubocop' to version args
Fixes #17
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides an interface to rubocop."""
syntax = ('ruby', 'ruby on rails', 'rspec')
cmd = 'ruby -S rubocop --format emacs'
version_args = '-S rubocop --version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.15.0'
regex = (
r'^.+?:(?P<line>\d+):(?P<col>\d+): '
r'(:?(?P<warning>[RCW])|(?P<error>[EF])): '
r'(?P<message>.+)'
)
tempfile_suffix = 'rb'
config_file = ('--config', '.rubocop.yml')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides an interface to rubocop."""
syntax = ('ruby', 'ruby on rails', 'rspec')
cmd = 'ruby -S rubocop --format emacs'
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.15.0'
regex = (
r'^.+?:(?P<line>\d+):(?P<col>\d+): '
r'(:?(?P<warning>[RCW])|(?P<error>[EF])): '
r'(?P<message>.+)'
)
tempfile_suffix = 'rb'
config_file = ('--config', '.rubocop.yml')
|
Validate resource schema are valid on startup
|
'use strict'
const schemaValidator = module.exports = { }
schemaValidator.validate = function (resources) {
Object.keys(resources).forEach(resource => {
Object.keys(resources[resource].attributes).forEach(attribute => {
let joiSchema = resources[resource].attributes[attribute]
if (!joiSchema._settings) return
let types = joiSchema._settings.__one || joiSchema._settings.__many
types.forEach(type => {
if (!resources[type]) {
throw new Error(`'${resource}'.'${attribute}' is defined to hold a relation with '${type}', but '${type}' is not a valid resource name!`)
}
})
let foreignRelation = joiSchema._settings.__as
if (!foreignRelation) return
let backReference = resources[types[0]].attributes[foreignRelation]
if (!backReference) {
throw new Error(`'${resource}'.'${attribute}' is defined as being a foreign relation to the primary '${types[0]}'.'${foreignRelation}', but that primary relationship does not exist!`)
}
})
})
}
|
'use strict'
const schemaValidator = module.exports = { }
schemaValidator.validate = function (resources) {
Object.keys(resources).forEach(resource => {
Object.keys(resources[resource].attributes).forEach(attribute => {
let joiSchema = resources[resource].attributes[attribute]
if (!joiSchema._settings) return
let types = joiSchema._settings.__one || joiSchema._settings.__many
types.forEach(type => {
if (!resources[type]) {
throw new Error(`Error: '${resource}'.'${attribute}' is defined to hold a relation with '${type}', but '${type}' is not a valid resource name!`)
}
})
let foreignRelation = joiSchema._settings.__as
if (!foreignRelation) return
let backReference = resources[types[0]].attributes[foreignRelation]
if (!backReference) {
throw new Error(`Error: '${resource}'.'${attribute}' is defined as being a foreign relation to the primary '${types[0]}'.'${foreignRelation}', but that primary relationship does not exist!`)
}
})
})
}
|
Change way CSV parser opts are passed in
- i'll open that up to the CLI args somehow so the user can alter the 'fast-csv' package parsing args
|
const fs = require('fs')
const csv = require('fast-csv')
const transformToDocs = require('./transform-data-to-docs')
/**
* Input should be a single CSV row at a time. From one row we can transform a number of documents,
* each of which will get serialised to JSON and written to the output stream.
*/
const onInputData = outputStream => data =>
transformToDocs(data)
.forEach(doc => outputStream.write(`${JSON.stringify(doc)}\n`))
const onInputFinish = outputStream => () => {
console.log('Conversion finished.')
if (outputStream !== process.stdout) {
outputStream.end() // Not sure if neccessary
}
}
function convert({
input,
output,
maxVisits = 10,
parsingOpts = {},
}) {
const inputStream = input ? fs.createReadStream(input) : process.stdin
const outputStream = output ? fs.createWriteStream(output) : process.stdout
// Set up conversion stream
const converterStream = csv(Object.assign({}, { headers: true, ignoreEmpty: true }, parsingOpts))
converterStream.on('data', onInputData(outputStream))
converterStream.on('end', onInputFinish(outputStream))
// Start piping the input file over the conversion stream
inputStream.pipe(converterStream)
}
module.exports = convert
|
const fs = require('fs')
const csv = require('fast-csv')
const transformToDocs = require('./transform-data-to-docs')
/**
* Input should be a single CSV row at a time. From one row we can transform a number of documents,
* each of which will get serialised to JSON and written to the output stream.
*/
const onInputData = outputStream => data =>
transformToDocs(data)
.forEach(doc => outputStream.write(`${JSON.stringify(doc)}\n`))
const onInputFinish = outputStream => () => {
console.log('Conversion finished.')
if (outputStream !== process.stdout) {
outputStream.end() // Not sure if neccessary
}
}
function convert({
input,
output,
maxVisits = 10,
parsingOpts = {
headers: true,
ignoreEmpty: true,
},
}) {
const inputStream = input ? fs.createReadStream(input) : process.stdin
const outputStream = output ? fs.createWriteStream(output) : process.stdout
// Set up conversion stream
const converterStream = csv(parsingOpts)
converterStream.on('data', onInputData(outputStream))
converterStream.on('end', onInputFinish(outputStream))
// Start piping the input file over the conversion stream
inputStream.pipe(converterStream)
}
module.exports = convert
|
Change cross-origin check to work behind proxies
Signed-off-by: Jan Dvořák <86df5a4870880bf501c926309e3bcfbe57789f3f@anilinux.org>
|
#!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['internal_origin_only']
from urllib.parse import urlparse
from functools import wraps
from werkzeug.exceptions import Forbidden
import flask
import re
def internal_origin_only(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
host = flask.request.headers.get('X-Forwarded-Host') or \
flask.request.headers.get('Host', '')
h = urlparse('http://' + host)
origin = flask.request.headers.get('Origin') or \
flask.request.headers.get('Referer') or \
host
o = urlparse(origin)
if h.hostname != o.hostname:
raise Forbidden('Cross-Site Request Forbidden')
return fn(*args, **kwargs)
return wrapper
# vim:set sw=4 ts=4 et:
|
#!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['internal_origin_only']
from urllib.parse import urlparse
from functools import wraps
from werkzeug.exceptions import Forbidden
import flask
import re
def internal_origin_only(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
h = urlparse('http://' + flask.request.headers.get('Host', ''))
host = '%s:%i' % (h.hostname, h.port or 80)
if 'Origin' in flask.request.headers:
o = urlparse(flask.request.headers.get('Origin'))
origin = '%s:%i' % (o.hostname, o.port or 80)
elif 'Referer' in flask.request.headers:
r = urlparse(flask.request.headers.get('Referer'))
origin = '%s:%i' % (r.hostname, r.port or 80)
else:
origin = host
if host != origin:
raise Forbidden('Cross-Site Request Forbidden')
return fn(*args, **kwargs)
return wrapper
# vim:set sw=4 ts=4 et:
|
Read test host from env variable
Signed-off-by: Max Ehrlich <c7cd0513ef0c504f678ca33c2b168f4f84cd4d51@gmail.com>
|
package acmedns
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
var (
acmednsLiveTest bool
acmednsHost string
acmednsAccountsJson []byte
acmednsDomain string
)
func init() {
acmednsHost = os.Getenv("ACME_DNS_HOST")
acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNTS_JSON"))
acmednsDomain = os.Getenv("ACME_DNS_DOMAIN")
if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
acmednsLiveTest = true
}
}
func TestLiveAcmeDnsPresent(t *testing.T) {
if !acmednsLiveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
assert.NoError(t, err)
err = provider.Present(acmednsDomain, "", "123d==")
assert.NoError(t, err)
}
|
package acmedns
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
var (
acmednsLiveTest bool
acmednsHost string
acmednsAccountsJson []byte
acmednsDomain string
)
func init() {
acmednsHost = os.Getenv("ACME_DNS_HOST")
acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNTS_JSON"))
if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
acmednsLiveTest = true
}
}
func TestLiveAcmeDnsPresent(t *testing.T) {
if !acmednsLiveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
assert.NoError(t, err)
err = provider.Present(acmednsDomain, "", "123d==")
assert.NoError(t, err)
}
|
Add ability to reference users by ID
|
package co.phoenixlab.discord.commands;
import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;
public class CommandUtil {
static User findUser(MessageContext context, String username) {
Message message = context.getMessage();
User user;
Channel channel = context.getApiClient().getChannelById(message.getChannelId());
// Attempt to find the given user
// If the user is @mentioned, try that first
if (message.getMentions() != null && message.getMentions().length > 0) {
user = message.getMentions()[0];
} else {
user = context.getApiClient().findUser(username, channel.getParent());
}
// Try matching by ID
if (user == null) {
user = context.getApiClient().getUserById(username);
}
return user;
}
}
|
package co.phoenixlab.discord.commands;
import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;
public class CommandUtil {
static User findUser(MessageContext context, String username) {
Message message = context.getMessage();
User user;
Channel channel = context.getApiClient().getChannelById(message.getChannelId());
// Attempt to find the given user
// If the user is @mentioned, try that first
if (message.getMentions() != null && message.getMentions().length > 0) {
user = message.getMentions()[0];
} else {
user = context.getApiClient().findUser(username, channel.getParent());
}
return user;
}
}
|
Remove the no longer existing function "isUserVerified"
Thx @eMerzh
|
<?php
// Check if we are a user
OCP\JSON::callCheck();
OC_JSON::checkLoggedIn();
$username = isset($_POST["username"]) ? $_POST["username"] : OC_User::getUser();
$password = $_POST["password"];
$oldPassword=isset($_POST["oldpassword"])?$_POST["oldpassword"]:'';
$userstatus = null;
if(OC_User::isAdminUser(OC_User::getUser())) {
$userstatus = 'admin';
}
if(OC_SubAdmin::isUserAccessible(OC_User::getUser(), $username)) {
$userstatus = 'subadmin';
}
if(OC_User::getUser() === $username && OC_User::checkPassword($username, $oldPassword)) {
$userstatus = 'user';
}
if(is_null($userstatus)) {
OC_JSON::error( array( "data" => array( "message" => "Authentication error" )));
exit();
}
// Return Success story
if( OC_User::setPassword( $username, $password )) {
OC_JSON::success(array("data" => array( "username" => $username )));
}
else{
OC_JSON::error(array("data" => array( "message" => "Unable to change password" )));
}
|
<?php
// Check if we are a user
OCP\JSON::callCheck();
OC_JSON::checkLoggedIn();
$username = isset($_POST["username"]) ? $_POST["username"] : OC_User::getUser();
$password = $_POST["password"];
$oldPassword=isset($_POST["oldpassword"])?$_POST["oldpassword"]:'';
$userstatus = null;
if(OC_User::isAdminUser(OC_User::getUser())) {
$userstatus = 'admin';
}
if(OC_SubAdmin::isUserAccessible(OC_User::getUser(), $username)) {
$userstatus = 'subadmin';
}
if(OC_User::getUser() === $username) {
if (OC_User::checkPassword($username, $oldPassword)) {
$userstatus = 'user';
} else {
if (!OC_Util::isUserVerified()) {
$userstatus = null;
}
}
}
if(is_null($userstatus)) {
OC_JSON::error( array( "data" => array( "message" => "Authentication error" )));
exit();
}
// Return Success story
if( OC_User::setPassword( $username, $password )) {
OC_JSON::success(array("data" => array( "username" => $username )));
}
else{
OC_JSON::error(array("data" => array( "message" => "Unable to change password" )));
}
|
Update API to expose: render, parse, and clearCache methods
|
var mustache = require('mustache')
var defaultWriter = new mustache.Writer()
mustache.tags = '% %'
function unescapeKeywords (template) {
var KEYWORD_REGEX = /%(asset_name_linked|asset_short_name_linked)\b/g
return template.replace(KEYWORD_REGEX, '%&$1')
}
exports.clearCache = function clearCache () {
return defaultWriter.clearCache()
}
exports.parse = function parse (template, tags) {
return defaultWriter.parse(unescapeKeywords(template), tags)
}
exports.render = function render (template, view, partials) {
var _view = {
asset_name_linked: function nameLinked () {
if (view.name && view.href) {
return '<a href="' + view.href + '">' + view.name + '</a>'
}
},
asset_short_name_linked: function shortNameLinked () {
if (view.short_name && view.href) {
return '<a href="' + view.href + '">' + view.short_name + '</a>'
}
}
}
var keys = Object.keys(view)
for (var i = 0, key; i < keys.length; i++) {
key = keys[i]
_view['asset_' + key] = view[key]
}
return defaultWriter.render(unescapeKeywords(template), _view, partials)
}
|
var mustache = require('mustache')
mustache.tags = '% %'
function render (template, view) {
var KEYWORD_REGEX = /%(asset_name_linked|asset_short_name_linked)\b/g
var _template = template.replace(KEYWORD_REGEX, '%&$1')
var _view = {
asset_name_linked: function nameLinked () {
if (view.name && view.href) {
return '<a href="' + view.href + '">' + view.name + '</a>'
}
},
asset_short_name_linked: function shortNameLinked () {
if (view.short_name && view.href) {
return '<a href="' + view.href + '">' + view.short_name + '</a>'
}
}
}
var keys = Object.keys(view)
for (var i = 0, key; i < keys.length; i++) {
key = keys[i]
_view['asset_' + key] = view[key]
}
return mustache.render(_template, _view)
}
exports.render = render
|
Create download directory if not exists.
|
#!/usr/bin/python3
# -*- coding: utf8 -*-
import os
import shutil
import subprocess
bootstrap_updater_version = 1
BootstrapDownloads = 'BootstrapDownloads/'
BootstrapPrograms = 'BootstrapPrograms/'
bootstrap = 'https://www.dropbox.com/s/0zhbgb1ftspcv9w/polygon4.zip?dl=1'
bootstrap_zip = BootstrapDownloads + 'bootstrap.zip'
_7z = BootstrapPrograms + '7za'
curl = BootstrapPrograms + 'curl'
def main():
print_version()
if os.path.exists(BootstrapDownloads) == False:
os.mkdir(BootstrapDownloads)
if os.path.exists(bootstrap_zip):
shutil.copy(bootstrap_zip, bootstrap_zip + '.bak')
download_file(bootstrap, bootstrap_zip)
unpack_file(bootstrap_zip)
def download_file(url, file):
print('Downloading file: ' + file)
p = subprocess.Popen([curl, '-L', '-k', '-o', file, url])
p.communicate()
print()
def unpack_file(file):
print('Unpacking file: ' + file)
p = subprocess.Popen([_7z, 'x', '-y', file], stdout = subprocess.PIPE)
p.communicate()
def print_version():
print('Polygon-4 Bootstrap Updater Version ' + str(bootstrap_updater_version))
print()
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
# -*- coding: utf8 -*-
import os
import shutil
import subprocess
bootstrap_updater_version = 1
BootstrapDownloads = 'BootstrapDownloads/'
BootstrapPrograms = 'BootstrapPrograms/'
bootstrap = 'https://www.dropbox.com/s/0zhbgb1ftspcv9w/polygon4.zip?dl=1'
bootstrap_zip = BootstrapDownloads + 'bootstrap.zip'
_7z = BootstrapPrograms + '7za'
curl = BootstrapPrograms + 'curl'
def main():
print_version()
if os.path.exists(bootstrap_zip):
shutil.copy(bootstrap_zip, bootstrap_zip + '.bak')
download_file(bootstrap, bootstrap_zip)
unpack_file(bootstrap_zip)
def download_file(url, file):
print('Downloading file: ' + file)
p = subprocess.Popen([curl, '-L', '-k', '-o', file, url])
p.communicate()
print()
def unpack_file(file):
print('Unpacking file: ' + file)
p = subprocess.Popen([_7z, 'x', '-y', file], stdout = subprocess.PIPE)
p.communicate()
def print_version():
print('Polygon-4 Bootstrap Updater Version ' + str(bootstrap_updater_version))
print()
if __name__ == '__main__':
main()
|
Make buttons of person links
|
@extends('layouts.offcanvas')
@section('sidebar')
@endsection
@section('main')
<div id="tribe-details">
<h2>@lang("ui.about")</h2>
{{ link_to_action('FriendsController@getGoals', trans('ui.goals.title_index'), $d->id, array('class' => 'button small')) }}
{{ link_to_action('FriendsController@getEndorsements', trans('ui.endorsements.title_index'), $d->id, array('class' => 'button small')) }}
<div data-section-content class="row">
<div class="columns small-12 large-6">
@include('field', array('name' => 'avatar'))
</div>
<div class="columns small-12 large-6">
@include('field', array('name' => 'full_name'))
@include('field', array('name' => 'email'))
@include('field', array('name' => 'birth_date'))
{{link_to_route('users.edit', trans('forms.edit'), $d->id, array('class' => 'button small right'))}}
</div>
</div>
{{ link_to('tribe', trans('ui.back'), array('class' => 'left')) }}
</div>
@endsection
|
@extends('layouts.offcanvas')
@section('sidebar')
@endsection
@section('main')
<div id="tribe-details">
<h2>@lang("ui.about")</h2>
{{ link_to_action('FriendsController@getGoals', trans('ui.goals.title_index'), $d->id) }}
{{ link_to_action('FriendsController@getEndorsements', trans('ui.endorsements.title_index'), $d->id) }}
<div data-section-content class="row">
<div class="columns small-12 large-6">
@include('field', array('name' => 'avatar'))
</div>
<div class="columns small-12 large-6">
@include('field', array('name' => 'full_name'))
@include('field', array('name' => 'email'))
@include('field', array('name' => 'birth_date'))
{{link_to_route('users.edit', trans('forms.edit'), $d->id, array('class' => 'button small right'))}}
</div>
</div>
{{ link_to('tribe', trans('ui.back'), array('class' => 'left')) }}
</div>
@endsection
|
Tweak server to be shorter
|
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
)
func main() {
addr := flag.String("addr", ":4000", "HTTP network address")
certFile := flag.String("certfile", "cert.pem", "certificate PEM file")
keyFile := flag.String("keyfile", "key.pem", "key PEM file")
flag.Parse()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Proudly served with Go and HTTPS!")
})
srv := &http.Server{
Addr: *addr,
Handler: mux,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
PreferServerCipherSuites: true,
},
}
log.Printf("Starting server on %s", *addr)
err := srv.ListenAndServeTLS(*certFile, *keyFile)
log.Fatal(err)
}
|
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
"time"
)
func main() {
addr := flag.String("addr", ":4000", "HTTP network address")
certFile := flag.String("certfile", "cert.pem", "certificate PEM file")
keyFile := flag.String("keyfile", "key.pem", "key PEM file")
flag.Parse()
tlsConfig := &tls.Config{
PreferServerCipherSuites: true,
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256},
}
mux := http.NewServeMux()
mux.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Pong")
})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})
srv := &http.Server{
Addr: *addr,
Handler: mux,
TLSConfig: tlsConfig,
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Printf("Starting server on %s", *addr)
err := srv.ListenAndServeTLS(*certFile, *keyFile)
log.Fatal(err)
}
|
Refactor uploader tests to use the fixture module.
|
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from datapackage import DataPackage
from future import standard_library
from gobble.user import User
standard_library.install_aliases()
from json import loads
from io import open
from gobble.uploader import Uploader
# noinspection PyUnresolvedReferences
from tests.fixtures import (dummy_requests,
ROOT_DIR,
PACKAGE_FILE,
UPLOADER_PAYLOAD)
# noinspection PyShadowingNames
def test_build_payloads(dummy_requests):
with dummy_requests:
user = User()
package = DataPackage(PACKAGE_FILE)
uploader = Uploader(user, package)
with open(UPLOADER_PAYLOAD) as json:
assert uploader.payload == loads(json.read())
|
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import open
from future import standard_library
standard_library.install_aliases()
from os.path import join
from datapackage import DataPackage
from pytest import fixture
from json import loads
from gobble.config import ASSETS_DIR
from gobble.uploader import Uploader
from gobble.user import User
@fixture
def user():
return User()
@fixture
def package():
filepath = join(ASSETS_DIR, 'mexican-budget-samples', 'datapackage.json')
return DataPackage(filepath)
# noinspection PyShadowingNames
def test_build_payloads(user, package):
uploader = Uploader(user, package)
expected = join(ASSETS_DIR, 'mexican-budget-samples', 'payload.json')
with open(expected) as json:
assert uploader.payload == loads(json.read())
|
Revert "Hide exceptions if elasticsearch is not running. This needs some fixing and cleaning up by someone smarter than myself."
This reverts commit eb1900265fb3f077cf104c0944d8832a8d48012e and fixes #45.
|
<?php
namespace FOQ\ElasticaBundle;
use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;
/**
* @author Gordon Franke <info@nevalon.de>
*/
class Client extends Elastica_Client
{
protected $logger;
public function setLogger(ElasticaLogger $logger)
{
$this->logger = $logger;
}
public function request($path, $method, $data = array())
{
$start = microtime(true);
$response = parent::request($path, $method, $data);
if (null !== $this->logger) {
$time = microtime(true) - $start;
$this->logger->logQuery($path, $method, $data, $time);
}
return $response;
}
}
|
<?php
namespace FOQ\ElasticaBundle;
use Elastica_Client;
use FOQ\ElasticaBundle\Logger\ElasticaLogger;
/**
* @author Gordon Franke <info@nevalon.de>
*/
class Client extends Elastica_Client
{
protected $logger;
public function setLogger(ElasticaLogger $logger)
{
$this->logger = $logger;
}
public function request($path, $method, $data = array())
{
$start = microtime(true);
//this is ghetto, but i couldnt figure out another way of making our site continue to behave normally even if ES was not running.
//Any improvements on this welcome. Perhaps another parameter that allows you to control if you want to ignore exceptions about ES not running
try {
$response = parent::request($path, $method, $data);
} catch(\Exception $e) {
//again, ghetto, but couldnt figure out how to return a default empty Elastica_Response
return new \Elastica_Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}');
}
if (null !== $this->logger) {
$time = microtime(true) - $start;
$this->logger->logQuery($path, $method, $data, $time);
}
return $response;
}
}
|
[BUG] Fix string typo in migration
|
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('users', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: { type: 'string', notNull: true, unique: true },
salt: { type: 'string', notNull: true },
federation_tag: { type: 'string' },
admin: { type: 'boolean', default: false },
federation_name: { type: 'string' },
password_hash: { type: 'string', notNull: true },
bank_account_id: { type: 'int'},
kyc_id: { type: 'int' },
createdAt: { type: 'datetime', notNull: true },
updatedAt: { type: 'datetime' },
external_id: { type: 'string' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('users', callback);
};
|
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('users', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: { type: 'string', notNull: true, unique: true },
salt: { type: 'string', notNull: true },
federation_tag: { type: 'string' },
admin: { type: 'boolean', default: false },
federation_name: { type: 'string' },
password_hash: { type: 'string', notNull: true },
bank_account_id: { type: 'int'},
kyc_id: { type: 'int' },
createdAt: { type: 'datetime', notNull: true },
updatedAt: { type: 'datetime' },
external_id: { type: string' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('users', callback);
};
|
Enhancement: Add return type declaration and DocBlock
Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event\TestRunner;
use function array_merge;
use function asort;
use function extension_loaded;
use function get_loaded_extensions;
use ArrayIterator;
use IteratorAggregate;
final class Extensions implements IteratorAggregate
{
public function loaded(string $name): bool
{
return extension_loaded($name);
}
/**
* @return ArrayIterator<int, string>
*/
public function getIterator(): ArrayIterator
{
$all = array_merge(
get_loaded_extensions(true),
get_loaded_extensions(false)
);
asort($all);
return new ArrayIterator($all);
}
}
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event\TestRunner;
use function array_merge;
use function asort;
use function extension_loaded;
use function get_loaded_extensions;
use ArrayIterator;
use IteratorAggregate;
final class Extensions implements IteratorAggregate
{
public function loaded(string $name): bool
{
return extension_loaded($name);
}
public function getIterator()
{
$all = array_merge(
get_loaded_extensions(true),
get_loaded_extensions(false)
);
asort($all);
return new ArrayIterator($all);
}
}
|
Make clear how to use HTTPS in the helloworld example
|
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.example.http.helloworld;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
// Uncomment the following line if you want HTTPS
//SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
//engine.setUseClientMode(false);
//p.addLast("ssl", new SslHandler(engine));
p.addLast("codec", new HttpServerCodec());
p.addLast("handler", new HttpHelloWorldServerHandler());
}
}
|
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.example.http.helloworld;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("codec", new HttpServerCodec());
p.addLast("handler", new HttpHelloWorldServerHandler());
}
}
|
Add mkdn extension to markdown extension list
mkdn is an acceptable extension as per
https://github.com/github/markup/tree/master#markups
|
<?php
/*
* This file is a part of Sculpin.
*
* (c) Dragonfly Development Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sculpin\Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration.
*
* @author Beau Simensen <beau@dflydev.com>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder;
$rootNode = $treeBuilder->root('sculpin_markdown');
$rootNode
->children()
->scalarNode('parser_class')->defaultValue('Sculpin\Bundle\MarkdownBundle\PhpMarkdownExtraParser')->end()
->arrayNode('extensions')
->defaultValue(array('md', 'mdown', 'mkdn', 'markdown'))
->prototype('scalar')->end()
->end()
->end();
return $treeBuilder;
}
}
|
<?php
/*
* This file is a part of Sculpin.
*
* (c) Dragonfly Development Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sculpin\Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration.
*
* @author Beau Simensen <beau@dflydev.com>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder;
$rootNode = $treeBuilder->root('sculpin_markdown');
$rootNode
->children()
->scalarNode('parser_class')->defaultValue('Sculpin\Bundle\MarkdownBundle\PhpMarkdownExtraParser')->end()
->arrayNode('extensions')
->defaultValue(array('md', 'mdown', 'markdown'))
->prototype('scalar')->end()
->end()
->end();
return $treeBuilder;
}
}
|
Add socket connect timeout option to sentinel connection
|
from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1,
retry_on_timeout=True,
socket_connect_timeout=0.1)
redis_db = app.config.get('REDIS_DB') or 0
self.master = self.connection.master_for('mymaster', db=redis_db)
self.slave = self.connection.slave_for('mymaster', db=redis_db)
|
from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1,
retry_on_timeout=True)
redis_db = app.config.get('REDIS_DB') or 0
self.master = self.connection.master_for('mymaster', db=redis_db)
self.slave = self.connection.slave_for('mymaster', db=redis_db)
|
Remove ".label" from optional field
'fv-word:part_of_speech'
|
// TODO: IMPORT ONLY WHAT IS USED
import * as yup from 'yup'
import copy from './internationalization'
const validForm = yup.object().shape({
'dc:title': yup.string().required(copy.validation.title),
'fv-word:part_of_speech': yup.string(),
'fv-word:pronunciation': yup.string(),
'fv-word:available_in_games': yup.string(),
'fv:available_in_childrens_archive': yup.string(),
'fv:cultural_note': yup.array().of(yup.string()),
'fv:definitions': yup.array().of(yup.object().shape({ language: yup.string(), translation: yup.string() })),
'fv:literal_translation': yup.array().of(yup.object().shape({ language: yup.string(), translation: yup.string() })),
'fv:reference': yup.string(),
'fv:related_audio': yup.array().of(yup.string()),
'fv:related_pictures': yup.array().of(yup.string()),
'fv:source': yup.array().of(yup.string()),
})
export const toParse = [
/^fv:literal_translation/,
/^fv:definitions/,
/^fv:related_audio/,
/^fv:related_pictures/,
/^fv:cultural_note/,
/^fvm:source/,
/^fv-word:related_phrases/,
]
export default validForm
|
// TODO: IMPORT ONLY WHAT IS USED
import * as yup from 'yup'
import copy from './internationalization'
const validForm = yup.object().shape({
'dc:title': yup.string().required(copy.validation.title),
'fv-word:part_of_speech': yup.string().label('Part of speech'),
'fv-word:pronunciation': yup.string(),
'fv-word:available_in_games': yup.string(),
'fv:available_in_childrens_archive': yup.string(),
'fv:cultural_note': yup.array().of(yup.string()),
'fv:definitions': yup.array().of(yup.object().shape({ language: yup.string(), translation: yup.string() })),
'fv:literal_translation': yup.array().of(yup.object().shape({ language: yup.string(), translation: yup.string() })),
'fv:reference': yup.string(),
'fv:related_audio': yup.array().of(yup.string()),
'fv:related_pictures': yup.array().of(yup.string()),
'fv:source': yup.array().of(yup.string()),
})
export const toParse = [
/^fv:literal_translation/,
/^fv:definitions/,
/^fv:related_audio/,
/^fv:related_pictures/,
/^fv:cultural_note/,
/^fvm:source/,
/^fv-word:related_phrases/,
]
export default validForm
|
Add hide for casting to the default mod list
|
var rModsList = [];
/* start ui_mod_list */
var global_mod_list = [
];
var scene_mod_list = {'connect_to_game': [
],'game_over': [
],
'icon_atlas': [
],
'live_game': [
//In game timer
'../../mods/dTimer/dTimer.css',
'../../mods/dTimer/dTimer.js',
//Mex/Energy Count
'../../mods/dMexCount/dMexCount.css',
'../../mods/dMexCount/dMexCount.js',
//Better System view (show system view at all times)
'../../mods/dBetterSystemView/dBetterSystemView.css',
'../../mods/dBetterSystemView/dBetterSystemView.js',
//Reminders
'../../mods/dReminderTimer/dReminderTimer.css',
'../../mods/dReminderTimer/dReminderTimer.js',
//Hide for casting
'../../mods/dHideCast/dHideCast.css',
'../../mods/dHideCast/dHideCast.js',
],
'load_planet': [
],
'lobby': [
],
'matchmaking': [
],
'new_game': [
],
'server_browser': [
],
'settings': [
],
'special_icon_atlas': [
],
'start': [
],
'system_editor': [
],
'transit': [
]
}
/* end ui_mod_list */
|
var rModsList = [];
/* start ui_mod_list */
var global_mod_list = [
];
var scene_mod_list = {'connect_to_game': [
],'game_over': [
],
'icon_atlas': [
],
'live_game': [
//In game timer
'../../mods/dTimer/dTimer.css',
'../../mods/dTimer/dTimer.js',
//Mex/Energy Count
'../../mods/dMexCount/dMexCount.css',
'../../mods/dMexCount/dMexCount.js',
//Better System view (show system view at all times)
'../../mods/dBetterSystemView/dBetterSystemView.css',
'../../mods/dBetterSystemView/dBetterSystemView.js',
//Reminders
'../../mods/dReminderTimer/dReminderTimer.css',
'../../mods/dReminderTimer/dReminderTimer.js',
],
'load_planet': [
],
'lobby': [
],
'matchmaking': [
],
'new_game': [
],
'server_browser': [
],
'settings': [
],
'special_icon_atlas': [
],
'start': [
],
'system_editor': [
],
'transit': [
]
}
/* end ui_mod_list */
|
UNIT_TEST: Add ability to run unit test script from anywhere
|
#!/usr/bin/env python
import serial
import os
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset button on the STM32F4Discovery board and then press enter to continue...")
# Open a serial port
ser = serial.Serial("/dev/serial/by-id/usb-PopaGator_Toad-if00", 115200)
# Send data to start USB OTG
ser.write("start")
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
result += ser.read(num_chars)
if result.find("Finished") != -1:
break
finally:
# Print the result so the user can see and close the serial port
print result
ser.close()
|
#!/usr/bin/env python
import serial
import os
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.system("cd " + FILE_LOCATION + " ../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset button on the STM32F4Discovery board and then press enter to continue...")
# Open a serial port
ser = serial.Serial("/dev/serial/by-id/usb-PopaGator_Toad-if00", 115200)
# Send data to start USB OTG
ser.write("start")
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
result += ser.read(num_chars)
if result.find("Finished") != -1:
break
finally:
# Print the result so the user can see and close the serial port
print result
ser.close()
|
Fix cl console.log shorthand to show real path
Merge pull request #100 from Novicell/tbb2-patch-1
Update novicell.js
|
'use strict';
/*global console:true */
/*!
*
* Novicell JavaScript Library v0.5
* http://www.novicell.dk
*
* Copyright Novicell
*
*/
// Prevent console errors in IE
if (typeof (console) === 'undefined') {
var console = {};
console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function () { };
}
// Shorthand for console.log
var cl = console.log.bind(window.console);
// Init the novicell js lib
var novicell = novicell || {};
$(function () {
if (typeof projectName !== 'undefined') {
$('body').prepend('<div class="debug" style="text-align:center;font-weight:bold;background:#66CE5F;padding:20px;margin-bottom:50px;">Hi there. Remember to rename the "projectName" object in master.js file :)</div>');
}
});
|
'use strict';
/*global console:true */
/*!
*
* Novicell JavaScript Library v0.5
* http://www.novicell.dk
*
* Copyright Novicell
*
*/
// Prevent console errors in IE
if (typeof (console) === 'undefined') {
var console = {};
console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function () { };
}
// Shorthand for console.log
function cl(d) {
return console.log(d);
}
// Init the novicell js lib
var novicell = novicell || {};
$(function () {
if (typeof projectName !== 'undefined') {
$('body').prepend('<div class="debug" style="text-align:center;font-weight:bold;background:#66CE5F;padding:20px;margin-bottom:50px;">Hi there. Remember to rename the "projectName" object in master.js file :)</div>');
}
});
|
Make curl follow redirects to prevent relocation in the future
|
<?php
namespace Raffle;
class RandomService
{
/**
* Base URL
*/
const BASE_URL = 'https://www.random.org/integer-sets/?sets=1&min=%d&max=%d&num=%d&order=random&format=plain&rnd=new';
/**
* Retrieve a block of random numbers.
*
* @param int $min Minimum amount.
* @param int $max Maximum amount.
* @return array
*/
public function getRandomNumbers($min, $max)
{
// Construct the URL
$url = sprintf(self::BASE_URL, $min, $max, $max + 1);
// Fetch the numbers
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
// Decode data and return
return explode(" ", trim($data));
}
}
|
<?php
namespace Raffle;
class RandomService
{
/**
* Base URL
*/
const BASE_URL = 'https://www.random.org/integer-sets/?sets=1&min=%d&max=%d&num=%d&order=random&format=plain&rnd=new';
/**
* Retrieve a block of random numbers.
*
* @param int $min Minimum amount.
* @param int $max Maximum amount.
* @return array
*/
public function getRandomNumbers($min, $max)
{
// Construct the URL
$url = sprintf(self::BASE_URL, $min, $max, $max + 1);
// Fetch the numbers
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
// Decode data and return
return explode(" ", trim($data));
}
}
|
Move configuration variables to constants.
|
from urlparse import urlparse
import logging
import os
from flask import Flask
import pymongo
HOST= '0.0.0.0'
PORT = int(os.environ.get('PORT', 5000))
MONGO_URL = os.environ.get('MONGOHQ_URL', 'http://localhost:27017/db')
DEBUG = True
app = Flask(__name__)
_logger = logging.getLogger(__name__)
db = None
def get_connection():
global db
if db:
return db
config = urlparse(MONGO_URL)
db_name = config.path.rpartition('/')[2]
connection = pymongo.Connection(config.hostname, config.port)
db = connection[db_name]
if config.username:
db.authenticate(config.username, config.password)
return db
@app.route('/')
def hello():
db = get_connection()
emptyset = db.some_collection.find()
return 'Hello World! {0}'.format(emptyset.count())
if __name__ == '__main__':
app.run(host=HOST, port=PORT, debug=DEBUG)
|
from urlparse import urlparse
import logging
import os
from flask import Flask
import pymongo
app = Flask(__name__)
_logger = logging.getLogger(__name__)
db = None
def get_connection():
global db
if db:
return db
config = urlparse(os.environ.get('MONGOHQ_URL', 'http://localhost:27017/db'))
db_name = config.path.rpartition('/')[2]
connection = pymongo.Connection(config.hostname, config.port)
db = connection[db_name]
if config.username:
db.authenticate(config.username, config.password)
return db
@app.route('/')
def hello():
db = get_connection()
emptyset = db.some_collection.find()
return 'Hello World! {0}'.format(emptyset.count())
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.debug = True
app.run(host='0.0.0.0', port=port)
|
Update copyright notice with MIT license
|
/*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--*/
package com.nasmlanguage.psi;
import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;
public class NASMTokenType extends IElementType {
public NASMTokenType(@NotNull @NonNls String debugName) {
super(debugName, NASMLanguage.INSTANCE);
}
@Override
public String toString() {
return "NASMTokenType." + super.toString();
}
}
|
/*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--*/
package com.nasmlanguage.psi;
import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;
public class NASMTokenType extends IElementType {
public NASMTokenType(@NotNull @NonNls String debugName) {
super(debugName, NASMLanguage.INSTANCE);
}
@Override
public String toString() {
return "NASMTokenType." + super.toString();
}
}
|
Make perms write_roles actually work
|
/**
* Based on: https://github.com/iriscouch/manage_couchdb/
* License: Apache License 2.0
**/
function(newDoc, oldDoc, userCtx, secObj) {
var ddoc = this;
secObj.admins = secObj.admins || {};
secObj.admins.names = secObj.admins.names || [];
secObj.admins.roles = secObj.admins.roles || [];
var IS_DB_ADMIN = false;
if(~ userCtx.roles.indexOf('_admin'))
IS_DB_ADMIN = true;
if(~ secObj.admins.names.indexOf(userCtx.name))
IS_DB_ADMIN = true;
for(var i = 0; i < userCtx.roles; i++)
if(~ secObj.admins.roles.indexOf(userCtx.roles[i]))
IS_DB_ADMIN = true;
// check access.json's write_roles collection
for(var i = 0; i < userCtx.roles.length; i++)
if(~ ddoc.access.write_roles.indexOf(userCtx.roles[i]))
IS_DB_ADMIN = true;
if(ddoc.access && ddoc.access.read_only)
if(IS_DB_ADMIN)
log('Admin change on read-only db: ' + newDoc._id);
else
throw {'forbidden':'This database is read-only'};
}
|
/**
* Based on: https://github.com/iriscouch/manage_couchdb/
* License: Apache License 2.0
**/
function(newDoc, oldDoc, userCtx, secObj) {
var ddoc = this;
secObj.admins = secObj.admins || {};
secObj.admins.names = secObj.admins.names || [];
secObj.admins.roles = secObj.admins.roles || [];
var IS_DB_ADMIN = false;
if(~ userCtx.roles.indexOf('_admin'))
IS_DB_ADMIN = true;
if(~ secObj.admins.names.indexOf(userCtx.name))
IS_DB_ADMIN = true;
for(var i = 0; i < userCtx.roles; i++)
if(~ secObj.admins.roles.indexOf(userCtx.roles[i]))
IS_DB_ADMIN = true;
// check access.json's write_roles collection
for(var i = 0; i < userCtx.roles; i++)
if(~ ddoc.write_roles.indexOf(userCtx.roles[i]))
IS_DB_ADMIN = true;
if(ddoc.access && ddoc.access.read_only)
if(IS_DB_ADMIN)
log('Admin change on read-only db: ' + newDoc._id);
else
throw {'forbidden':'This database is read-only'};
}
|
Use "elm-format" as the default binary path
Not all people have elm-format installed into /usr/local/bin/elm-format (I installed it via package manager so it's in /usr/bin/elm-format), but I assume most of the people have it int their PATH. This should fix #18 for most users.
|
'use babel';
export default {
binary: {
title: 'Binary path',
description: 'Path for elm-format',
type: 'string',
default: 'elm-format',
order: 1,
},
formatOnSave: {
title: 'Format on save',
description: 'Do we format when you save files?',
type: 'boolean',
default: true,
order: 2,
},
showNotifications: {
title: 'Show notifications on save',
description: 'Do you want to see the bar when we save?',
type: 'boolean',
default: false,
order: 3,
},
showErrorNotifications: {
title: 'Show error notifications on save',
description: 'Do you want to see the bar when we save?',
type: 'boolean',
default: true,
order: 4,
},
};
|
'use babel';
export default {
binary: {
title: 'Binary path',
description: 'Path for elm-format',
type: 'string',
default: '/usr/local/bin/elm-format',
order: 1,
},
formatOnSave: {
title: 'Format on save',
description: 'Do we format when you save files?',
type: 'boolean',
default: true,
order: 2,
},
showNotifications: {
title: 'Show notifications on save',
description: 'Do you want to see the bar when we save?',
type: 'boolean',
default: false,
order: 3,
},
showErrorNotifications: {
title: 'Show error notifications on save',
description: 'Do you want to see the bar when we save?',
type: 'boolean',
default: true,
order: 4,
},
};
|
Update license classifier to MIT
|
from os import path, pardir, chdir
from setuptools import setup, find_packages
README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))
setup(
name='django-perimeter',
version='0.9',
packages=find_packages(),
include_package_data=True,
license='MIT',
description='Site-wide perimeter access control for Django projects.',
long_description=README,
url='https://github.com/yunojuno/django-perimeter',
author='YunoJuno',
author_email='code@yunojuno.com',
maintainer='YunoJuno',
maintainer_email='code@yunojuno.com',
install_requires=['Django>=1.8'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
from os import path, pardir, chdir
from setuptools import setup, find_packages
README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))
setup(
name='django-perimeter',
version='0.9',
packages=find_packages(),
include_package_data=True,
license='MIT',
description='Site-wide perimeter access control for Django projects.',
long_description=README,
url='https://github.com/yunojuno/django-perimeter',
author='YunoJuno',
author_email='code@yunojuno.com',
maintainer='YunoJuno',
maintainer_email='code@yunojuno.com',
install_requires=['Django>=1.8'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Add simple UI for first example
|
package org.kikermo.blepotcontroller.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import org.kikermo.blepotcontroller.R;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private TextView value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.value);
((SeekBar) findViewById(R.id.pot)).setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
value.setText(i + "%");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
|
package org.kikermo.blepotcontroller.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import org.kikermo.blepotcontroller.R;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private TextView value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.value);
((SeekBar)findViewById(R.id.pot)).setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
|
Add updated_at attribute for Dashboard.Repository
|
require('dashboard/core');
Dashboard.Repository = DS.Model.extend({
name: DS.attr('string'),
full_name: DS.attr('string'),
description: DS.attr('string'),
html_url: DS.attr('string'),
homepage: DS.attr('string'),
watchers: DS.attr('number'),
forks: DS.attr('number'),
language: DS.attr('string'),
updated_at: DS.attr('date'),
owner: function() {
return this.get('data.owner')
}.property('data')
});
Dashboard.Event = DS.Model.extend({
type: DS.attr('string'),
created_at: DS.attr('string'),
actor: function() { return this.get('data.actor'); }.property('data.actor'),
repo: function() { return this.get('data.repo'); }.property('data.repo'),
org: function() { return this.get('data.org'); }.property('data.org'),
payload: function() { return this.get('data.payload'); }.property('data.payload')
});
Dashboard.User = DS.Model.extend({
primaryKey: 'login',
login: DS.attr('string'),
avatar_url: DS.attr('string'),
name: DS.attr('string'),
blog: DS.attr('string'),
email: DS.attr('string'),
bio: DS.attr('string'),
public_repos: DS.attr('number'),
followers: DS.attr('number'),
following: DS.attr('number'),
html_url: DS.attr('string'),
created_at: DS.attr('string')
});
|
require('dashboard/core');
Dashboard.Repository = DS.Model.extend({
name: DS.attr('string'),
full_name: DS.attr('string'),
description: DS.attr('string'),
html_url: DS.attr('string'),
homepage: DS.attr('string'),
watchers: DS.attr('number'),
forks: DS.attr('number'),
language: DS.attr('string'),
owner: function() {
return this.get('data.owner')
}.property('data')
});
Dashboard.Event = DS.Model.extend({
type: DS.attr('string'),
created_at: DS.attr('string'),
actor: function() { return this.get('data.actor'); }.property('data.actor'),
repo: function() { return this.get('data.repo'); }.property('data.repo'),
org: function() { return this.get('data.org'); }.property('data.org'),
payload: function() { return this.get('data.payload'); }.property('data.payload')
});
Dashboard.User = DS.Model.extend({
primaryKey: 'login',
login: DS.attr('string'),
avatar_url: DS.attr('string'),
name: DS.attr('string'),
blog: DS.attr('string'),
email: DS.attr('string'),
bio: DS.attr('string'),
public_repos: DS.attr('number'),
followers: DS.attr('number'),
following: DS.attr('number'),
html_url: DS.attr('string'),
created_at: DS.attr('string')
});
|
Add Last Modified date and author
|
#!/usr/bin/env php
<?php
/**
* Last modified 2014-03-10
* @author Ryo Utsunomiya (https://twitter.com/ryo511)
*/
if (empty($argv[1])) {
fputs(STDERR, "1st argument is empty; Pass me a text file which contains file list\n");
exit(1);
}
if (empty($argv[2])) {
fputs(STDERR, "2nd argument is empty; Pass me a path to destination\n");
exit(1);
}
$destination = trim($argv[2]);
$files = file_get_contents($argv[1]);
$files = explode("\n", $files);
$files = array_filter($files, 'strlen');
foreach ($files as $filepath) {
$filepath = trim($filepath);
if (is_file($filepath) || is_dir($filepath)) {
$command = sprintf("cp -a --parents %s %s 2>&1", $filepath, $destination);
$output = array();
$return_var = 0;
exec($command, $outout, $return_var);
// echo $command, PHP_EOL;
if ($return_var !== 0) {
fputs(STDERR, $output[0]);
exit(1);
}
} else {
fputs(STDERR, "No such file or directory: $filepath\n");
exit(1);
}
}
exit(0);
|
#!/usr/bin/env php
<?php
if (empty($argv[1])) {
fputs(STDERR, "1st argument is empty; Pass me a text file which contains file list\n");
exit(1);
}
if (empty($argv[2])) {
fputs(STDERR, "2nd argument is empty; Pass me a path to destination\n");
exit(1);
}
$destination = trim($argv[2]);
$files = file_get_contents($argv[1]);
$files = explode("\n", $files);
$files = array_filter($files, 'strlen');
foreach ($files as $filepath) {
$filepath = trim($filepath);
if (is_file($filepath) || is_dir($filepath)) {
$command = sprintf("cp -a --parents %s %s 2>&1", $filepath, $destination);
$output = array();
$return_var = 0;
exec($command, $outout, $return_var);
// echo $command, PHP_EOL;
if ($return_var !== 0) {
fputs(STDERR, $output[0]);
exit(1);
}
} else {
fputs(STDERR, "No such file or directory: $filepath\n");
exit(1);
}
}
exit(0);
|
Fix doubling quotes when closing string literal
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2014 AS3Boyan
* Copyright 2014-2014 Elias Ku
*
* 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.intellij.plugins.haxe.ide;
import com.intellij.codeInsight.editorActions.SimpleTokenSetQuoteHandler;
import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes;
/**
* @author fedor.korotkov
*/
public class HaxeQuoteHandler extends SimpleTokenSetQuoteHandler {
public HaxeQuoteHandler() {
super(HaxeTokenTypes.OPEN_QUOTE);
}
}
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2014 AS3Boyan
* Copyright 2014-2014 Elias Ku
*
* 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.intellij.plugins.haxe.ide;
import com.intellij.codeInsight.editorActions.SimpleTokenSetQuoteHandler;
import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypeSets;
import com.intellij.psi.TokenType;
import com.intellij.util.ArrayUtil;
/**
* @author fedor.korotkov
*/
public class HaxeQuoteHandler extends SimpleTokenSetQuoteHandler {
public HaxeQuoteHandler() {
super(ArrayUtil.append(HaxeTokenTypeSets.STRINGS.getTypes(), TokenType.BAD_CHARACTER));
}
}
|
Make number of attributes in editor variable
|
package editor.views;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The AttributesPanelView is used to show all of the attributes of an XML
* element in an editable form.
* @see xml.Element
*/
public class AttributesPanelView extends JPanel {
private JPanel attributesPanel;
private ArrayList<JTextField> attributeNameFields;
private ArrayList<JTextField> attributeValueFields;
/**
* Initialize the AttributesPanelView with no data
*/
public AttributesPanelView() {
attributeNameFields = new ArrayList<JTextField>();
attributeValueFields = new ArrayList<JTextField>();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JLabel("Attributes"));
attributesPanel = new JPanel();
attributesPanel.setLayout(new GridLayout());
addAttribute();
add(attributesPanel);
}
/**
* Add more space for another attribute to be added. This adds a field for
* the attribute's name and another for its value.
*/
public void addAttribute() {
JTextField nameField = new JTextField("", 10);
attributesPanel.add(nameField);
attributeNameFields.add(nameField);
JTextField valueField = new JTextField("", 10);
attributesPanel.add(valueField);
attributeValueFields.add(valueField);
}
}
|
package editor.views;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
/**
* The AttributesPanelView is used to show all of the attributes of an XML
* element in an editable form.
* @see xml.Element
*/
public class AttributesPanelView extends JPanel {
private JPanel attributesPanel;
/**
* Initialize the AttributesPanelView with no data
*/
public AttributesPanelView() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JLabel("Attributes"));
attributesPanel = new JPanel();
attributesPanel.setLayout(new GridLayout());
attributesPanel.add(new JTextField("", 10));
attributesPanel.add(new JTextField("", 10));
add(attributesPanel);
}
}
|
Use array shorthand for cache table
|
<?php
namespace Craft;
class Wistia_CacheRecord extends BaseRecord
{
public function getTableName()
{
return 'wistia_cache';
}
protected function defineAttributes()
{
return [
'id' => [
AttributeType::Number,
'column' => ColumnType::PK
],
'hashedId' => AttributeType::String,
'type' => [
AttributeType::Enum,
'values' => 'data, stats'
],
'data' => [
AttributeType::String,
'column' => ColumnType::Text
]
];
}
public function defineIndexes()
{
return [
[
'columns' => 'hashedId'
],
[
'columns' => 'type'
]
];
}
}
|
<?php
namespace Craft;
class Wistia_CacheRecord extends BaseRecord
{
public function getTableName()
{
return 'wistia_cache';
}
protected function defineAttributes()
{
return array(
'id' => array(
AttributeType::Number,
'column' => ColumnType::PK
),
'hashedId' => AttributeType::String,
'type' => array(
AttributeType::Enum,
'values' => 'data, stats'
),
'data' => array(
AttributeType::String,
'column' => ColumnType::Text
)
);
}
public function defineIndexes()
{
return array(
array(
'columns' => 'hashedId'
),
array(
'columns' => 'type'
)
);
}
}
|
FEATURE: Add PHPs json_encode options to stringify eel helper
|
<?php
namespace Neos\Eel\Helper;
/*
* This file is part of the Neos.Eel package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
/**
* JSON helpers for Eel contexts
*
* @Flow\Proxy(false)
*/
class JsonHelper implements ProtectedContextAwareInterface
{
/**
* JSON encode the given value
*
* @param mixed $value
* @param array $options Array of option constant names as strings
* @return string
*/
public function stringify($value, array $options = []): string
{
$optionSum = array_sum(array_map('constant', $options));
return json_encode($value, $optionSum);
}
/**
* JSON decode the given string
*
* @param string $json
* @param boolean $associativeArrays
* @return mixed
*/
public function parse($json, $associativeArrays = true)
{
return json_decode($json, $associativeArrays);
}
/**
* All methods are considered safe
*
* @param string $methodName
* @return boolean
*/
public function allowsCallOfMethod($methodName)
{
return true;
}
}
|
<?php
namespace Neos\Eel\Helper;
/*
* This file is part of the Neos.Eel package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
/**
* JSON helpers for Eel contexts
*
* @Flow\Proxy(false)
*/
class JsonHelper implements ProtectedContextAwareInterface
{
/**
* JSON encode the given value
*
* @param mixed $value
* @return string
*/
public function stringify($value)
{
return json_encode($value);
}
/**
* JSON decode the given string
*
* @param string $json
* @param boolean $associativeArrays
* @return mixed
*/
public function parse($json, $associativeArrays = true)
{
return json_decode($json, $associativeArrays);
}
/**
* All methods are considered safe
*
* @param string $methodName
* @return boolean
*/
public function allowsCallOfMethod($methodName)
{
return true;
}
}
|
Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
Add new test pending dependencies.
|
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('pc simple ruby app', function(){
it('will barf without arguments');
describe('default', function(){
before(function(done){
// on smaller dev machines this setup takes longer than the default 2s.
this.timeout(0);
helpers.run(path.join(__dirname, '../generators/app'))
.withArguments(['ShinyProject'])
.on('end', done);
});
it('creates files', function(){
assert.file([
'Gemfile',
'Rakefile',
'lib/new_project.rb',
'test/new_project_test.rb'
]);
});
});
});
|
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('pc simple ruby app', function(){
describe('default', function(){
before(function(done){
// on smaller dev machines this setup takes longer than the default 2s.
this.timeout(0);
helpers.run(path.join(__dirname, '../generators/app'))
.withArguments(['ShinyProject'])
.on('end', done);
});
it('creates files', function(){
assert.file([
'Gemfile',
'Rakefile',
'lib/new_project.rb',
'test/new_project_test.rb'
]);
});
});
});
|
Remove import models from init in sepa_credit_transfer
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# SEPA Credit Transfer module for OpenERP
# Copyright (C) 2010-2013 Akretion (http://www.akretion.com)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import wizard
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# SEPA Credit Transfer module for OpenERP
# Copyright (C) 2010-2013 Akretion (http://www.akretion.com)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import wizard
from . import models
|
Reset scroll on back/next pages.
|
import Ember from 'ember';
export default Ember.Route.extend({
queryParams: {
page: {
refreshModel: true
}
},
model(params) {
let now = new Date();
let twoMonthsAgo = new Date(now.getFullYear(),
now.getMonth() - 2,
now.getDate());
let queryParams = {
ordering: '-arrivaldate,artist,title',
min_arrival: moment(twoMonthsAgo).format('YYYY-MM-DD'),
page: params.page
};
return this.store.query('release', queryParams);
},
afterModel() {
window.scrollTo(0,0);
}
});
|
import Ember from 'ember';
export default Ember.Route.extend({
queryParams: {
page: {
refreshModel: true
}
},
model(params) {
let now = new Date();
let twoMonthsAgo = new Date(now.getFullYear(),
now.getMonth() - 2,
now.getDate());
let queryParams = {
ordering: '-arrivaldate,artist,title',
min_arrival: moment(twoMonthsAgo).format('YYYY-MM-DD'),
page: params.page
};
return this.store.query('release', queryParams);
},
});
|
Make auto-incrementing event names work with a mixture of numeric and non-numeric event names
|
import ckan.logic as logic
import ckan.plugins.toolkit as toolkit
def event_create(context, data_dict):
""" Creates a 'event' type group with a custom unique identifier for the
event """
if data_dict.get('name'):
name = data_dict.get('name')
else:
# Generate a new operation ID
existing_events = toolkit.get_action('group_list')(
context,
{'type': 'event', 'sort': 'name desc'})
event_code = 1 #default value, if there are no existing numericly named events
for event in existing_events:
if event.isdigit():
event_code = int(event) + 1
break
name = str(event_code).zfill(5)
data_dict.update({
'name': name,
'type':'event'
})
try:
foo = toolkit.get_action('group_create')(
context,
data_dict=data_dict)
except (logic.NotFound) as e:
raise toolkit.ValidationError("foo %s" % e)
return foo
|
import ckan.logic as logic
import ckan.plugins.toolkit as toolkit
def event_create(context, data_dict):
""" Creates a 'event' type group with a custom unique identifier for the
event """
if data_dict.get('name'):
name = data_dict.get('name')
else:
# Generate a new operation ID
existing_events = toolkit.get_action('group_list')(
context,
{'type': 'event', 'sort': 'name desc'})
if len(existing_events) == 0:
event_code = 1
else:
event_code = int(existing_events[0]) + 1
name = str(event_code).zfill(5)
data_dict.update({
'name': name,
'type':'event'
})
try:
foo = toolkit.get_action('group_create')(
context,
data_dict=data_dict)
except (logic.NotFound) as e:
raise toolkit.ValidationError("foo %s" % e)
return foo
|
Bring `this` back into scope
|
import Ember from 'ember';
import RestUtils from 'moviematcher/utils/rest';
import Cookie from 'moviematcher/utils/cookies';
export default Ember.Controller.extend({
queryParams: ['redirect'],
actions: {
userLogin(username, password) {
const sessionDurationSeconds = 2 * 60 * 60; // 2 hours
return RestUtils.post(undefined, '/v1/login', {data: {username, password}})
.then((value) => {
const cookie = new Cookie('session');
cookie.save(value.session_id, sessionDurationSeconds);
if(this.get('redirect')) {
this.transitionToRoute(this.get('redirect'));
}
else {
this.transitionToRoute('index');
}
}, (reason) => {
alert(reason);
this.transitionToRoute('register');
return false;
});
}
}
});
|
import Ember from 'ember';
import RestUtils from 'moviematcher/utils/rest';
import Cookie from 'moviematcher/utils/cookies';
export default Ember.Controller.extend({
queryParams: ['redirect'],
actions: {
userLogin(username, password) {
const loginThis = this;
const sessionDurationSeconds = 2 * 60 * 60; // 2 hours
return RestUtils.post(undefined, '/v1/login', {data: {username, password}})
.then((value) => {
const cookie = new Cookie('session');
cookie.save(value.session_id, sessionDurationSeconds);
if(this.get('redirect')) {
loginThis.transitionToRoute(this.get('redirect'));
}
else {
loginThis.transitionToRoute('index');
}
}, (reason) => {
alert(reason);
loginThis.transitionToRoute('register');
return false;
});
}
}
});
|
Make custom generated anotation only availabe at source
|
package net.vergien.beanautoutils.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Used as long java8 and java9/10/.. is on the market
*/
@Retention(SOURCE)
@Target(TYPE)
public @interface Generated
{
/**
* The value element MUST have the name of the code generator. The name is
* the fully qualified name of the code generator.
*
* @return The name of the code generator
*/
String[] value();
/**
* Date when the source was generated. The date element must follow the ISO
* 8601 standard. For example the date element would have the following value
* 2017-07-04T12:08:56.235-0700 which represents 2017-07-04 12:08:56 local
* time in the U.S. Pacific Time time zone.
*
* @return The date the source was generated
*/
String date() default "";
/**
* A place holder for any comments that the code generator may want to
* include in the generated code.
*
* @return Comments that the code generated included
*/
String comments() default "";
}
|
package net.vergien.beanautoutils.annotation;
/**
* Used as long java8 and java9/10/.. is on the market
*/
public @interface Generated {
/**
* The value element MUST have the name of the code generator. The
* name is the fully qualified name of the code generator.
*
* @return The name of the code generator
*/
String[] value();
/**
* Date when the source was generated. The date element must follow the ISO
* 8601 standard. For example the date element would have the following
* value 2017-07-04T12:08:56.235-0700 which represents 2017-07-04 12:08:56
* local time in the U.S. Pacific Time time zone.
*
* @return The date the source was generated
*/
String date() default "";
/**
* A place holder for any comments that the code generator may want to
* include in the generated code.
*
* @return Comments that the code generated included
*/
String comments() default "";
}
|
Fix syntax error on phantom js browser
|
'use strict';
const BrowserWorker = require('./BrowserWorker');
const WebDriver = require('webdriverio');
class PhantomJsBrowserWorker extends BrowserWorker {
constructor(scenario) {
super(scenario);
}
setup(done) {
if(typeof Browser === 'undefined') {
global.Browser = WebDriver.remote({
capabilities: { browserName: 'phantomjs' },
services: ['phantomjs']
});
}
super.setup(() => {
Browser.init().then(() => done() , done);
})
}
teardown(done) {
super.teardown(() => Browser.end().then(() => done() , done));
}
}
module.exports = PhantomJsBrowserWorker;
|
'use strict';
const BrowserWorker = require('./BrowserWorker');
const WebDriver = require('webdriverio');
class PhantomJsBrowserWorker extends BrowserWorker {
constructor(scenario) {
super(scenario);
}
setup(done) {
if(typeof Browser === 'undefined') {
global.Browser = WebDriver.remote({
capabilities: { browserName: 'phantomjs' },
services: ['phantomjs']
});
}
super.setup(() => {
Browser.init().then(() => done() , done);
})
}
teardown(done) {
super.teardown(() => Browser.end().then(() => done() , done)});
}
}
module.exports = PhantomJsBrowserWorker;
|
Add proptype validation to Table component
|
import React from 'react';
import { map } from 'lodash';
import PropTypes from 'prop-types';
import CampaignRow from './CampaignRow';
import EventRow from './EventRow';
import './table.scss';
class Table extends React.Component {
render() {
const heading = this.props.headings.map((title, index) => {
return <th key={index} className="table__cell"><h3 className="heading -delta">{title}</h3></th>
});
// @TODO - Rethink this. Why are CampaignRow and EventRow different?
const rows = this.props.data.map((content, index) => {
if (this.props.type === 'campaigns') {
return <CampaignRow key={index} data={content} />;
}
return <EventRow key={index} data={content} />;
});
return (
<table className="table">
<thead>
<tr className="table__header">
{heading}
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
)
}
}
Table.propTypes = {
headings: PropTypes.array.isRequired, // eslint-disable-line react/forbid-prop-types
data: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
type: PropTypes.string.isRequired,
};
export default Table;
|
import React from 'react';
import { map } from 'lodash';
import CampaignRow from './CampaignRow';
import EventRow from './EventRow';
import './table.scss';
class Table extends React.Component {
render() {
const heading = this.props.headings.map((title, index) => {
return <th key={index} className="table__cell"><h3 className="heading -delta">{title}</h3></th>
});
const rows = this.props.data.map((content, index) => {
if (this.props.type === 'campaigns') {
return <CampaignRow key={index} data={content} />;
}
return <EventRow key={index} data={content} />;
});
return (
<table className="table">
<thead>
<tr className="table__header">
{heading}
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
)
}
}
export default Table;
|
Fix typo which breaks test build:
[]
GITHUB_BREAKING_CHANGES=n/a
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=339165220
|
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.invocationbuilders.javatypes;
/** Represents a template type. */
public final class TemplateJavaType extends JavaType {
public TemplateJavaType() {
this(/* isNullable= */ false);
}
public TemplateJavaType(boolean isNullable) {
super(isNullable);
}
@Override
public String toJavaTypeString() {
return "com.google.template.soy.testing.metadata.placeholdertypes.TemplatePlaceholderType";
}
@Override
public JavaType asNullable() {
return new TemplateJavaType(/* isNullable= */ true);
}
@Override
String asGenericsTypeArgumentString() {
return toJavaTypeString();
}
@Override
public String asInlineCast(String variable, int depth) {
throw new UnsupportedOperationException();
}
}
|
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.invocationbuilders.javatypes;
/** Represents a template type. */
public final class TemplateJavaType extends JavaType {
public TemplateJavaType() {
this(/* isNullable= */ false);
}
public TemplateJavaType(boolean isNullable) {
super(isNullable);
}
@Override
public String toJavaTypeString() {
return "com.google.template.soy.testing.metadata.placeholdertypes.TeplatePlaceholderType";
}
@Override
public JavaType asNullable() {
return new TemplateJavaType(/* isNullable= */ true);
}
@Override
String asGenericsTypeArgumentString() {
return toJavaTypeString();
}
@Override
public String asInlineCast(String variable, int depth) {
throw new UnsupportedOperationException();
}
}
|
Fix management command for submitted exercises
|
# -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.core.management.base import BaseCommand
from wger.exercises.models import Exercise
class Command(BaseCommand):
'''
Read out the user submitted exercise.
Used to generate the AUTHORS file for a release
'''
help = 'Read out the user submitted exercise'
def handle(self, *args, **options):
exercises = Exercise.objects.filter(status=Exercise.EXERCISE_STATUS_ACCEPTED)
usernames = []
for exercise in exercises:
if exercise.user not in usernames:
usernames.append(exercise.user)
self.stdout.write(exercise.user)
|
# -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
from django.core.management.base import BaseCommand
from wger.exercises.models import Exercise
class Command(BaseCommand):
'''
Read out the user submitted exercise.
Used to generate the AUTHORS file for a release
'''
help = 'Read out the user submitted exercise'
def handle(self, *args, **options):
exercises = Exercise.objects.filter(status=Exercise.EXERCISE_STATUS_ACCEPTED)
usernames = []
for exercise in exercises:
username = exercise.user.username
if username not in usernames:
usernames.append(username)
self.stdout.write('{0}\n'.format(username))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.