text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Remove extra regexp group from URL pattern.
|
from handlers.nodes import NodesHandler
from handlers.node import NodeHandler
from handlers.streams import StreamsHandler
from handlers.stream import StreamHandler
from handlers.ping import PingHandler
from handlers.events import EventHandler
from handlers.ticket import TicketHandler
from handlers.tickets import TicketsHandler
url_patterns = [
(r"/nodes", NodesHandler),
(r"/node/(\d+)", NodeHandler),
(r"/node", NodeHandler),
(r"/streams", StreamsHandler),
(r"/tickets", TicketsHandler),
(r"/stream/(\d+)", StreamHandler),
(r"/stream/(\d+)/tickets", TicketsHandler),
(r"/stream/(\d+)/ticket/(\d+)", TicketHandler),
(r"/stream/(\d+)/ticket", TicketHandler),
(r"/ping", PingHandler),
(r"/events", EventHandler),
]
|
from handlers.nodes import NodesHandler
from handlers.node import NodeHandler
from handlers.streams import StreamsHandler
from handlers.stream import StreamHandler
from handlers.ping import PingHandler
from handlers.events import EventHandler
from handlers.ticket import TicketHandler
from handlers.tickets import TicketsHandler
url_patterns = [
(r"/nodes", NodesHandler),
(r"/(node)/(\d+)", NodeHandler),
(r"/node", NodeHandler),
(r"/streams", StreamsHandler),
(r"/tickets", TicketsHandler),
(r"/stream/(\d+)", StreamHandler),
(r"/stream/(\d+)/tickets", TicketsHandler),
(r"/stream/(\d+)/ticket/(\d+)", TicketHandler),
(r"/stream/(\d+)/ticket", TicketHandler),
(r"/ping", PingHandler),
(r"/events", EventHandler),
]
|
Support key prefixes at the client-level
|
<?php
namespace LinkORB\Component\ObjectStorage;
use RuntimeException;
class Client
{
private $driver;
private $prefix;
public function __construct($driver, $prefix = '')
{
$this->driver = $driver;
$this->prefix = $prefix;
}
public function get($key)
{
return $this->driver->get($this->prefix . $key);
}
public function set($key, $data)
{
$this->driver->set($this->prefix . $key, $data);
}
public function delete($key)
{
$this->driver->delete($this->prefix . $key);
}
public function upload($key, $filename)
{
if (!file_exists($filename)) {
throw new RuntimeException("File not found: " . $filename);
}
$data = file_get_contents($filename);
$this->set($this->prefix . $key, $data);
}
public function download($key, $filename)
{
$data = $this->get($this->prefix . $key);
file_put_contents($filename, $data);
}
}
|
<?php
namespace LinkORB\Component\ObjectStorage;
use RuntimeException;
class Client
{
private $driver;
public function __construct($driver)
{
$this->driver = $driver;
}
public function get($key)
{
return $this->driver->get($key);
}
public function set($key, $data)
{
$this->driver->set($key, $data);
}
public function delete($key)
{
$this->driver->delete($key);
}
public function upload($key, $filename)
{
if (!file_exists($filename)) {
throw new RuntimeException("File not found: " . $filename);
}
$data = file_get_contents($filename);
$this->set($key, $data);
}
public function download($key, $filename)
{
$data = $this->get($key);
file_put_contents($filename, $data);
}
}
|
[FEATURE] Add function in client to register admin user.
|
'use strict';
angular.module('publicApp')
.controller('LoginCtrl', ['$scope', '$http', '$location', 'UserService', function ($scope, $http, $location, $user) {
function checkAdminExists() {
$http.get("/api/v1/gateway/settings").success(function(resp){
if (resp.success) {
$scope.adminExists = resp.settings.adminExists
}
$scope.loading = false
})
}
checkAdminExists()
$scope.loading = true
$scope.adminExists = false
$scope.admin = { email: '' }
$scope.user = {}
$scope.userService = $user
$scope.logout = function() {
$user.logout()
}
$scope.registerAdmin = function() {
if ($scope.admin.email) {
$http.post('/api/v1/admin/users', { email: $scope.admin.email }).success(function(resp) {
console.log(resp)
})
}
}
$scope.login = function () {
var name = $scope.user.name;
var password = $scope.user.password;
$user.login(name, password, function(err, session){
if (!!session.username) {
$location.path('/gateway/account');
} else {
$location.path('/admin/users/new');
}
})
}
}]);
|
'use strict';
angular.module('publicApp')
.controller('LoginCtrl', ['$scope', '$http', '$location', 'UserService', function ($scope, $http, $location, $user) {
function checkAdminExists() {
$http.get("/api/v1/gateway/settings").success(function(resp){
if (resp.success) {
$scope.adminExists = resp.settings.adminExists
}
$scope.loading = false
})
}
checkAdminExists()
$scope.loading = true
$scope.adminExists = false
$scope.user = {}
$scope.userService = $user
$scope.logout = function() {
$user.logout()
}
$scope.login = function () {
var name = $scope.user.name;
var password = $scope.user.password;
$user.login(name, password, function(err, session){
if (!!session.username) {
$location.path('/gateway/account');
} else {
$location.path('/admin/users/new');
}
})
}
}]);
|
Initialize the file writer by default.
|
package org.lemsml.jlemsviz;
import org.lemsml.jlems.expression.ParseError;
import org.lemsml.jlems.run.ConnectionError;
import org.lemsml.jlems.run.RuntimeError;
import org.lemsml.jlems.sim.ContentError;
import org.lemsml.jlems.sim.ParseException;
import org.lemsml.jlems.type.BuildException;
import org.lemsml.jlems.xml.XMLException;
import org.lemsml.jlemsio.Main;
import org.lemsml.jlemsio.logging.DefaultLogger;
import org.lemsml.jlemsio.out.FileResultWriterFactory;
import org.lemsml.jlemsviz.datadisplay.SwingDataViewerFactory;
public final class VizMain {
private VizMain() {
}
public static void main(String[] argv) throws ConnectionError, ContentError, RuntimeError, ParseError, ParseException, BuildException, XMLException {
FileResultWriterFactory.initialize();
SwingDataViewerFactory.initialize();
DefaultLogger.initialize();
Main.main(argv);
}
}
|
package org.lemsml.jlemsviz;
import org.lemsml.jlems.expression.ParseError;
import org.lemsml.jlems.run.ConnectionError;
import org.lemsml.jlems.run.RuntimeError;
import org.lemsml.jlems.sim.ContentError;
import org.lemsml.jlems.sim.ParseException;
import org.lemsml.jlems.type.BuildException;
import org.lemsml.jlems.xml.XMLException;
import org.lemsml.jlemsio.Main;
import org.lemsml.jlemsio.logging.DefaultLogger;
import org.lemsml.jlemsviz.datadisplay.SwingDataViewerFactory;
public final class VizMain {
private VizMain() {
}
public static void main(String[] argv) throws ConnectionError, ContentError, RuntimeError, ParseError, ParseException, BuildException, XMLException {
SwingDataViewerFactory.initialize();
DefaultLogger.initialize();
Main.main(argv);
}
}
|
Handle errors emitted from PBKDF2
|
var pbkdf2 = require('crypto').pbkdf2
, randomBytes = require('crypto').randomBytes;
exports.verify = function(password, hash, callback) {
hashParts = hash.split('$');
var iterations = hashParts[2] * 500;
var salt = hashParts[3];
var hashed_password = hashParts[4];
pbkdf2(password, salt, iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
callback(null, derivedKey.toString('hex') == hashed_password);
}
});
}
exports.crypt = function(password, cost, callback) {
if (typeof(callback) !== 'function') {
callback = cost;
cost = 2;
}
iterations = cost * 500;
randomBytes(18, function(error, buf) {
if(error) {
callback(new Error(error));
} else {
try {
pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
callback(null, hash);
}
});
} catch(e) {
callback(new Error(error));
}
}
});
}
|
var pbkdf2 = require('crypto').pbkdf2
, randomBytes = require('crypto').randomBytes;
exports.verify = function(password, hash, callback) {
hashParts = hash.split('$');
var iterations = hashParts[2] * 500;
var salt = hashParts[3];
var hashed_password = hashParts[4];
pbkdf2(password, salt, iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
callback(null, derivedKey.toString('hex') == hashed_password);
}
});
}
exports.crypt = function(password, cost, callback) {
if (typeof(callback) !== 'function') {
callback = cost;
cost = 2;
}
iterations = cost * 500;
randomBytes(18, function(error, buf) {
if(error) {
callback(new Error(error));
} else {
pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
callback(null, hash);
}
});
}
});
}
|
Remove "Graph" prefix on method names
|
package git
/*
#include <git2.h>
*/
import "C"
import (
"runtime"
)
func (repo *Repository) DescendantOf(commit, ancestor *Oid) (bool, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ret := C.git_graph_descendant_of(repo.ptr, commit.toC(), ancestor.toC())
if ret < 0 {
return false, MakeGitError(ret)
}
return (ret > 0), nil
}
func (repo *Repository) AheadBehind(local, upstream *Oid) (ahead, behind int, err error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var aheadT C.size_t
var behindT C.size_t
ret := C.git_graph_ahead_behind(&aheadT, &behindT, repo.ptr, local.toC(), upstream.toC())
if ret < 0 {
return 0, 0, MakeGitError(ret)
}
return int(aheadT), int(behindT), nil
}
|
package git
/*
#include <git2.h>
*/
import "C"
import (
"runtime"
)
func (repo *Repository) GraphDescendantOf(commit, ancestor *Oid) (bool, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ret := C.git_graph_descendant_of(repo.ptr, commit.toC(), ancestor.toC())
if ret < 0 {
return false, MakeGitError(ret)
}
return (ret > 0), nil
}
func (repo *Repository) GraphAheadBehind(local, upstream *Oid) (ahead, behind int, err error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var aheadT C.size_t
var behindT C.size_t
ret := C.git_graph_ahead_behind(&aheadT, &behindT, repo.ptr, local.toC(), upstream.toC())
if ret < 0 {
return 0, 0, MakeGitError(ret)
}
return int(aheadT), int(behindT), nil
}
|
Update to emergency shutdown endpoint for tests
|
package web
import (
"github.com/control-center/serviced/dao"
rest "github.com/zenoss/go-json-rest"
)
type EmergencyShutdownRequest struct {
Operation int // 0 is emergency shutdown, 1 is clear emergency shutdown status
TenantID string
}
func restEmergencyShutdown(w *rest.ResponseWriter, r *rest.Request, ctx *requestContext) {
req := EmergencyShutdownRequest{}
err := r.DecodeJsonPayload(&req)
if err != nil {
plog.WithError(err).Error("Could not decode json payload for emergency shutdown request")
restBadRequest(w, err)
return
}
daoReq := dao.ScheduleServiceRequest{
ServiceID: req.TenantID,
AutoLaunch: true,
Synchronous: false,
}
go ctx.getFacade().EmergencyStopService(ctx.getDatastoreContext(), daoReq)
restSuccess(w)
}
|
package web
import (
"github.com/control-center/serviced/dao"
rest "github.com/zenoss/go-json-rest"
)
type EmergencyShutdownRequest struct {
Operation int // 0 is emergency shutdown, 1 is clear emergency shutdown status
TenantID string
}
func restEmergencyShutdown(w *rest.ResponseWriter, r *rest.Request, ctx *requestContext) {
req := EmergencyShutdownRequest{}
err := r.DecodeJsonPayload(&req)
if err != nil {
plog.WithError(err).Error("Could not decode json payload for emergency shutdown request")
restBadRequest(w, err)
return
}
daoReq := dao.ScheduleServiceRequest{
ServiceID: req.TenantID,
AutoLaunch: true,
Synchronous: false,
}
n, err := ctx.getFacade().EmergencyStopService(ctx.getDatastoreContext(), daoReq)
if err != nil {
plog.WithError(err).Error("Facade could not process Emergency Shutdown Request")
restBadRequest(w, err)
return
}
plog.Infof("Scheduled %d services", n)
restSuccess(w)
}
|
Change static variables to private
|
<?php
namespace Axllent\Gfmarkdown\FieldTypes;
use Parsedown;
use SilverStripe\ORM\FieldType\DBText;
class Markdown extends DBText
{
private static $casting = array(
'AsHTML' => 'HTMLText',
'Markdown' => 'Text'
);
private static $escape_type = 'xml';
/**
* Render markdown as HTML using Parsedown
*
* @return string Markdown rendered as HTML
*/
public function AsHTML()
{
$parsedown = new Parsedown();
$options = $this->config()->get('options');
foreach ($options as $fn => $param) {
if (method_exists($parsedown, $fn)) {
$parsedown->{$fn}($param);
}
}
return $parsedown->text($this->value);
}
/**
* Renders the field used in the template
* @return string HTML to be used in the template
*/
public function forTemplate()
{
return $this->AsHTML();
}
}
|
<?php
namespace Axllent\Gfmarkdown\FieldTypes;
use Parsedown;
use SilverStripe\ORM\FieldType\DBText;
class Markdown extends DBText
{
public static $casting = array(
'AsHTML' => 'HTMLText',
'Markdown' => 'Text'
);
public static $escape_type = 'xml';
private static $options = [];
/**
* Render markdown as HTML using Parsedown
*
* @return string Markdown rendered as HTML
*/
public function AsHTML()
{
$parsedown = new Parsedown();
$options = $this->config()->get('options');
foreach ($options as $fn => $param) {
if (method_exists($parsedown, $fn)) {
$parsedown->{$fn}($param);
}
}
return $parsedown->text($this->value);
}
/**
* Renders the field used in the template
* @return string HTML to be used in the template
*/
public function forTemplate()
{
return $this->AsHTML();
}
}
|
Split up assignment logic and add elucidating comment
This is the first in a line of commit intended to make this module more useable
|
'use strict';
var fs = require('fs');
/*
* read *.<type> files at given `path',
* return array of files and their
* textual content
*/
exports.read = function (path, type, callback) {
var textFiles = {};
var regex = new RegExp("\\." + type);
var typeLen = (type.length * -1) -1;
fs.readdir(path, function (error, files) {
if (error) throw new Error("Error reading from path: " + path);
for (var file = 0; file < files.length; file++) {
if (files[file].match(regex)) {
// load textFiles with content
textFiles[files[file]
.slice(0, typeLen] = fs.readFileSync(path
+ '/'
+ files[file]
, 'utf8');
}
}
if (typeof callback === 'function') {
callback(textFiles);
}
});
}
|
'use strict';
var fs = require('fs');
/*
* read *.<type> files at given `path',
* return array of files and their
* textual content
*/
exports.read = function (path, type, callback) {
var textFiles = {};
var regex = new RegExp("\\." + type);
fs.readdir(path, function (error, files) {
if (error) throw new Error("Error reading from path: " + path);
for (var file = 0; file < files.length; file++) {
if (files[file].match(regex)) {
textFiles[files[file]
.slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path
+ '/'
+ files[file]
, 'utf8');
}
}
if (typeof callback === 'function') {
callback(textFiles);
}
});
}
|
Add get_language method for TranslationsMixin
|
class TranslationsMixin(object):
"Helper for getting transalations"
SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed
LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed
def get_translations(self):
"Query set for the translations"
self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS)
self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS)
slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug}
lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang}
return self.__class__.objects.filter(**slug).exclude(**lang)
def get_language(self):
"Get the language display for this item's language"
attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS)
return getattr(self, attr)()
|
class TranslationsMixin(object):
"Helper for getting transalations"
SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed
LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed
def get_translations(self):
"Query set for the translations"
self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS)
self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS)
slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug}
lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang}
return self.__class__.objects.filter(**slug).exclude(**lang)
|
Add sibling `vendor` folder location
For the development use case where all repositories are checked out into a flat folder hierarchy (mirroring the GitHub org), the `vendor` folder will end up being a sibling to the `wp-cli` framework folder.
The bootstrapping code needs to allow for this setup as well.
|
<?php
// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );
if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) {
define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) {
define( 'WP_CLI_VENDOR_DIR', dirname( dirname( WP_CLI_ROOT ) ) );
} elseif ( file_exists( dirname( WP_CLI_ROOT ) . '/vendor/autoload.php' ) ) {
define( 'WP_CLI_VENDOR_DIR', dirname( WP_CLI_ROOT ) . '/vendor' );
} else {
define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
}
// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
require_once WP_CLI_ROOT . '/php/bootstrap.php';
\WP_CLI\bootstrap();
|
<?php
// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );
if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) {
define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) {
define( 'WP_CLI_VENDOR_DIR', dirname( dirname( WP_CLI_ROOT ) ) );
} else {
define( 'WP_CLI_VENDOR_DIR', WP_CLI_ROOT . '/vendor' );
}
// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
require_once WP_CLI_ROOT . '/php/bootstrap.php';
\WP_CLI\bootstrap();
|
Add onset detection processing node to top-level exports
|
from node.duration import \
Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds
from node.audio_metadata import MetaData, AudioMetaDataEncoder
from node.ogg_vorbis import \
OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \
OggVorbisWrapper
from node.audiostream import AudioStream
from node.basic import Slice, Sum, Max
from node.learn import KMeans, BinaryRbm, LinearRbm, Learned
from node.onset import \
MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \
SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain
from node.preprocess import \
MeanStdNormalization, UnitNorm, PreprocessingPipeline
from node.random_samples import ReservoirSampler
from node.resample import Resampler
from node.samplerate import \
SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped
from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc
from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC
from node.template_match import TemplateMatch
from node.timeseries import \
TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \
GreedyConstantRateTimeSeriesDecoder
from node.api import ZoundsApp
from node.util import process_dir
|
from node.duration import \
Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds
from node.audio_metadata import MetaData, AudioMetaDataEncoder
from node.ogg_vorbis import \
OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \
OggVorbisWrapper
from node.audiostream import AudioStream
from node.basic import Slice, Sum, Max
from node.learn import KMeans, BinaryRbm, LinearRbm, Learned
from node.onset import \
MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \
SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature
from node.preprocess import \
MeanStdNormalization, UnitNorm, PreprocessingPipeline
from node.random_samples import ReservoirSampler
from node.resample import Resampler
from node.samplerate import \
SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped
from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc
from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC
from node.template_match import TemplateMatch
from node.timeseries import \
TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \
GreedyConstantRateTimeSeriesDecoder
from node.api import ZoundsApp
from node.util import process_dir
|
Fix a sluice test with probablistic failure.
The synchronization wasn't wrong: the test was. If you sign up another channel first, *then* send, it's random -- up to map order -- which one will get it.
The test now sends that message, then signs up the next channel, making the behavior predictable.
Though it's always amusing to me to see things like map iteration on a 2-item map be "AB" 80% of the time and "BA" 20% of the time. An interesting form of random, that. Nobody promised uniform distribution, just... wat.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us>
|
package sluice
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test(t *testing.T) {
Convey("Sluice can...", t, func() {
gondola := New()
Convey("pump values", func() {
gondola.Push("x")
gondola.Push("y")
gondola.Push("z")
So(<-gondola.Next(), ShouldEqual, "x")
So(<-gondola.Next(), ShouldEqual, "y")
So(<-gondola.Next(), ShouldEqual, "z")
})
Convey("block when empty", func() {
var answered bool
select {
case <-gondola.Next():
answered = true
default:
answered = false
}
So(answered, ShouldEqual, false)
Convey("answers even dropped channels", func() {
gondola.Push("1")
// we still don't expect an answer,
// because the "1" routed to the channel in the prev test.
secondReq := gondola.Next()
select {
case <-secondReq:
answered = true
default:
answered = false
}
So(answered, ShouldEqual, false)
Convey("definitely answers eventually", func() {
gondola.Push("2")
So(<-secondReq, ShouldEqual, "2")
})
})
})
})
}
|
package sluice
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test(t *testing.T) {
Convey("Sluice can...", t, func() {
gondola := New()
Convey("pump values", func() {
gondola.Push("x")
gondola.Push("y")
gondola.Push("z")
So(<-gondola.Next(), ShouldEqual, "x")
So(<-gondola.Next(), ShouldEqual, "y")
So(<-gondola.Next(), ShouldEqual, "z")
})
Convey("block when empty", func() {
var answered bool
select {
case <-gondola.Next():
answered = true
default:
answered = false
}
So(answered, ShouldEqual, false)
Convey("answers even dropped channels", func() {
secondReq := gondola.Next()
gondola.Push("1")
// we still don't expect an answer,
// because the "1" routed to the channel in the prev test.
select {
case <-secondReq:
answered = true
default:
answered = false
}
So(answered, ShouldEqual, false)
Convey("definitely answers eventually", func() {
gondola.Push("2")
So(<-secondReq, ShouldEqual, "2")
})
})
})
})
}
|
Add another default from JSLint.
|
package com.googlecode.jslint4java.eclipse.preferences;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import com.googlecode.jslint4java.Option;
import com.googlecode.jslint4java.eclipse.JSLintPlugin;
/**
* Set up the default preferences. By default,we enable:
* <ul>
* <li> {@link Option#EQEQEQ}
* <li> {@link Option#UNDEF}
* <li> {@link Option#WHITE}
* <li>
*/
public class PreferencesInitializer extends AbstractPreferenceInitializer {
private static final int DEFAULT_INDENT = 4;
private static final int DEFAULT_MAXERR = 50;
private final Set<Option> defaultEnable = EnumSet.of(Option.EQEQEQ, Option.UNDEF, Option.WHITE);
@Override
public void initializeDefaultPreferences() {
IEclipsePreferences node = new DefaultScope().getNode(JSLintPlugin.PLUGIN_ID);
for (Option o : defaultEnable) {
node.putBoolean(o.getLowerName(), true);
}
// Hand code these.
node.putInt(Option.INDENT.getLowerName(), DEFAULT_INDENT);
node.putInt(Option.MAXERR.getLowerName(), DEFAULT_MAXERR);
}
}
|
package com.googlecode.jslint4java.eclipse.preferences;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import com.googlecode.jslint4java.Option;
import com.googlecode.jslint4java.eclipse.JSLintPlugin;
/**
* Set up the default preferences. By default,we enable:
* <ul>
* <li> {@link Option#EQEQEQ}
* <li> {@link Option#UNDEF}
* <li> {@link Option#WHITE}
* <li>
*/
public class PreferencesInitializer extends AbstractPreferenceInitializer {
private static final int DEFAULT_INDENT = 4;
private final Set<Option> defaultEnable = EnumSet.of(Option.EQEQEQ, Option.UNDEF, Option.WHITE);
@Override
public void initializeDefaultPreferences() {
IEclipsePreferences node = new DefaultScope().getNode(JSLintPlugin.PLUGIN_ID);
for (Option o : defaultEnable) {
node.putBoolean(o.getLowerName(), true);
}
// Hand code these.
node.putInt(Option.INDENT.getLowerName(), DEFAULT_INDENT);
}
}
|
Allow freedomcfg to be passed in to setupFreedom.
|
Components.utils.import("resource://gre/modules/devtools/Console.jsm");
Components.utils.import("resource://gre/modules/Timer.jsm");
Components.utils.import('resource://gre/modules/Services.jsm');
// This module does not support all of es6 promise functionality.
// Components.utils.import("resource://gre/modules/Promise.jsm");
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest");
Components.utils.importGlobalProperties(['URL']);
var hiddenWindow = Services.appShell.hiddenDOMWindow;
var mozRTCPeerConnection = hiddenWindow.mozRTCPeerConnection;
var mozRTCSessionDescription = hiddenWindow.mozRTCSessionDescription;
var mozRTCIceCandidate = hiddenWindow.mozRTCIceCandidate;
// Replace Blob with blob that has prototype defined.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1007318
var Blob = hiddenWindow.Blob;
var firefoxExtension = true;
var freedom;
function setupFreedom(manifest, debug, freedomcfg) {
if (this.freedom) {
return this.freedom;
}
var lastSlash = manifest.lastIndexOf("/");
var manifestLocation = manifest.substring(0, lastSlash + 1);
//var manifestFilename = manifest.substring(lastSlash + 1);
firefox_config = {
isApp: false,
manifest: manifest,
portType: 'Worker',
stayLocal: true,
location: manifestLocation,
debug: debug || false,
moduleContext: false
};
|
Components.utils.import("resource://gre/modules/devtools/Console.jsm");
Components.utils.import("resource://gre/modules/Timer.jsm");
Components.utils.import('resource://gre/modules/Services.jsm');
// This module does not support all of es6 promise functionality.
// Components.utils.import("resource://gre/modules/Promise.jsm");
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest");
Components.utils.importGlobalProperties(['URL']);
var hiddenWindow = Services.appShell.hiddenDOMWindow;
var mozRTCPeerConnection = hiddenWindow.mozRTCPeerConnection;
var mozRTCSessionDescription = hiddenWindow.mozRTCSessionDescription;
var mozRTCIceCandidate = hiddenWindow.mozRTCIceCandidate;
// Replace Blob with blob that has prototype defined.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1007318
var Blob = hiddenWindow.Blob;
var freedom;
function setupFreedom(manifest, debug) {
if (this.freedom) {
return this.freedom;
}
var lastSlash = manifest.lastIndexOf("/");
var manifestLocation = manifest.substring(0, lastSlash + 1);
//var manifestFilename = manifest.substring(lastSlash + 1);
firefox_config = {
isApp: false,
manifest: manifest,
portType: 'Worker',
stayLocal: true,
location: manifestLocation,
debug: debug || false,
moduleContext: false
};
|
Patch from Dave to make requestCompleted() final and to add a retype() method.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@2572 6335cc39-0255-0410-8fd6-9bcaacd3b74c
|
//
// $Id$
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2007 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
/**
* The pessimist's dream. This ResultListener silently eats requestCompleted but makes subclasses
* handle requestFailed.
*/
public abstract class FailureListener<T>
implements ResultListener<T>
{
// from interface ResultListener
public final void requestCompleted (T result)
{
// Yeah, yeah, yeah. You did something. Good for you.
}
/**
* Recasts us to look like we're of a different type. We can safely do this because we know
* that requestCompleted never actually looks at the value passed in.
*/
public <V> FailureListener<V> retype (Class<V> klass)
{
@SuppressWarnings("unchecked") FailureListener<V> casted = (FailureListener<V>)this;
return casted;
}
}
|
//
// $Id$
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2007 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
/**
* The pessimist's dream. This ResultListener silently eats requestCompleted but makes subclasses
* handle requestFailed.
*/
public abstract class FailureListener<T>
implements ResultListener<T>
{
// documentation inherited from interface ResultListener
public void requestCompleted (T result)
{
// Yeah, yeah, yeah. You did something. Good for you.
}
}
|
Add $useAutoIncrement property to model template
|
<@php
namespace {namespace};
use CodeIgniter\Model;
class {class} extends Model
{
protected $table = '{table}';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $DBGroup = '{dbgroup}';
protected $returnType = '{return}';
protected $useSoftDeletes = false;
protected $allowedFields = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $protectFields = true;
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
|
<@php
namespace {namespace};
use CodeIgniter\Model;
class {class} extends Model
{
protected $table = '{table}';
protected $primaryKey = 'id';
protected $insertID = 0;
protected $DBGroup = '{dbgroup}';
protected $returnType = '{return}';
protected $useSoftDeletes = false;
protected $allowedFields = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $protectFields = true;
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
|
Change the URL of Facebook Like
|
'use strict';
angular.module('angularjsRundownApp')
.factory('facebookApi', ['$q', 'facebookAppId', function($q, facebookAppId) {
// Public API here
return {
favoriteMovie: function(movie) {
var defer = $q.defer();
FB.api(
'me/kinetoscope:favorite',
'post',
{
movie: "http://kinetoscope.herokuapp.com/#!/movie/" + movie.id,
},
function(response) {
defer.resolve(response);
}
);
return defer.promise;
}
};
}]);
|
'use strict';
angular.module('angularjsRundownApp')
.factory('facebookApi', ['$q', 'facebookAppId', function($q, facebookAppId) {
// Public API here
return {
favoriteMovie: function(movie) {
var defer = $q.defer();
FB.api(
'me/kinetoscope:favorite',
'post',
{
movie: "http://kinetoscope.herokuapp.com/#/movie/" + movie.id,
},
function(response) {
defer.resolve(response);
}
);
return defer.promise;
}
};
}]);
|
Add semicolon as first character
To be better protected against other bad javascript code.
|
/**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.1
* @licence MIT
*/
;(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
/* We store the condition given in the if() method */
var condition;
$.fn["if"] = function(options) {
orig = this;
condition = !!options;
if (!condition) {
return $undef;
} else {
return this;
}
};
$.fn["else"] = function( options) {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function(options) {
if (orig === undefined)
throw "fi() can't be used before if()";
var toReturn = orig;
orig = undefined;
return toReturn;
};
})(jQuery);
|
/**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.1
* @licence MIT
*/
(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
/* We store the condition given in the if() method */
var condition;
$.fn["if"] = function(options) {
orig = this;
condition = !!options;
if (!condition) {
return $undef;
} else {
return this;
}
};
$.fn["else"] = function( options) {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function(options) {
if (orig === undefined)
throw "fi() can't be used before if()";
var toReturn = orig;
orig = undefined;
return toReturn;
};
})(jQuery);
|
Add logging initializer to tests
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.sample.data.jpa;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.initializer.ConfigFileApplicationContextInitializer;
import org.springframework.boot.context.initializer.LoggingApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* Base class for integration tests. Mimics the behaviour of
* {@link SpringApplication#run(String...)}.
*
* @author Oliver Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = SampleDataJpaApplication.class, initializers = {
ConfigFileApplicationContextInitializer.class,
LoggingApplicationContextInitializer.class })
public abstract class AbstractIntegrationTests {
}
|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.sample.data.jpa;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.initializer.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* Base class for integration tests. Mimics the behavior of
* {@link SpringApplication#run(String...)}.
*
* @author Oliver Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = SampleDataJpaApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
public abstract class AbstractIntegrationTests {
}
|
Exclude bower components from linting
|
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
gulp.task('lint', function() {
return gulp.src(['./src/**/*.js', '!./src/static/bower_components{,**}',
'./test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
function test(srcPath) {
return gulp.src(srcPath, {read: false})
.pipe(mocha())
.on('error', gutil.log);
}
gulp.task('commitTests', function() {
return test('./test/commit/**/*.js');
});
gulp.task('acceptanceTests', function() {
return test('./test/acceptance/**/*.js');
});
gulp.task('watch', ['lint', 'commitTests', 'acceptanceTests']);
gulp.task('default', ['watch'], function() {
gulp.watch(['./src/**/*.js', '!./src/static/bower_coponents{,**}',
'./test/**/*.js'], ['watch']);
});
|
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
gulp.task('lint', function() {
return gulp.src(['./src/**/*.js', './test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
function test(srcPath) {
return gulp.src(srcPath)
.pipe(mocha())
.on('error', gutil.log);
}
gulp.task('commitTests', function() {
return test('./test/commit/**/*.js');
});
gulp.task('acceptanceTests', function() {
return test('./test/acceptance/**/*.js');
});
gulp.task('watch', ['lint', 'commitTests', 'acceptanceTests']);
gulp.task('default', ['watch'], function() {
gulp.watch(['./src/**/*.js', './test/**/*.js'], ['watch']);
});
|
Remove extra quote from template in BreadcrumbsHelper.
|
<?php
/**
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file
* Redistributions of files must retain the above copyright notice.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/mit-license.php
*
*
* @copyright Copyright (c) Mikaël Capelle (https://typename.fr)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Bootstrap\View\Helper;
use Cake\View\Helper\BreadcrumbsHelper;
class BootstrapBreadcrumbsHelper extends BreadcrumbsHelper {
/**
* Default config for the helper.
*
* @var array
*/
protected $_defaultConfig = [
'templates' => [
'wrapper' => '<ol class="breadcrumb{{attrs.class}}"{{attrs}}>{{content}}</ol>',
'item' => '<li{{attrs}}><a href="{{url}}"{{innerAttrs}}>{{title}}</a></li>',
'itemWithoutLink' => '<li class="active{{attrs.class}}"{{attrs}}>{{title}}</li>',
'separator' => ''
],
'templateClass' => 'Bootstrap\View\BootstrapStringTemplate'
];
};
|
<?php
/**
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file
* Redistributions of files must retain the above copyright notice.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/mit-license.php
*
*
* @copyright Copyright (c) Mikaël Capelle (https://typename.fr)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Bootstrap\View\Helper;
use Cake\View\Helper\BreadcrumbsHelper;
class BootstrapBreadcrumbsHelper extends BreadcrumbsHelper {
/**
* Default config for the helper.
*
* @var array
*/
protected $_defaultConfig = [
'templates' => [
'wrapper' => '<ol class="breadcrumb{{attrs.class}}"{{attrs}}">{{content}}</ol>',
'item' => '<li{{attrs}}><a href="{{url}}"{{innerAttrs}}>{{title}}</a></li>',
'itemWithoutLink' => '<li class="active{{attrs.class}}"{{attrs}}>{{title}}</li>',
'separator' => ''
],
'templateClass' => 'Bootstrap\View\BootstrapStringTemplate'
];
};
|
Exclude upper case letters from generated passwords.
12 character passwords from the set a-z0-9 have more bits of
entropy (62) than 10 character passwords from the set
a-zA-Z0-9 (60), and are probably perceived as nicer by the
users too (less ambiguity, easier to type on smartphones and
the like).
|
from pwgen import pwgen
from re import findall
import vccs_client
def generate_password(settings, credential_id, email):
"""
Generate a new password credential and add it to the VCCS authentication backend.
The salt returned needs to be saved for use in subsequent authentications using
this password. The password is returned so that it can be conveyed to the user.
:param settings: settings dict
:param credential_id: VCCS credential_id as string
:param email: user e-mail address as string
:return: (password, salt) both strings
"""
password = pwgen(settings.get('password_length'), no_capitalize = True, no_symbols = True)
factor = vccs_client.VCCSPasswordFactor(password,
credential_id = credential_id)
vccs = vccs_client.VCCSClient(base_url = settings.get('vccs_url'))
vccs.add_credentials(email, [factor])
return (_human_readable(password), factor.salt)
def _human_readable(password):
"""
Format a random password more readable to humans (groups of four characters).
:param password: string
:return: readable password as string
:rtype: string
"""
regexp = '.{,4}'
parts = findall(regexp, password)
return ' '.join(parts)
|
from pwgen import pwgen
from re import findall
import vccs_client
def generate_password(settings, credential_id, email):
"""
Generate a new password credential and add it to the VCCS authentication backend.
The salt returned needs to be saved for use in subsequent authentications using
this password. The password is returned so that it can be conveyed to the user.
:param settings: settings dict
:param credential_id: VCCS credential_id as string
:param email: user e-mail address as string
:return: (password, salt) both strings
"""
password = pwgen(settings.get('password_length'), no_symbols = True)
factor = vccs_client.VCCSPasswordFactor(password,
credential_id = credential_id)
vccs = vccs_client.VCCSClient(base_url = settings.get('vccs_url'))
vccs.add_credentials(email, [factor])
return (_human_readable(password), factor.salt)
def _human_readable(password):
"""
Format a random password more readable to humans (groups of four characters).
:param password: string
:return: readable password as string
:rtype: string
"""
regexp = '.{,4}'
parts = findall(regexp, password)
return ' '.join(parts)
|
Update for string.fromcodepoint v1.0.0 API
|
import 'browser-polyfills';
import 'string.fromcodepoint/auto';
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
// polyfill requestIdleCallback
window.requestIdleCallback = window.requestIdleCallback ||
function(cb) {
var start = Date.now();
return window.requestAnimationFrame(function() {
cb({
didTimeout: false,
timeRemaining: function() {
return Math.max(0, 50 - (Date.now() - start));
}
});
});
};
window.cancelIdleCallback = window.cancelIdleCallback ||
function(id) {
window.cancelAnimationFrame(id);
};
import * as iD from './index';
window.iD = iD;
|
import 'browser-polyfills';
import 'string.fromcodepoint';
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
// polyfill requestIdleCallback
window.requestIdleCallback = window.requestIdleCallback ||
function(cb) {
var start = Date.now();
return window.requestAnimationFrame(function() {
cb({
didTimeout: false,
timeRemaining: function() {
return Math.max(0, 50 - (Date.now() - start));
}
});
});
};
window.cancelIdleCallback = window.cancelIdleCallback ||
function(id) {
window.cancelAnimationFrame(id);
};
import * as iD from './index';
window.iD = iD;
|
Fix base class for python 2.x
|
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color(object):
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile(object):
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color:
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile:
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
Make test environment use CNOT_CR implementation of CNOT.
At least for the test_pulse_types tests.
|
import unittest
from QGL import *
from QGL.PulseSequencer import *
import QGL.config
from .helpers import setup_test_lib
class PulseTypes(unittest.TestCase):
def setUp(self):
setup_test_lib()
QGL.config.cnot_implementation = 'CNOT_CR'
self.q1 = QubitFactory('q1')
self.q2 = QubitFactory('q2')
self.q3 = QubitFactory('q3')
self.q4 = QubitFactory('q4')
def test_promotion_rules(self):
q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4
assert( type(X(q1)) == Pulse )
assert( type(X(q1) + Y(q1)) == CompositePulse )
assert( type(X(q1) * X(q2)) == PulseBlock )
assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock )
assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate )
assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
|
import unittest
from QGL import *
from QGL.PulseSequencer import *
from .helpers import setup_test_lib
class PulseTypes(unittest.TestCase):
def setUp(self):
setup_test_lib()
self.q1 = QubitFactory('q1')
self.q2 = QubitFactory('q2')
self.q3 = QubitFactory('q3')
self.q4 = QubitFactory('q4')
def test_promotion_rules(self):
q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4
assert( type(X(q1)) == Pulse )
assert( type(X(q1) + Y(q1)) == CompositePulse )
assert( type(X(q1) * X(q2)) == PulseBlock )
assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock )
assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate )
assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
|
Use pathlib to read ext.conf
|
import pathlib
from mopidy import config, ext
__version__ = "1.1.1"
class Extension(ext.Extension):
dist_name = "Mopidy-ALSAMixer"
ext_name = "alsamixer"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["card"] = config.Integer(minimum=0)
schema["control"] = config.String()
schema["min_volume"] = config.Integer(minimum=0, maximum=100)
schema["max_volume"] = config.Integer(minimum=0, maximum=100)
schema["volume_scale"] = config.String(
choices=("linear", "cubic", "log")
)
return schema
def setup(self, registry):
from mopidy_alsamixer.mixer import AlsaMixer
registry.add("mixer", AlsaMixer)
|
import os
from mopidy import config, ext
__version__ = "1.1.1"
class Extension(ext.Extension):
dist_name = "Mopidy-ALSAMixer"
ext_name = "alsamixer"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["card"] = config.Integer(minimum=0)
schema["control"] = config.String()
schema["min_volume"] = config.Integer(minimum=0, maximum=100)
schema["max_volume"] = config.Integer(minimum=0, maximum=100)
schema["volume_scale"] = config.String(
choices=("linear", "cubic", "log")
)
return schema
def setup(self, registry):
from mopidy_alsamixer.mixer import AlsaMixer
registry.add("mixer", AlsaMixer)
|
fix: Make codesplitting split on each container
|
import React from 'react';
import { get } from 'lodash';
import { IndexRoute, Route } from 'react-router';
import App from './containers/App';
function getLandingPage(name) {
return ;
}
function loginRequired(nextState, replace) {
if (!get(window.user, 'isAuthenticated')) {
replace({ pathname: '/' });
}
}
export default (
<Route path="/" component={App}>
<IndexRoute
getComponent={(location, callback) => {
require.ensure([], require => {
callback(null, require('./containers/LandingPage').default);
});
}}
/>
<Route
path="projects/:owner/:name"
getComponent={(location, callback) => {
require.ensure([], require => {
callback(null, require('./containers/ProjectDetails').default);
});
}}
onEnter={loginRequired}
/>
<Route
path="*"
getComponent={(location, callback) => {
require.ensure([], require => {
callback(null, require('./containers/NotFound').default);
});
}}
onEnter={loginRequired}
/>
</Route>
);
|
import React from 'react';
import { get } from 'lodash';
import { IndexRoute, Route } from 'react-router';
import App from './containers/App';
function getContainer(name) {
return (location, callback) => {
require.ensure([], require => {
callback(null, require(`./containers/${name}`).default);
});
};
}
function loginRequired(nextState, replace) {
if (!get(window.user, 'isAuthenticated')) {
replace({ pathname: '/' });
}
}
export default (
<Route path="/" component={App}>
<IndexRoute getComponent={getContainer('LandingPage')} />
<Route
path="projects/:owner/:name"
getComponent={getContainer('ProjectDetails')}
onEnter={loginRequired}
/>
<Route path="*" getComponent={getContainer('NotFound')} onEnter={loginRequired} />
</Route>
);
|
Revert "* adding a method for cleaning the uris"
This reverts commit 8841631a74b0e67c54e86466b16772f2898740ec.
|
<?php
/**
* @package vsc_infrastructure
* @author marius orcsik <marius@habarnam.ro>
* @date 10.04.16
*/
class vscString {
static function stripTags ($sString) {
return ereg_replace("<[a-z\/\":=]*>", '', $sString);
}
static function stripEntities ($sString) {
return html_entity_decode($sString, ENT_NOQUOTES, 'UTF-8');
}
static function _echo ($sString, $iTimes = 1) {
for ($i = 0; $i <= $iTimes; $i++)
echo $sString;
}
/**
* returns an end of line, based on the environment
* @return string
*/
static public function nl () {
return isCli() ? "\n" : '<br/>' . "\n";
}
/**
* Removes all extra spaces from a string
* @param string $s
* @return string
*/
static public function allTrim ($sString) {
return trim (ereg_replace('/\s+/', ' ', $sString));
}
}
|
<?php
/**
* @package vsc_infrastructure
* @author marius orcsik <marius@habarnam.ro>
* @date 10.04.16
*/
class vscString {
static function stripTags ($sString) {
return ereg_replace("<[a-z\/\":=]*>", '', $sString);
}
static function stripEntities ($sString) {
return html_entity_decode($sString, ENT_NOQUOTES, 'UTF-8');
}
static function _echo ($sString, $iTimes = 1) {
for ($i = 0; $i <= $iTimes; $i++)
echo $sString;
}
/**
* returns an end of line, based on the environment
* @return string
*/
static public function nl () {
return isCli() ? "\n" : '<br/>' . "\n";
}
/**
* Removes all extra spaces from a string
* @param string $s
* @return string
*/
static public function allTrim ($sString) {
return trim (ereg_replace('/\s+/', ' ', $sString));
}
static public function formatUri ($sString) {
$aToReplace = array (
'/(&([^(amp;)]+=))/'
);
$aReplaceWith = array (
'&\2'
);
return preg_replace($aToReplace, $aReplaceWith, $sString);
}
}
|
Update dsub version to 0.3.3
PiperOrigin-RevId: 266979768
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.3'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.3.dev0'
|
Return back input stream in getContent
|
package id.kodekreatif.cordova.PDFDigiSign;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.cms.CMSObjectIdentifiers;
import org.spongycastle.cms.CMSException;
import org.spongycastle.cms.CMSTypedData;
class PDFDigiSignData implements CMSTypedData
{
InputStream in;
private static final int BUFFER_SIZE = 10240;
private final ASN1ObjectIdentifier type;
public PDFDigiSignData(ASN1ObjectIdentifier type,
InputStream is)
{
this.type = type;
in = is;
}
public PDFDigiSignData(InputStream is)
{
this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
}
@Override
public Object getContent()
{
return in;
}
@Override
public void write(OutputStream out) throws IOException, CMSException
{
// read the content only one time
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while ((c = in.read(buffer)) != -1)
{
out.write(buffer, 0, c);
}
in.close();
}
@Override
public ASN1ObjectIdentifier getContentType() {
return type;
}
}
|
package id.kodekreatif.cordova.PDFDigiSign;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.cms.CMSObjectIdentifiers;
import org.spongycastle.cms.CMSException;
import org.spongycastle.cms.CMSTypedData;
class PDFDigiSignData implements CMSTypedData
{
InputStream in;
private static final int BUFFER_SIZE = 10240;
private final ASN1ObjectIdentifier type;
public PDFDigiSignData(ASN1ObjectIdentifier type,
InputStream is)
{
this.type = type;
in = is;
}
public PDFDigiSignData(InputStream is)
{
this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
}
@Override
public Object getContent()
{
return null;
}
@Override
public void write(OutputStream out) throws IOException, CMSException
{
// read the content only one time
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while ((c = in.read(buffer)) != -1)
{
out.write(buffer, 0, c);
}
in.close();
}
@Override
public ASN1ObjectIdentifier getContentType() {
return type;
}
}
|
Add ginkgo defer to allow us to see error message
-This is when the main_suite_test fails before running
the main_test
|
package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
defer GinkgoRecover()
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
|
package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
|
Fix so that Timestamp objects get formatted as Date's
|
package com.bradmcevoy.http.values;
import com.bradmcevoy.http.DateUtils;
import com.bradmcevoy.http.DateUtils.DateParseException;
import com.bradmcevoy.http.XmlWriter;
import java.util.Date;
import java.util.Map;
public class DateValueWriter implements ValueWriter {
@Override
public boolean supports( String nsUri, String localName, Class c ) {
return c.isInstance(Date.class);
}
@Override
public void writeValue( XmlWriter writer, String nsUri, String prefix, String localName, Object val, String href, Map<String, String> nsPrefixes ) {
if( val == null ) {
writer.writeProperty( prefix, localName );
} else {
Date date = (Date) val;
String s = DateUtils.formatDate( date );
writer.writeProperty( prefix, localName, s );
}
}
@Override
public Object parse( String namespaceURI, String localPart, String value ) {
if( value == null || value.length() == 0 ) return null;
Date dt;
try {
dt = DateUtils.parseDate( value );
return dt;
} catch( DateParseException ex ) {
throw new RuntimeException( value, ex );
}
}
}
|
package com.bradmcevoy.http.values;
import com.bradmcevoy.http.DateUtils;
import com.bradmcevoy.http.DateUtils.DateParseException;
import com.bradmcevoy.http.XmlWriter;
import java.util.Date;
import java.util.Map;
public class DateValueWriter implements ValueWriter {
public boolean supports( String nsUri, String localName, Class c ) {
return Date.class.equals( c );
}
public void writeValue( XmlWriter writer, String nsUri, String prefix, String localName, Object val, String href, Map<String, String> nsPrefixes ) {
if( val == null ) {
writer.writeProperty( prefix, localName );
} else {
Date date = (Date) val;
String s = DateUtils.formatDate( date );
writer.writeProperty( prefix, localName, s );
}
}
public Object parse( String namespaceURI, String localPart, String value ) {
if( value == null || value.length() == 0 ) return null;
Date dt;
try {
dt = DateUtils.parseDate( value );
return dt;
} catch( DateParseException ex ) {
throw new RuntimeException( value, ex );
}
}
}
|
Revert "Update hacking period start"
|
const moment = require('moment');
function getHackathonStartDate() {
return moment('2018-01-20');
}
function getHackathonEndDate() {
return getHackathonStartDate().add(1, 'day');
}
/**
* Returns the earliest graduation date we can accept.
*
* This is due to the restriction imposed by MLH that attendees must either be students or
* graduates who have graduated within the 12 months prior to the event.
* https://mlh.io/faq#i-just-graduated-can-i-still-come-to-an-event
*/
function getEarliestGraduationDateToAccept() {
return getHackathonStartDate().subtract(1, 'year');
}
/**
* Returns the datetime at which the hacking period begins.
*/
function getHackingPeriodStart() {
return moment('2018-01-20T12:00:00Z');
}
/**
* Returns the datetime at which the hacking period ends.
*/
function getHackingPeriodEnd() {
return moment('2018-01-21T12:00:00Z');
}
module.exports = {
getHackathonStartDate,
getHackathonEndDate,
getEarliestGraduationDateToAccept,
getHackingPeriodStart,
getHackingPeriodEnd
};
|
const moment = require('moment');
function getHackathonStartDate() {
return moment('2018-01-20');
}
function getHackathonEndDate() {
return getHackathonStartDate().add(1, 'day');
}
/**
* Returns the earliest graduation date we can accept.
*
* This is due to the restriction imposed by MLH that attendees must either be students or
* graduates who have graduated within the 12 months prior to the event.
* https://mlh.io/faq#i-just-graduated-can-i-still-come-to-an-event
*/
function getEarliestGraduationDateToAccept() {
return getHackathonStartDate().subtract(1, 'year');
}
/**
* Returns the datetime at which the hacking period begins.
*/
function getHackingPeriodStart() {
return moment('2018-01-20T12:15:00Z');
}
/**
* Returns the datetime at which the hacking period ends.
*/
function getHackingPeriodEnd() {
return moment('2018-01-21T12:00:00Z');
}
module.exports = {
getHackathonStartDate,
getHackathonEndDate,
getEarliestGraduationDateToAccept,
getHackingPeriodStart,
getHackingPeriodEnd
};
|
Add Google icon to Google sign in button
Fixes #425
|
'use strict';
angular.module('directive.googlesignin', []).
directive('googleSignin', function (Session, $rootScope) {
return {
restrict: 'E',
template: '<button class="btn btn-block btn-social btn-google-plus btn-lg"><i class="fa fa-google"></i> Sign in with Google</button>',
replace: true,
link: function (scope, element, attrs) {
element.bind("click", function(){
console.log("Sign in with Google has started...");
Session.fetchGoogleLoginUrl().$promise.then(function(data){
window.location.replace(data.Url);
}).then(function(error) {
console.log('fetchGoogleLoginUrl: error = ', error);
});
})
}
};
});
|
'use strict';
angular.module('directive.googlesignin', []).
directive('googleSignin', function (Session, $rootScope) {
return {
restrict: 'E',
template: '<button class="btn btn-block btn-social btn-google-plus btn-lg"><i class="fa fa-google-plus"></i> Sign in with Google</button>',
replace: true,
link: function (scope, element, attrs) {
element.bind("click", function(){
console.log("Sign in with Google has started...");
Session.fetchGoogleLoginUrl().$promise.then(function(data){
window.location.replace(data.Url);
}).then(function(error) {
console.log('fetchGoogleLoginUrl: error = ', error);
});
})
}
};
});
|
Fix race condition in test
|
package io.undertow.servlet.test.streams;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Stuart Douglas
*/
public class ContentLengthCloseFlushServlet extends HttpServlet {
private boolean completed = false;
@Override
protected synchronized void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (completed) {
resp.getWriter().write("OK");
} else {
resp.setContentLength(1);
ServletOutputStream stream = resp.getOutputStream();
stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
stream.flush();
stream.close();
completed = true;
}
}
}
|
package io.undertow.servlet.test.streams;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Stuart Douglas
*/
public class ContentLengthCloseFlushServlet extends HttpServlet {
private boolean completed = false;
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (completed) {
resp.getWriter().write("OK");
} else {
resp.setContentLength(1);
ServletOutputStream stream = resp.getOutputStream();
stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
stream.flush();
stream.close();
completed = true;
}
}
}
|
Update 0.4.2
- Added hashtags
|
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_message = "Voyager I is now {:,} km from Earth. \nVoyager II is now {:,} km from Earth. \n#bot #space #voyager".format(*distance)
api.update_status(voyager_message)
except IndexError:
pass
for data in NEO().flyby_data():
try:
new_neo = "Today's NEO: Object: {} at {}. Estimated diameter: {} - {} km. \n#bot #NEO #asteroids".format(*data)
api.update_status(new_neo)
except IndexError:
api.update_status("No near-Earth objects for today! We're save! ...at least for now... \n#bot #doomsday #NEO #asteroids")
|
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_message = "Voyager I is now {:,} km from Earth. \nVoyager II is now {:,} km from Earth.".format(*distance)
api.update_status(voyager_message)
except IndexError:
pass
for data in NEO().flyby_data():
try:
new_neo = "Today's NEO: Object: {} at {}. Estimated diameter: {} - {} km.".format(*data)
api.update_status(new_neo)
except IndexError:
api.update_status("No near-Earth objects for today! We're save! ...at least for now...")
|
Move appsHandler creation outside of the closure
|
// Package web Cozy Stack API.
//
// Cozy is a personal platform as a service with a focus on data.
package web
import (
"strings"
"github.com/cozy/cozy-stack/pkg/instance"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/labstack/echo"
)
func splitHost(host string) (instanceHost string, appSlug string) {
parts := strings.SplitN(host, ".", 2)
if len(parts) == 2 {
return parts[1], parts[0]
}
return parts[0], ""
}
// Create returns a new web server that will handle that apps routing given the
// host of the request.
func Create(router *echo.Echo, serveApps echo.HandlerFunc) (*echo.Echo, error) {
appsHandler := middlewares.LoadSession(serveApps)
main := echo.New()
main.Any("/*", func(c echo.Context) error {
// TODO(optim): minimize the number of instance requests
if parent, slug := splitHost(c.Request().Host); slug != "" {
if i, err := instance.Get(parent); err == nil {
if serveApps != nil {
c.Set("instance", i)
c.Set("slug", slug)
return appsHandler(c)
}
return nil
}
}
router.ServeHTTP(c.Response(), c.Request())
return nil
})
return main, nil
}
|
// Package web Cozy Stack API.
//
// Cozy is a personal platform as a service with a focus on data.
package web
import (
"strings"
"github.com/cozy/cozy-stack/pkg/instance"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/labstack/echo"
)
func splitHost(host string) (instanceHost string, appSlug string) {
parts := strings.SplitN(host, ".", 2)
if len(parts) == 2 {
return parts[1], parts[0]
}
return parts[0], ""
}
// Create returns a new web server that will handle that apps routing given the
// host of the request.
func Create(router *echo.Echo, serveApps echo.HandlerFunc) (*echo.Echo, error) {
main := echo.New()
main.Any("/*", func(c echo.Context) error {
// TODO(optim): minimize the number of instance requests
if parent, slug := splitHost(c.Request().Host); slug != "" {
if i, err := instance.Get(parent); err == nil {
if serveApps != nil {
c.Set("instance", i)
c.Set("slug", slug)
handler := middlewares.LoadSession(serveApps)
return handler(c)
}
return nil
}
}
router.ServeHTTP(c.Response(), c.Request())
return nil
})
return main, nil
}
|
Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.
|
require('core-js'); // es2015 polyfill
var path = require('path');
var plopBase = require('./modules/plop-base');
var generatorRunner = require('./modules/generator-runner');
/**
* Main node-plop module
*
* @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with
* @returns {object} the node-plop API for the plopfile requested
*/
module.exports = function (plopfilePath) {
const plop = plopBase();
const runner = generatorRunner(plop);
if (plopfilePath) {
plopfilePath = path.resolve(plopfilePath);
plop.setPlopfilePath(plopfilePath);
require(plopfilePath)(plop);
}
/////
// external API for node-plop
//
return {
getGeneratorList: plop.getGeneratorList,
getGenerator: function (genName) {
const genObject = plop.getGenerator(genName);
return Object.assign(genObject, {
runActions: (data) => runner.runGeneratorActions(genObject, data),
runPrompts: () => runner.runGeneratorPrompts(genObject)
});
},
setGenerator: plop.setGenerator,
runActions: runner.runGeneratorActions,
runPrompts: runner.runGeneratorPrompts
};
};
|
require('core-js'); // es2015 polyfill
var path = require('path');
var plopBase = require('./modules/plop-base');
var generatorRunner = require('./modules/generator-runner');
/**
* Main node-plop module
*
* @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with
* @returns {object} the node-plop API for the plopfile requested
*/
module.exports = function (plopfilePath) {
const plop = plopBase();
const runner = generatorRunner(plop);
plopfilePath = path.resolve(plopfilePath);
plop.setPlopfilePath(plopfilePath);
require(plopfilePath)(plop);
/////
// external API for node-plop
//
return {
getGeneratorList: plop.getGeneratorList,
getGenerator: function (genName) {
const genObject = plop.getGenerator(genName);
return Object.assign(genObject, {
runActions: (data) => runner.runGeneratorActions(genObject, data),
runPrompts: () => runner.runGeneratorPrompts(genObject)
});
},
runActions: runner.runGeneratorActions,
runPrompts: runner.runGeneratorPrompts
};
};
|
Make type-hinting in function signature mathc in subclass.
Is this going to be problem for system scripts too?
svn commit r13063
|
<?php
require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';
/**
* @package Site
* @copyright 2006 silverorange
*/
abstract class SiteXMLRPCServerFactory extends SitePageFactory
{
// {{{ public function resolvePage()
public function resolvePage(SiteWebApplication $app, $source)
{
$layout = $this->resolveLayout($app, $source);
$map = $this->getPageMap();
if (isset($map[$source])) {
$class = $map[$source];
$params = array($app, $layout);
$page = $this->instantiatePage($class, $params);
return $page;
}
throw new SiteNotFoundException();
}
// }}}
// {{{ protected function resolveLayout()
protected function resolveLayout($app, $source)
{
return new SiteXMLRPCServerLayout($app);
}
// }}}
}
?>
|
<?php
require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';
/**
* @package Site
* @copyright 2006 silverorange
*/
abstract class SiteXMLRPCServerFactory extends SitePageFactory
{
// {{{ public function resolvePage()
public function resolvePage($app, $source)
{
$layout = $this->resolveLayout($app, $source);
$map = $this->getPageMap();
if (isset($map[$source])) {
$class = $map[$source];
$params = array($app, $layout);
$page = $this->instantiatePage($class, $params);
return $page;
}
throw new SiteNotFoundException();
}
// }}}
// {{{ protected function resolveLayout()
protected function resolveLayout($app, $source)
{
return new SiteXMLRPCServerLayout($app);
}
// }}}
}
?>
|
Fix NaN when input is 0
|
(function() {
'use strict';
var app = angular.module('bonito-filters', []);
/**
* Print large number using prefixes (k, M, G, etc.) to
* keep their size short and to be friendlier to the poor non-robots.
* Adapted from: https://gist.github.com/thomseddon/3511330
*/
app.filter('humanNumber', function() {
return function(input, precision) {
input = parseFloat(input);
if (isNaN(input) || !isFinite(input)) {
return '-';
}
if (input === 0) {
return '0';
}
var negativeSign = '';
if (input < 0) {
input = -input;
negativeSign = '-';
}
if (typeof precision === 'undefined') {
precision = 1;
}
var units = ['', 'k', 'M', 'G', 'T', 'P'],
number = Math.floor(Math.log(input) / Math.log(1000));
return negativeSign + (input / Math.pow(1000, number)).toFixed(precision) + units[number];
};
});
})();
|
(function() {
'use strict';
var app = angular.module('bonito-filters', []);
/**
* Print large number using prefixes (k, M, G, etc.) to
* keep their size short and to be friendlier to the poor non-robots.
* Adapted from: https://gist.github.com/thomseddon/3511330
*/
app.filter('humanNumber', function() {
return function(input, precision) {
input = parseFloat(input);
if (isNaN(input) || !isFinite(input)) {
return '-';
}
var negativeSign = '';
if (input < 0) {
input = -input;
negativeSign = '-';
}
if (typeof precision === 'undefined') {
precision = 1;
}
var units = ['', 'k', 'M', 'G', 'T', 'P'],
number = Math.floor(Math.log(input) / Math.log(1000));
return negativeSign + (input / Math.pow(1000, number)).toFixed(precision) + units[number];
};
});
})();
|
Add test for url types
|
import utils from 'ember-cli-mirage/shorthands/utils';
import Db from 'ember-cli-mirage/db';
import {module, test} from 'qunit';
var request;
module('mirage:shorthands#utils', {
beforeEach: function() {
request = { params: {id: ''} };
}
});
test('it returns a number if it\'s a number', function(assert) {
request.params.id = 2;
assert.equal(utils.getIdForRequest(request), 2, 'it returns a number');
});
test('it returns a number if it\'s a string represented number', function(assert) {
request.params.id = "2";
assert.equal(utils.getIdForRequest(request), 2, 'it returns a number');
});
test('it returns a string it\'s a dasherized number', function(assert) {
request.params.id = "2-1";
assert.equal(utils.getIdForRequest(request), "2-1", 'it returns a number');
});
test('it returns a string if it\'s a string', function(assert) {
request.params.id = "someID";
assert.equal(utils.getIdForRequest(request), "someID", 'it returns a number');
});
test('url without id returns correct type', function (assert) {
var urlWithSlash = '/api/users/?test=true';
var urlWithoutSlash = '/api/users?test=true';
assert.equal(utils.getTypeFromUrl(urlWithSlash), 'user', 'it returns a singular type');
assert.equal(utils.getTypeFromUrl(urlWithoutSlash), 'user', 'it returns a singular type');
});
|
import utils from 'ember-cli-mirage/shorthands/utils';
import Db from 'ember-cli-mirage/db';
import {module, test} from 'qunit';
var request;
module('mirage:shorthands#utils', {
beforeEach: function() {
request = { params: {id: ''} };
}
});
test('it returns a number if it\'s a number', function(assert) {
request.params.id = 2;
assert.equal(utils.getIdForRequest(request), 2, 'it returns a number');
});
test('it returns a number if it\'s a string represented number', function(assert) {
request.params.id = "2";
assert.equal(utils.getIdForRequest(request), 2, 'it returns a number');
});
test('it returns a string it\'s a dasherized number', function(assert) {
request.params.id = "2-1";
assert.equal(utils.getIdForRequest(request), "2-1", 'it returns a number');
});
test('it returns a string if it\'s a string', function(assert) {
request.params.id = "someID";
assert.equal(utils.getIdForRequest(request), "someID", 'it returns a number');
});
|
Fix debug log of target url
|
package main
import (
"flag"
"fmt"
"os"
log "github.com/cihub/seelog"
)
var (
flagSet = flag.NewFlagSet("kraken", flag.ExitOnError)
target = flagSet.String("target", "", "target URL to crawl")
)
func main() {
// Process flags
flagSet.Parse(os.Args[1:])
// Flush logs before exit
defer log.Flush()
// Do we have a target?
if *target == "" {
fmt.Println("Please specify a target domain, eg. kraken -target=\"http://example.com\"")
os.Exit(1)
}
log.Infof("Unleashing the Kraken at %s", *target)
// Use a HTTP based fetcher
fetcher := &HttpFetcher{}
// Crawl the specified site
Crawl(*target, 4, fetcher)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
_, urls, err := fetcher.Fetch(url)
if err != nil {
log.Errorf("Error:", err)
return
}
log.Infof("URLs found: %+v", urls)
}
|
package main
import (
"flag"
"fmt"
"os"
log "github.com/cihub/seelog"
)
var (
flagSet = flag.NewFlagSet("kraken", flag.ExitOnError)
target = flagSet.String("target", "", "target URL to crawl")
)
func main() {
// Process flags
flagSet.Parse(os.Args[1:])
// Flush logs before exit
defer log.Flush()
// Do we have a target?
if *target == "" {
fmt.Println("Please specify a target domain, eg. kraken -target=\"http://example.com\"")
os.Exit(1)
}
log.Infof("Unleashing the Kraken at %s", target)
// Use a HTTP based fetcher
fetcher := &HttpFetcher{}
// Crawl the specified site
Crawl(*target, 4, fetcher)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
_, urls, err := fetcher.Fetch(url)
if err != nil {
log.Errorf("Error:", err)
return
}
log.Infof("URLs found: %+v", urls)
}
|
Define __all__ to restrict global imports
|
from pymongo import MongoClient
from thingy import classproperty, DatabaseThingy
class Thingy(DatabaseThingy):
client = None
_collection = None
@classproperty
def collection(cls):
return cls._collection or cls.table
@classproperty
def collection_name(cls):
return cls.collection.name
@classproperty
def _table(cls):
return cls._collection
@classmethod
def _get_database_from_table(cls, collection):
return collection.database
@classmethod
def _get_table_from_database(cls, database):
return database[cls.table_name]
def connect(*args, **kwargs):
client = MongoClient(*args, **kwargs)
Thingy.client = client
return client
__all__ = ["Thingy", "connect"]
|
from pymongo import MongoClient
from thingy import classproperty, DatabaseThingy
class Thingy(DatabaseThingy):
client = None
_collection = None
@classproperty
def collection(cls):
return cls._collection or cls.table
@classproperty
def collection_name(cls):
return cls.collection.name
@classproperty
def _table(cls):
return cls._collection
@classmethod
def _get_database_from_table(cls, collection):
return collection.database
@classmethod
def _get_table_from_database(cls, database):
return database[cls.table_name]
def connect(*args, **kwargs):
client = MongoClient(*args, **kwargs)
Thingy.client = client
return client
|
Add Tags to SNS::Topic per 2019-11-31 changes
|
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class SubscriptionResource(AWSObject):
resource_type = "AWS::SNS::Subscription"
props = {
'DeliveryPolicy': (dict, False),
'Endpoint': (basestring, False),
'FilterPolicy': (dict, False),
'Protocol': (basestring, True),
'RawMessageDelivery': (boolean, False),
'Region': (basestring, False),
'TopicArn': (basestring, True),
}
class TopicPolicy(AWSObject):
resource_type = "AWS::SNS::TopicPolicy"
props = {
'PolicyDocument': (policytypes, True),
'Topics': (list, True),
}
class Topic(AWSObject):
resource_type = "AWS::SNS::Topic"
props = {
'DisplayName': (basestring, False),
'KmsMasterKeyId': (basestring, False),
'Subscription': ([Subscription], False),
'Tags': (Tags, False),
'TopicName': (basestring, False),
}
|
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class SubscriptionResource(AWSObject):
resource_type = "AWS::SNS::Subscription"
props = {
'DeliveryPolicy': (dict, False),
'Endpoint': (basestring, False),
'FilterPolicy': (dict, False),
'Protocol': (basestring, True),
'RawMessageDelivery': (boolean, False),
'Region': (basestring, False),
'TopicArn': (basestring, True),
}
class TopicPolicy(AWSObject):
resource_type = "AWS::SNS::TopicPolicy"
props = {
'PolicyDocument': (policytypes, True),
'Topics': (list, True),
}
class Topic(AWSObject):
resource_type = "AWS::SNS::Topic"
props = {
'DisplayName': (basestring, False),
'KmsMasterKeyId': (basestring, False),
'Subscription': ([Subscription], False),
'TopicName': (basestring, False),
}
|
Make use of cloudflare 1.0.0.1 by default to resolve addresses
|
// Package dns resolves names to dns records
package dns
import (
"context"
"net"
"github.com/micro/go-micro/network/resolver"
"github.com/miekg/dns"
)
// Resolver is a DNS network resolve
type Resolver struct {
// The resolver address to use
Address string
}
// Resolve assumes ID is a domain name e.g micro.mu
func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
host, port, err := net.SplitHostPort(name)
if err != nil {
host = name
port = "8085"
}
if len(host) == 0 {
host = "localhost"
}
if len(r.Address) == 0 {
r.Address = "1.0.0.1:53"
}
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(host), dns.TypeA)
rec, err := dns.ExchangeContext(context.Background(), m, r.Address)
if err != nil {
return nil, err
}
var records []*resolver.Record
for _, answer := range rec.Answer {
h := answer.Header()
// check record type matches
if h.Rrtype != dns.TypeA {
continue
}
arec, _ := answer.(*dns.A)
addr := arec.A.String()
// join resolved record with port
address := net.JoinHostPort(addr, port)
// append to record set
records = append(records, &resolver.Record{
Address: address,
})
}
return records, nil
}
|
// Package dns resolves names to dns records
package dns
import (
"net"
"github.com/micro/go-micro/network/resolver"
)
// Resolver is a DNS network resolve
type Resolver struct{}
// Resolve assumes ID is a domain name e.g micro.mu
func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
host, port, err := net.SplitHostPort(name)
if err != nil {
host = name
port = "8085"
}
if len(host) == 0 {
host = "localhost"
}
addrs, err := net.LookupHost(host)
if err != nil {
return nil, err
}
records := make([]*resolver.Record, 0, len(addrs))
for _, addr := range addrs {
// join resolved record with port
address := net.JoinHostPort(addr, port)
// append to record set
records = append(records, &resolver.Record{
Address: address,
})
}
return records, nil
}
|
Remove stray non-ASCII character in docstring
|
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on the following personnel involved in a football match:
* Players,
* Managers,
* Match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
|
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on all personnel involved in a football match – players,
managers, and match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
|
Remove TODO -> was done, but forgot to delete it
|
/**
* Created by quasarchimaere on 21.01.2019.
*/
import { get } from "../utils.js";
import {
isProcessingInitialLoad,
isProcessingLogin,
isProcessingLogout,
isProcessingPublish,
isProcessingAcceptTermsOfService,
isProcessingVerifyEmailAddress,
isProcessingResendVerificationEmail,
isProcessingSendAnonymousLinkEmail,
isAnyNeedLoading,
isAnyConnectionLoading,
isAnyMessageLoading,
} from "../process-utils.js";
/**
* Check if anything in the state sub-map of process is currently marked as loading
* @param state (full redux-state)
* @returns true if anything is currently loading
*/
export function isLoading(state) {
const process = get(state, "process");
return (
isProcessingInitialLoad(process) ||
isProcessingLogin(process) ||
isProcessingLogout(process) ||
isProcessingPublish(process) ||
isProcessingAcceptTermsOfService(process) ||
isProcessingVerifyEmailAddress(process) ||
isProcessingResendVerificationEmail(process) ||
isProcessingSendAnonymousLinkEmail(process) ||
isAnyNeedLoading(process) ||
isAnyConnectionLoading(process) ||
isAnyMessageLoading(process)
);
}
|
/**
* Created by quasarchimaere on 21.01.2019.
*/
import { get } from "../utils.js";
import {
isProcessingInitialLoad,
isProcessingLogin,
isProcessingLogout,
isProcessingPublish,
isProcessingAcceptTermsOfService,
isProcessingVerifyEmailAddress,
isProcessingResendVerificationEmail,
isProcessingSendAnonymousLinkEmail,
isAnyNeedLoading,
isAnyConnectionLoading,
isAnyMessageLoading,
} from "../process-utils.js";
/**
* Check if anything in the state sub-map of process is currently marked as loading
* @param state (full redux-state)
* @returns true if anything is currently loading
*/
export function isLoading(state) {
//TODO: Incl. lookup to determine any other process being in loading
const process = get(state, "process");
return (
isProcessingInitialLoad(process) ||
isProcessingLogin(process) ||
isProcessingLogout(process) ||
isProcessingPublish(process) ||
isProcessingAcceptTermsOfService(process) ||
isProcessingVerifyEmailAddress(process) ||
isProcessingResendVerificationEmail(process) ||
isProcessingSendAnonymousLinkEmail(process) ||
isAnyNeedLoading(process) ||
isAnyConnectionLoading(process) ||
isAnyMessageLoading(process)
);
}
|
Add day of the month
|
// @flow
/**
* We want to represent each subs. type as minimally as possible,
* so instead of using strings we just use characters, which lets us
* represent 27 individual subs. using a single character each.
*/
export const UserText = 'a';
export const FullMonth = 'b';
export const PartialMonth = 'c';
export const FullYear = 'd';
export const PartialYear = 'e';
export const DayOfTheWeek = 'f';
export const Hour = 'g';
export const Minutes = 'h';
export const Seconds = 'i';
export const PostOrAnteMeridiem = 'j';
export const Day = 'k';
export const DayOfTheMonth = 'i';
const SubToTypeIdentifierMap: {
[abbreviation: string]: string
} = {
'MMMM': FullMonth,
'MM': PartialMonth,
'YYYY': FullYear,
'YY': PartialYear,
'dddd': DayOfTheWeek,
'DD': DayOfTheMonth,
'Do': Day,
'h': Hour,
'mm': Minutes,
'ss': Seconds,
'a': PostOrAnteMeridiem,
};
export default SubToTypeIdentifierMap;
|
// @flow
/**
* We want to represent each subs. type as minimally as possible,
* so instead of using strings we just use characters, which lets us
* represent 27 individual subs. using a single character each.
*/
export const UserText = 'a';
export const FullMonth = 'b';
export const PartialMonth = 'c';
export const FullYear = 'd';
export const PartialYear = 'e';
export const DayOfTheWeek = 'f';
export const Hour = 'g';
export const Minutes = 'h';
export const Seconds = 'i';
export const PostOrAnteMeridiem = 'j';
export const Day = 'k';
const SubToTypeIdentifierMap: {
[abbreviation: string]: string
} = {
'MMMM': FullMonth,
'MM': PartialMonth,
'YYYY': FullYear,
'YY': PartialYear,
'dddd': DayOfTheWeek,
'Do': Day,
'h': Hour,
'mm': Minutes,
'ss': Seconds,
'a': PostOrAnteMeridiem,
};
export default SubToTypeIdentifierMap;
|
Update caching for User type.
|
<?php namespace ProcessWire\GraphQL\Type;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Cache;
class UserType
{
public static $name = 'User';
public static $description = 'ProcessWire User.';
public static function type()
{
return Cache::type(self::$name, function () {
return new ObjectType([
'name' => self::$name,
'description' => self::$description,
'fields' => [
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => "The user's login name.",
],
'email' => [
'type' => Type::nonNull(Type::string()),
'description' => "The user's email address.",
],
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => "The user's id.",
],
]
]);
});
}
}
|
<?php namespace ProcessWire\GraphQL\Type;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use ProcessWire\GraphQL\Type\Traits\CacheTrait;
class UserType
{
use CacheTrait;
public static $name = 'User';
public static $description = 'ProcessWire User.';
public static function type()
{
return self::cache('default', function () {
return new ObjectType([
'name' => self::$name,
'description' => self::$description,
'fields' => [
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => "The user's login name.",
],
'email' => [
'type' => Type::nonNull(Type::string()),
'description' => "The user's email address.",
],
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => "The user's id.",
],
]
]);
});
}
}
|
Add missing svn:eol-style property to text files.
|
"""
A number of function that enhance IDLE on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
def runningAsOSXApp():
""" Returns True iff running from the IDLE.app bundle on OSX """
return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0])
def addOpenEventSupport(root, flist):
"""
This ensures that the application will respont to open AppleEvents, which
makes is feaseable to use IDLE as the default application for python files.
"""
def doOpenFile(*args):
for fn in args:
flist.open(fn)
# The command below is a hook in aquatk that is called whenever the app
# receives a file open event. The callback can have multiple arguments,
# one for every file that should be opened.
root.createcommand("::tk::mac::OpenDocument", doOpenFile)
def hideTkConsole(root):
root.tk.call('console', 'hide')
def setupApp(root, flist):
"""
Perform setup for the OSX application bundle.
"""
if not runningAsOSXApp(): return
hideTkConsole(root)
addOpenEventSupport(root, flist)
|
"""
A number of function that enhance IDLE on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
def runningAsOSXApp():
""" Returns True iff running from the IDLE.app bundle on OSX """
return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0])
def addOpenEventSupport(root, flist):
"""
This ensures that the application will respont to open AppleEvents, which
makes is feaseable to use IDLE as the default application for python files.
"""
def doOpenFile(*args):
for fn in args:
flist.open(fn)
# The command below is a hook in aquatk that is called whenever the app
# receives a file open event. The callback can have multiple arguments,
# one for every file that should be opened.
root.createcommand("::tk::mac::OpenDocument", doOpenFile)
def hideTkConsole(root):
root.tk.call('console', 'hide')
def setupApp(root, flist):
"""
Perform setup for the OSX application bundle.
"""
if not runningAsOSXApp(): return
hideTkConsole(root)
addOpenEventSupport(root, flist)
|
Configure documentation version for release.
|
"""
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = False
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
doc_version = 'latest'
else:
doc_version = vesper_version.full_version
return 'https://vesper.readthedocs.io/en/' + doc_version + '/'
def _create_tutorial_url():
return _create_documentation_url() + 'tutorial.html'
documentation_url = _create_documentation_url()
tutorial_url = _create_tutorial_url()
source_code_url = 'https://github.com/HaroldMills/Vesper'
|
"""
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = True
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
doc_version = 'latest'
else:
doc_version = vesper_version.full_version
return 'https://vesper.readthedocs.io/en/' + doc_version + '/'
def _create_tutorial_url():
return _create_documentation_url() + 'tutorial.html'
documentation_url = _create_documentation_url()
tutorial_url = _create_tutorial_url()
source_code_url = 'https://github.com/HaroldMills/Vesper'
|
Store Context in atomic Value
|
package floc
import (
"context"
"sync"
"sync/atomic"
)
type flowContext struct {
ctx atomic.Value
mu sync.Mutex
}
func NewContext() Context {
ctx := &flowContext{
ctx: atomic.Value{},
mu: sync.Mutex{},
}
ctx.ctx.Store(context.TODO())
return ctx
}
// Release releases resources.
func (flowCtx flowContext) Release() {
}
// Ctx returns the underlying context.
func (flowCtx flowContext) Ctx() context.Context {
return flowCtx.ctx.Load().(context.Context)
}
// UpdateCtx sets the new underlying context.
func (flowCtx flowContext) UpdateCtx(ctx context.Context) {
flowCtx.mu.Lock()
defer flowCtx.mu.Unlock()
flowCtx.ctx.Store(ctx)
}
// Value returns the value associated with this context for key,
// or nil if no value is associated with key.
func (flowCtx flowContext) Value(key interface{}) (value interface{}) {
ctx := flowCtx.ctx.Load().(context.Context)
return ctx.Value(key)
}
// Create a new context with value and make it the current.
func (flowCtx flowContext) AddValue(key, value interface{}) {
flowCtx.mu.Lock()
defer flowCtx.mu.Unlock()
oldCtx := flowCtx.ctx.Load().(context.Context)
newCtx := context.WithValue(oldCtx, key, value)
flowCtx.ctx.Store(newCtx)
}
|
package floc
import (
"context"
"sync"
)
type flowContext struct {
context.Context
sync.RWMutex
}
func NewContext() Context {
return &flowContext{
Context: context.TODO(),
RWMutex: sync.RWMutex{},
}
}
// Release releases resources.
func (flowCtx flowContext) Release() {
}
// Ctx returns the underlying context.
func (flowCtx flowContext) Ctx() context.Context {
flowCtx.RLock()
defer flowCtx.RUnlock()
return flowCtx.Context
}
// UpdateCtx sets the new underlying context.
func (flowCtx flowContext) UpdateCtx(ctx context.Context) {
flowCtx.Lock()
defer flowCtx.Unlock()
flowCtx.Context = ctx
}
// Value returns the value associated with this context for key,
// or nil if no value is associated with key.
func (flowCtx flowContext) Value(key interface{}) (value interface{}) {
flowCtx.RLock()
defer flowCtx.RUnlock()
return flowCtx.Context.Value(key)
}
// Create a new context with value and make it the current.
func (flowCtx flowContext) AddValue(key, value interface{}) {
flowCtx.Lock()
defer flowCtx.Unlock()
newCtx := context.WithValue(flowCtx.Context, key, value)
flowCtx.Context = newCtx
}
|
Move along, nothing to see here.
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Template </title>
<link rel="shortcut icon" href="/includes/img/kp.ico">
<link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
<link href="/includes/css/style.css" rel="stylesheet">
<link href="/includes/js/konami.js">
<script>
var easter_egg = new Konami(function() { alert('Konami code!')});
easter_egg.load();
</script>
</head>
<body>
<?php include 'includes/php/header.php'; ?>
<div class="container">
<div class="row">
<h1> Page content </h1>
<p> This be your page content... </p>
</div>
</div>
<?php include 'includes/php/footer.php'; ?>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Template </title>
<link rel="shortcut icon" href="/includes/img/kp.ico">
<link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
<link href="/includes/css/style.css" rel="stylesheet">
</head>
<body>
<?php include 'includes/php/header.php'; ?>
<div class="container">
<div class="row">
<h1> Page content </h1>
<p> This be your page content... </p>
</div>
</div>
<?php include 'includes/php/footer.php'; ?>
</body>
</html>
|
Fix typos in urlconf registry
|
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a urlconf for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested urlconf was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
|
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a widget for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested widget was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
|
Add `max_length` to char fields
|
from django.db import models
class TestUser0(models.Model):
username = models.CharField(max_length=255)
test_field = models.CharField('My title', max_length=255)
class Meta:
app_label = 'controlcenter'
def foo(self):
return 'original foo value'
foo.short_description = 'original foo label'
def bar(self):
return 'original bar value'
bar.short_description = 'original bar label'
def baz(self):
pass
baz.short_description = ''
def egg(self):
return 'original egg value'
class TestUser1(models.Model):
primary = models.AutoField(primary_key=True)
username = models.CharField(max_length=255)
class Meta:
app_label = 'controlcenter'
|
from django.db import models
class TestUser0(models.Model):
username = models.CharField()
test_field = models.CharField('My title')
class Meta:
app_label = 'controlcenter'
def foo(self):
return 'original foo value'
foo.short_description = 'original foo label'
def bar(self):
return 'original bar value'
bar.short_description = 'original bar label'
def baz(self):
pass
baz.short_description = ''
def egg(self):
return 'original egg value'
class TestUser1(models.Model):
primary = models.AutoField(primary_key=True)
username = models.CharField()
class Meta:
app_label = 'controlcenter'
|
Add schema constraints + documentation
|
<?php
return [
'specificationBuildMode' => env('OPARL_BUILD_MODE', 'native'),
/**
* These constraints are used for the site-internal functions like
* displaying the specification's web view or providing the
* validation service.
*/
'versions' => [
'specification' => [
'stable' => '~1.0',
'latest' => 'master',
],
'liboparl' => [
'stable' => '~0.2',
'latest' => 'master'
],
'validator' => [
'stable' => '~0.1',
'latest' => 'master'
]
],
/**
* These constraints are used to provide downloads for specified component
*/
'downloads' => [
'specification' => [
'~1.0',
'master'
]
],
/**
* Mapping of Schema endpoints to version constraints of the specification repository
*/
'schema' => [
'1.0' => '~1.0',
'1.1' => 'master',
'master' => 'master'
]
];
|
<?php
return [
'specificationBuildMode' => env('OPARL_BUILD_MODE', 'native'),
'versions' => [
'specification' => [
'stable' => '~1.0',
'latest' => 'master',
],
'liboparl' => [
'stable' => '~0.2',
'latest' => 'master'
],
'validator' => [
'stable' => '~0.1',
'latest' => 'master'
]
],
'downloads' => [
'specification' => [
'~1.0',
'master'
]
]
];
|
Replace list-to-set cast with normal set literal
Don't know who did this but he did wrong, yo.
|
# Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Settings.Models.SettingVisibilityHandler import SettingVisibilityHandler
class MaterialSettingsVisibilityHandler(SettingVisibilityHandler):
def __init__(self, parent = None, *args, **kwargs):
super().__init__(parent = parent, *args, **kwargs)
material_settings = {
"default_material_print_temperature",
"material_bed_temperature",
"material_standby_temperature",
"cool_fan_speed",
"retraction_amount",
"retraction_speed",
}
self.setVisible(material_settings)
|
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Settings.Models.SettingVisibilityHandler import SettingVisibilityHandler
class MaterialSettingsVisibilityHandler(SettingVisibilityHandler):
def __init__(self, parent = None, *args, **kwargs):
super().__init__(parent = parent, *args, **kwargs)
material_settings = set([
"default_material_print_temperature",
"material_bed_temperature",
"material_standby_temperature",
"cool_fan_speed",
"retraction_amount",
"retraction_speed",
])
self.setVisible(material_settings)
|
Use ApOkHttpUrlLoader for all images
Probably got broken during my Glide update.
When using append or prepend, Glide uses the next one in the chain if ApOkHttpUrlLoader blocks
|
package de.danoeh.antennapod.core.glide;
import android.content.Context;
import android.support.annotation.NonNull;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.AppGlideModule;
import java.io.InputStream;
import com.bumptech.glide.request.RequestOptions;
import de.danoeh.antennapod.core.preferences.UserPreferences;
/**
* {@see com.bumptech.glide.integration.okhttp.OkHttpGlideModule}
*/
@GlideModule
public class ApGlideModule extends AppGlideModule {
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_ARGB_8888));
builder.setDiskCache(new InternalCacheDiskCacheFactory(context,
UserPreferences.getImageCacheSize()));
}
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
registry.replace(String.class, InputStream.class, new ApOkHttpUrlLoader.Factory());
}
}
|
package de.danoeh.antennapod.core.glide;
import android.content.Context;
import android.support.annotation.NonNull;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.AppGlideModule;
import java.io.InputStream;
import com.bumptech.glide.request.RequestOptions;
import de.danoeh.antennapod.core.preferences.UserPreferences;
/**
* {@see com.bumptech.glide.integration.okhttp.OkHttpGlideModule}
*/
@GlideModule
public class ApGlideModule extends AppGlideModule {
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_ARGB_8888));
builder.setDiskCache(new InternalCacheDiskCacheFactory(context,
UserPreferences.getImageCacheSize()));
}
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
registry.append(String.class, InputStream.class, new ApOkHttpUrlLoader.Factory());
}
}
|
Expand description to include single-element array behavior
|
import React from 'react';
const ReactUil = {
/**
* Wrap React elements
*
* If elements is an array with a single element, it will not be wrapped
* unless alwaysWrap is true.
*
* @param {Array.<ReactElement>|ReactElement} elements
* @param {function|String} wrapper component
* @param {boolean} [alwaysWrap]
*
* @returns {ReactElement} wrapped react elements
*/
wrapElements(elements, wrapper = 'div', alwaysWrap = false) {
if (elements == null && !alwaysWrap) {
return null;
}
if (Array.isArray(elements) && elements.length === 1 && !alwaysWrap) {
return elements[0];
}
if (React.isValidElement(elements) && !alwaysWrap) {
return elements;
}
return React.createElement(wrapper, null, elements);
}
};
module.exports = ReactUil;
|
import React from 'react';
const ReactUil = {
/**
* Wrap React elements
*
* @param {Array.<ReactElement>|ReactElement} elements
* @param {function|String} wrapper component
* @param {boolean} [alwaysWrap]
*
* @returns {ReactElement} wrapped react elements
*/
wrapElements(elements, wrapper = 'div', alwaysWrap = false) {
if (elements == null && !alwaysWrap) {
return null;
}
if (Array.isArray(elements) && elements.length === 1 && !alwaysWrap) {
return elements[0];
}
if (React.isValidElement(elements) && !alwaysWrap) {
return elements;
}
return React.createElement(wrapper, null, elements);
}
};
module.exports = ReactUil;
|
Fix for session handler overriding
This fixes a bug where setting a session.handler_id in your symfony
configuration didn't work, due to this bundle overriding it.
The setting is now only overridden if the handler_id is not null.
|
<?php
namespace Lsw\MemcacheBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* EnableSessionSupport is a compiler pass to set the session handler.
* Based on Emagister\MemcachedBundle by Christian Soronellas
*/
class EnableSessionSupport implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
// If there is no active session support, return
if (!$container->hasAlias('session.storage')) {
return;
}
// If the memcache.session_handler service is loaded set the alias
if ($container->hasDefinition('memcache.session_handler')) {
if (!$container->hasAlias('session.handler')) {
$container->setAlias('session.handler', 'memcache.session_handler');
}
}
}
}
|
<?php
namespace Lsw\MemcacheBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* EnableSessionSupport is a compiler pass to set the session handler.
* Based on Emagister\MemcachedBundle by Christian Soronellas
*/
class EnableSessionSupport implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
// If there is no active session support, return
if (!$container->hasAlias('session.storage')) {
return;
}
// If the memcache.session_handler service is loaded set the alias
if ($container->hasDefinition('memcache.session_handler')) {
$container->setAlias('session.handler', 'memcache.session_handler');
}
}
}
|
Fix undefined cookies on server
|
import React from "react";
import PropTypes from "prop-types";
import hoistStatics from "hoist-non-react-statics";
import { Cookies } from "react-cookie";
import getDisplayName from "../utils/getDisplayName";
import { NEXT_STATICS } from "../constants/Statics";
export default Page => {
class WithCookies extends React.Component {
static displayName = getDisplayName("WithCookies", Page);
static propTypes = {
cookies: PropTypes.oneOfType([
PropTypes.shape({
cookies: PropTypes.objectOf(PropTypes.string)
}),
PropTypes.instanceOf(Cookies)
]).isRequired
};
static async getInitialProps(ctx) {
const cookies = (ctx.req && ctx.req.universalCookies) || new Cookies();
const props =
Page.getInitialProps &&
(await Page.getInitialProps({ ...ctx, cookies }));
return {
...props,
cookies
};
}
constructor(props) {
super(props);
this.cookies = process.browser ? new Cookies() : props.cookies;
}
render() {
const { ...props } = this.props;
delete props.cookies;
return <Page {...props} cookies={this.cookies} />;
}
}
return hoistStatics(WithCookies, Page, NEXT_STATICS);
};
|
import React from "react";
import PropTypes from "prop-types";
import hoistStatics from "hoist-non-react-statics";
import { Cookies } from "react-cookie";
import getDisplayName from "../utils/getDisplayName";
import { NEXT_STATICS } from "../constants/Statics";
export default Page => {
class WithCookies extends React.Component {
static displayName = getDisplayName("WithCookies", Page);
static propTypes = {
cookies: PropTypes.oneOfType([
PropTypes.shape({
cookies: PropTypes.objectOf(PropTypes.string)
}),
PropTypes.instanceOf(Cookies)
]).isRequired
};
static async getInitialProps(ctx) {
const cookies = ctx.req ? ctx.req.universalCookies : new Cookies();
const props =
Page.getInitialProps &&
(await Page.getInitialProps({ ...ctx, cookies }));
return {
...props,
cookies
};
}
constructor(props) {
super(props);
this.cookies = process.browser ? new Cookies() : props.cookies;
}
render() {
const { ...props } = this.props;
delete props.cookies;
return <Page {...props} cookies={this.cookies} />;
}
}
return hoistStatics(WithCookies, Page, NEXT_STATICS);
};
|
Remove tappable by default mixin
|
// This is a function that decorates React's createClass.
// It's used only internally in this library,
// but could be used externally eventually.
// See the mixins for more information on what this does.
var UI = require('reapp-ui');
var Component = require('reapp-component')();
var React = require('react');
var Identified = require('./mixins/Identified');
var Styled = require('./mixins/Styled');
var Classed = require('./mixins/Classed');
var Animated = require('./mixins/Animated');
var ComponentProps = require('./mixins/ComponentProps');
Component.addDecorator(spec => {
spec.mixins = [].concat(
// unique ids and classes
Identified,
Classed(spec.name),
// constants
{ getConstant: UI.getConstants },
// styles and animations
Styled(spec.name, UI.getStyles),
Animated(UI.getAnimations),
// any component-defined mixins
spec.mixins || [],
// componentProps is the meat of a UI component
// when used, it will handle: id, ref, className, styles, animations
ComponentProps
);
// set UI displayname to help with debugging
spec.displayName = `UI-${spec.name}`;
// allow checking for 'isName' on all components
// spec.statics = spec.statics || {};
// spec[`is${spec.name}`] = true;
return React.createClass(spec);
});
module.exports = Component;
|
// This is a function that decorates React's createClass.
// It's used only internally in this library,
// but could be used externally eventually.
// See the mixins for more information on what this does.
var UI = require('reapp-ui');
var Component = require('reapp-component')();
var React = require('react');
var Identified = require('./mixins/Identified');
var Styled = require('./mixins/Styled');
var Classed = require('./mixins/Classed');
var Animated = require('./mixins/Animated');
var ComponentProps = require('./mixins/ComponentProps');
var Tappable = require('./mixins/Tappable');
Component.addDecorator(spec => {
spec.mixins = [].concat(
// unique ids and classes
Identified,
Classed(spec.name),
// constants
{ getConstant: UI.getConstants },
// styles and animations
Styled(spec.name, UI.getStyles),
Animated(UI.getAnimations),
// any component-defined mixins
spec.mixins || [],
Tappable,
// componentProps is the meat of a UI component
// when used, it will handle: id, ref, className, styles, animations
ComponentProps
);
// set UI displayname to help with debugging
spec.displayName = `UI-${spec.name}`;
// allow checking for 'isName' on all components
// spec.statics = spec.statics || {};
// spec[`is${spec.name}`] = true;
return React.createClass(spec);
});
module.exports = Component;
|
Make specific cache instance for page cache
|
var P = require('bluebird');
var url = require('url');
var fetch = require('node-fetch');
fetch.Promise = P;
var Cache = require('../lib/background-refresh-cache');
var debug = require('debuglog')('newww:cms');
var pageCache = new Cache('content', fetchPage, process.env.CMS_CACHE_TIME || 30 * 60);
function fetchPage(slug) {
var pageRoot = url.resolve(process.env.CMS_API, 'pages/');
var pageUrl = url.resolve(pageRoot, slug);
debug("Fetching %j for %j", pageUrl, slug);
return fetch(pageUrl).then(function(res) {
if (res.status >= 300) {
var err = new Error("Bad status: " + res.status);
err.statusCode = res.status;
throw err;
}
return res.json()
}).then(function(page) {
debug("Got content for %j: %j", slug, page);
if (typeof page != 'object' || !page.id || !page.html || !page.title) {
throw new Error("Invalid page returned");
}
return page;
}).then(function addMarker(json) {
json.fetchedAt = Date.now();
return json;
});
}
module.exports = {
getPage: function getPage(slug) {
return pageCache.get(slug);
}
};
|
var P = require('bluebird');
var url = require('url');
var fetch = require('node-fetch');
fetch.Promise = P;
var Cache = require('../lib/background-refresh-cache');
var debug = require('debuglog')('newww:cms');
var cache = new Cache('content', fetchPage, process.env.CMS_CACHE_TIME || 30 * 60);
function fetchPage(slug) {
var pageRoot = url.resolve(process.env.CMS_API, 'pages/');
var pageUrl = url.resolve(pageRoot, slug);
debug("Fetching %j for %j", pageUrl, slug);
return fetch(pageUrl).then(function(res) {
if (res.status >= 300) {
var err = new Error("Bad status: " + res.status);
err.statusCode = res.status;
throw err;
}
return res.json()
}).then(function(page) {
debug("Got content for %j: %j", slug, page);
if (typeof page != 'object' || !page.id || !page.html || !page.title) {
throw new Error("Invalid page returned");
}
return page;
}).then(function addMarker(json) {
json.fetchedAt = Date.now();
return json;
});
}
module.exports = {
getPage: function getPage(slug) {
return cache.get(slug);
}
};
|
Update package configuration, pt. ii
|
from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
install_requires=[
'tangled>=0.1.dev0',
'SQLAlchemy',
],
extras_require={
'dev': [
'tangled[dev]',
],
},
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
)
|
from setuptools import setup, find_packages
setup(
name='tangled.sqlalchemy',
version='0.1.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=find_packages(),
install_requires=(
'tangled>=0.1.dev0',
'SQLAlchemy',
),
extras_require={
'dev': (
'tangled[dev]',
),
},
classifiers=(
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
),
)
|
Add Dockstore CLI Release URL config.
|
'use strict';
/**
* @ngdoc service
* @name dockstore.ui.WebService
* @description
* # WebService
* Constant in the dockstore.ui.
*/
angular.module('dockstore.ui')
.constant('WebService', {
API_URI: 'http://www.dockstore.org:8080',
API_URI_DEBUG: 'http://www.dockstore.org/tests/dummy-data',
GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
GITHUB_CLIENT_ID: '7ad54aa857c6503013ea',
GITHUB_REDIRECT_URI: 'http://www.dockstore.org/%23/login',
GITHUB_SCOPE: 'read:org',
QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
QUAYIO_CLIENT_ID: 'X5HST9M57O6A57GZFX6T',
QUAYIO_REDIRECT_URI: 'http://www.dockstore.org/%23/onboarding',
QUAYIO_SCOPE: 'repo:read,user:read',
DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/releases/download/0.0.4/dockstore'
});
|
'use strict';
/**
* @ngdoc service
* @name dockstore.ui.WebService
* @description
* # WebService
* Constant in the dockstore.ui.
*/
angular.module('dockstore.ui')
.constant('WebService', {
API_URI: 'http://www.dockstore.org:8080',
API_URI_DEBUG: 'http://www.dockstore.org/tests/dummy-data',
GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
GITHUB_CLIENT_ID: '7ad54aa857c6503013ea',
GITHUB_REDIRECT_URI: 'http://www.dockstore.org/%23/login',
GITHUB_SCOPE: 'read:org',
QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
QUAYIO_CLIENT_ID: 'X5HST9M57O6A57GZFX6T',
QUAYIO_REDIRECT_URI: 'http://www.dockstore.org/%23/onboarding',
QUAYIO_SCOPE: 'repo:read,user:read'
});
|
Change path to install file systems - should not be created inside non-existant folder.
|
package make
import (
"fmt"
log "github.com/Sirupsen/logrus"
"os"
"strings"
"time"
)
// InstallFileSystem installs a basic private file system for any given input.
func (Site *Site) InstallFileSystem(DirectoryPath string) {
// Test the file system, create it if it doesn't exist!
dirPath := fmt.Sprintf(strings.Join([]string{Site.Path, Site.TimeStampGet(), "sites", Site.Name, DirectoryPath}, "/"))
_, err := os.Stat(dirPath + "/" + dirPath)
if err != nil {
dirErr := os.MkdirAll(dirPath, 0755)
if dirErr != nil {
log.Errorln("Couldn't create file system at", dirPath, dirErr)
} else {
log.Infoln("Created file system at", dirPath)
time.Sleep(1 * time.Second)
}
}
}
|
package make
import (
"fmt"
log "github.com/Sirupsen/logrus"
"os"
"strings"
"time"
)
// InstallFileSystem installs a basic private file system for any given input.
func (Site *Site) InstallFileSystem(DirectoryPath string) {
// Test the file system, create it if it doesn't exist!
dirPath := fmt.Sprintf(strings.Join([]string{Site.Path, Site.Domain + ".latest", "sites", Site.Name, DirectoryPath}, "/"))
_, err := os.Stat(dirPath + "/" + dirPath)
if err != nil {
dirErr := os.MkdirAll(dirPath, 0755)
if dirErr != nil {
log.Errorln("Couldn't create file system at", dirPath, dirErr)
} else {
log.Infoln("Created file system at", dirPath)
time.Sleep(1 * time.Second)
}
}
}
|
Fix moment.js not found in production
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// Used internally in the chat.
//= require jquery/jquery.autosize
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
// Use for XMPP in the chat.
//= require strophe
//= require i18n/translations
// Moment.js for dates
//= require moment
//= require moment/pt-br
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
// TODO: remove this dependecy, this is only used in attachments now and
// can be easily replaced by standard jquery methods.
//= require jquery/jquery.livequery
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// Used internally in the chat.
//= require jquery/jquery.autosize
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
// Use for XMPP in the chat.
//= require strophe
//= require i18n/translations
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
// Moment.js for dates
//= require moment
//= require moment/pt-br
// TODO: remove this dependecy, this is only used in attachments now and
// can be easily replaced by standard jquery methods.
//= require jquery/jquery.livequery
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
Update data-channels example to put messages in DOM instead of console
|
/* eslint-env browser */
let pc = new RTCPeerConnection()
let log = msg => {
document.getElementById('logs').innerHTML += msg + '<br>'
}
let sendChannel = pc.createDataChannel('foo')
sendChannel.onclose = () => console.log('sendChannel has closed')
sendChannel.onopen = () => console.log('sendChannel has opened')
sendChannel.onmessage = e => log(`sendChannel got '${e.data}'`)
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
pc.onnegotiationneeded = e =>
pc.createOffer({ }).then(d => {
document.getElementById('localSessionDescription').value = btoa(d.sdp)
return pc.setLocalDescription(d)
}).catch(log)
window.sendMessage = () => {
let message = document.getElementById('message').value
if (message === '') {
return alert('Message must not be empty')
}
sendChannel.send(message)
}
window.startSession = () => {
let sd = document.getElementById('remoteSessionDescription').value
if (sd === '') {
return alert('Session Description must not be empty')
}
try {
pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: atob(sd)}))
} catch (e) {
alert(e)
}
}
|
/* eslint-env browser */
let pc = new RTCPeerConnection()
let log = msg => {
document.getElementById('logs').innerHTML += msg + '<br>'
}
let sendChannel = pc.createDataChannel('foo')
sendChannel.onclose = () => console.log('sendChannel has closed')
sendChannel.onopen = () => console.log('sendChannel has opened')
sendChannel.onmessage = e => console.log(`sendChannel got ${e.data}`)
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
pc.onnegotiationneeded = e =>
pc.createOffer({ }).then(d => {
document.getElementById('localSessionDescription').value = btoa(d.sdp)
return pc.setLocalDescription(d)
}).catch(log)
window.sendMessage = () => {
let message = document.getElementById('message').value
if (message === '') {
return alert('Message must not be empty')
}
sendChannel.send(message)
}
window.startSession = () => {
let sd = document.getElementById('remoteSessionDescription').value
if (sd === '') {
return alert('Session Description must not be empty')
}
try {
pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: atob(sd)}))
} catch (e) {
alert(e)
}
}
|
Use built-in _format to enable xml output
|
<?php
namespace Kunstmaan\SitemapBundle\Controller;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SitemapController extends Controller
{
/**
* Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
*
* @Route("/sitemap.{_format}", name="KunstmaanSitemapBundle_sitemap", requirements={"_format" = "xml"})
* @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
*
* @param $mode
*
* @return array
*/
public function sitemapAction()
{
$em = $this->getDoctrine()->getManager();
$locale = $this->getRequest()->getLocale();
$securityContext = $this->container->get('security.context');
$aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
$nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);
return array(
'nodemenu' => $nodeMenu,
);
}
}
|
<?php
namespace Kunstmaan\SitemapBundle\Controller;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SitemapController extends Controller
{
/**
* Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
*
* @Route("/sitemap.{mode}", name="KunstmaanSitemapBundle_sitemap")
* @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
*
* @param $mode
*
* @return array
*/
public function sitemapAction($mode)
{
$em = $this->getDoctrine()->getManager();
$locale = $this->getRequest()->getLocale();
$securityContext = $this->container->get('security.context');
$aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
$nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);
return array(
'nodemenu' => $nodeMenu,
);
}
}
|
Add the class and version property
|
package net.hamnaberg.jsonstat;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by hadrien on 07/06/16.
*
* @see <a href="https://json-stat.org/format/#version">json-stat.org/format/#version</a>
*/
public class JsonStat {
private final Version version;
private final Class clazz;
public JsonStat(Version version, Class clazz) {
this.version = version;
this.clazz = clazz;
}
public String getVersion() {
return version.getTag();
}
@JsonProperty("class")
public String getClazz() {
return clazz.toString().toLowerCase();
}
public enum Version {
ONE("1.0"), TWO("2.0");
private final String tag;
Version(final String tag) {
this.tag = tag;
}
String getTag() {
return this.tag;
}
}
public enum Class {
DATASET,
DIMENSION,
COLLECTION
}
}
|
package net.hamnaberg.jsonstat;
/**
* Created by hadrien on 07/06/16.
*
* @see <a href="https://json-stat.org/format/#version">json-stat.org/format/#version</a>
*/
public class JsonStat {
private final Version version;
private final Class clazz;
public JsonStat(Version version, Class clazz) {
this.version = version;
this.clazz = clazz;
}
public enum Version {
ONE("1.0"), TWO("2.0");
private final String tag;
Version(final String tag) {
this.tag = tag;
}
String getTag() {
return this.tag;
}
}
public enum Class {
DATASET,
DIMENSION,
COLLECTION
}
}
|
Make sure we don't include Collection when pulling collections from a module
|
import types
from version import __version__
from .model import Model
from .collection import Collection
class Hammock(object):
def __init__(self, collections=(), authenticators=(), storage=None):
if type(collections) == types.ModuleType:
collection_classes = []
for k,v in collections.__dict__.items():
try:
if issubclass(v, Collection) and v != Collection:
collection_classes.append(v)
except TypeError:
pass
else:
collection_classes = collections
entities = set()
self.collections_by_class_name = {}
for collection_cls in collection_classes:
entities.add(collection_cls.entity)
collection = collection_cls(storage)
self.collections_by_class_name[collection_cls.__name__] = collection
setattr(self, collection_cls.plural_name, collection)
self.model = Model(storage, entities)
for collection in self.collections_by_class_name.values():
new_links = {}
if collection.links:
for k, v in collection.links.items():
if not isinstance(v, basestring):
v = v.__name__
referenced_collection = self.collections_by_class_name.get(v)
new_links[k] = referenced_collection
collection.links = new_links
|
import types
from version import __version__
from .model import Model
from .collection import Collection
class Hammock(object):
def __init__(self, collections=(), authenticators=(), storage=None):
if type(collections) == types.ModuleType:
collection_classes = []
for k,v in collections.__dict__.items():
try:
if issubclass(v, Collection):
collection_classes.append(v)
except TypeError:
pass
else:
collection_classes = collections
entities = set()
self.collections_by_class_name = {}
for collection_cls in collection_classes:
entities.add(collection_cls.entity)
collection = collection_cls(storage)
self.collections_by_class_name[collection_cls.__name__] = collection
setattr(self, collection_cls.plural_name, collection)
self.model = Model(storage, entities)
for collection in self.collections_by_class_name.values():
new_links = {}
if collection.links:
for k, v in collection.links.items():
if not isinstance(v, basestring):
v = v.__name__
referenced_collection = self.collections_by_class_name.get(v)
new_links[k] = referenced_collection
collection.links = new_links
|
Set app_path to src directory
|
<?php
namespace OpenDominion;
use Illuminate\Foundation\Application as LaravelApplication;
class Application extends LaravelApplication
{
protected $appPath;
public function __construct($basePath)
{
parent::__construct($basePath);
$this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app');
$this->bindPathsInContainer();
}
public function path()
{
return ($this->basePath . DIRECTORY_SEPARATOR . 'src');
}
public function bootstrapPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap');
}
public function configPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'config');
}
public function databasePath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'database');
}
public function langPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang');
}
public function storagePath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'storage');
}
}
|
<?php
namespace OpenDominion;
use Illuminate\Foundation\Application as LaravelApplication;
class Application extends LaravelApplication
{
protected $appPath;
public function __construct($basePath)
{
parent::__construct($basePath);
$this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app');
$this->bindPathsInContainer();
}
public function bootstrapPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap');
}
public function configPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'config');
}
public function databasePath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'database');
}
public function langPath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang');
}
public function storagePath()
{
return ($this->appPath . DIRECTORY_SEPARATOR . 'storage');
}
}
|
Add collision_scene_distances to set of tests to run
|
#!/usr/bin/env python
# This is a workaround for liburdf.so throwing an exception and killing
# the process on exit in ROS Indigo.
import subprocess
import os
import sys
cpptests = ['test_initializers',
'test_maps'
]
pytests = ['core.py',
'valkyrie_com.py',
'valkyrie_collision_check_fcl_default.py',
'valkyrie_collision_check_fcl_latest.py',
'collision_scene_distances.py'
]
for test in cpptests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if process.wait()!=0:
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
for test in pytests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if output[-1][0:11]!='>>SUCCESS<<':
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
|
#!/usr/bin/env python
# This is a workaround for liburdf.so throwing an exception and killing
# the process on exit in ROS Indigo.
import subprocess
import os
import sys
cpptests = ['test_initializers',
'test_maps'
]
pytests = ['core.py',
'valkyrie_com.py',
'valkyrie_collision_check_fcl_default.py',
'valkyrie_collision_check_fcl_latest.py'
]
for test in cpptests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if process.wait()!=0:
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
for test in pytests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if output[-1][0:11]!='>>SUCCESS<<':
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
|
Fix display of return type.
|
'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function CrossLinkComponent() {
Component.apply(this, arguments);
}
CrossLinkComponent.Prototype = function() {
this.render = function() {
var doc = this.context.doc;
var nodeId = this.props.nodeId;
var el;
if (nodeId && doc.get(nodeId)) {
el = $$('a').addClass('sc-cross-link')
.attr({
href: '#contextId=toc,nodeId='+nodeId,
"data-type": 'cross-link',
"data-node-id": nodeId
});
} else {
el = $$('span');
}
if (this.props.children.length > 0) {
el.append(this.props.children);
} else {
el.append(nodeId);
}
return el;
};
};
Component.extend(CrossLinkComponent);
module.exports = CrossLinkComponent;
|
'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function CrossLinkComponent() {
Component.apply(this, arguments);
}
CrossLinkComponent.Prototype = function() {
this.render = function() {
var doc = this.context.doc;
var nodeId = this.props.nodeId;
var el;
if (nodeId && doc.get(nodeId)) {
el = $$('a').addClass('sc-cross-link')
.attr({
href: '#contextId=toc,nodeId='+nodeId,
"data-type": 'cross-link',
"data-node-id": nodeId
});
} else {
el = $$('span');
}
if (this.props.children) {
el.append(this.props.children);
} else {
el.append(nodeId);
}
return el;
};
};
Component.extend(CrossLinkComponent);
module.exports = CrossLinkComponent;
|
Add success method for custom message in data.
|
package com.royalrangers.utils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.royalrangers.bean.ResponseResult;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
public class ResponseBuilder {
public static ResponseResult success() {
return new ResponseResult(true, new EmptyJsonResponse());
}
public static ResponseResult success(Object data) {
return new ResponseResult(true, data);
}
public static ResponseResult success(String message) {
return new ResponseResult(true, new ResponseMessage(message));
}
public static ResponseResult success(String key, String value) {
Map<String, String> data = new HashMap<>();
data.put(key, value);
return new ResponseResult(true, data);
}
public static ResponseResult fail() {
return new ResponseResult(false, new EmptyJsonResponse());
}
public static ResponseResult fail(String message) {
return new ResponseResult(false, new ResponseMessage(message));
}
@JsonSerialize
private static class EmptyJsonResponse { }
@Getter
@JsonSerialize
private static class ResponseMessage{
private String message;
ResponseMessage (String message) {
this.message = message;
}
}
}
|
package com.royalrangers.utils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.royalrangers.bean.ResponseResult;
import lombok.Getter;
public class ResponseBuilder {
public static ResponseResult success() {
return new ResponseResult(true, new EmptyJsonResponse());
}
public static ResponseResult success(Object data) {
return new ResponseResult(true, data);
}
public static ResponseResult success(String message) {
return new ResponseResult(true, new ResponseMessage(message));
}
public static ResponseResult fail() {
return new ResponseResult(false, new EmptyJsonResponse());
}
public static ResponseResult fail(String message) {
return new ResponseResult(false, new ResponseMessage(message));
}
@JsonSerialize
private static class EmptyJsonResponse { }
@Getter
@JsonSerialize
private static class ResponseMessage{
private String message;
ResponseMessage (String message) {
this.message = message;
}
}
}
|
Remove Tonic namespace restriction from autoloader so as to allow people to hit the ground running without having to configure their own autoloader.
|
<?php
namespace Tonic;
/**
* Autoload
*/
class Autoloader
{
/**
* Handles autoloading of classes
* @param string $className Name of the class to load
*/
public static function autoload($className)
{
$fileName = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR;
$namespace = '';
if (false !== ($lastNsPos = strripos($className, '\\'))) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
}
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register(array(new Autoloader, 'autoload'));
|
<?php
namespace Tonic;
/**
* Autoload
*/
class Autoloader
{
/**
* Handles autoloading of classes
* @param string $className Name of the class to load
*/
public static function autoload($className)
{
if ('Tonic\\' === substr($className, 0, strlen('Tonic\\'))) {
$fileName = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR;
$namespace = '';
if (false !== ($lastNsPos = strripos($className, '\\'))) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
}
}
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register(array(new Autoloader, 'autoload'));
|
Add a test case for the tuple leak in ctraits property.
Courtesy Robert Kern.
|
""" General regression tests for fixed bugs.
"""
import gc
import unittest
import sys
from traits.has_traits import HasTraits
def _create_subclass():
class Subclass(HasTraits):
pass
return Subclass
class TestRegression(unittest.TestCase):
def test_subclasses_weakref(self):
""" Make sure that dynamically created subclasses are not held
strongly by HasTraits.
"""
previous_subclasses = HasTraits.__subclasses__()
_create_subclass()
_create_subclass()
_create_subclass()
_create_subclass()
gc.collect()
self.assertEqual(previous_subclasses, HasTraits.__subclasses__())
def test_leaked_property_tuple(self):
""" the property ctrait constructor shouldn't leak a tuple. """
class A(HasTraits):
prop = Property()
a = A()
self.assertEqual(sys.getrefcount(a.trait('prop').property()), 1)
if __name__ == '__main__':
unittest.main()
|
""" General regression tests for fixed bugs.
"""
import gc
import unittest
import sys
from traits.has_traits import HasTraits
def _create_subclass():
class Subclass(HasTraits):
pass
return Subclass
class TestRegression(unittest.TestCase):
def test_subclasses_weakref(self):
""" Make sure that dynamically created subclasses are not held
strongly by HasTraits.
"""
previous_subclasses = HasTraits.__subclasses__()
_create_subclass()
_create_subclass()
_create_subclass()
_create_subclass()
gc.collect()
self.assertEqual(previous_subclasses, HasTraits.__subclasses__())
|
Allow for Admin to Edit / Delete
Allow for Admin to Edit / Delete articles. Allow allow for edit / delete of articles if the user was deleted.
|
'use strict';
var articles = require('../controllers/articles');
// Article authorization helpers
var hasAuthorization = function(req, res, next) {
if (res.adminEnabled() || (req.article.user && (req.article.user_id === req.user._id))) {
next();
}
else {
return res.send(401, 'User is not authorized');
}
};
module.exports = function(Articles, app, auth) {
app.route('/articles')
.get(articles.all)
.post(auth.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.show)
.put(auth.requiresLogin, hasAuthorization, articles.update)
.delete(auth.requiresLogin, hasAuthorization, articles.destroy);
// Finish with setting up the articleId param
app.param('articleId', articles.article);
};
|
'use strict';
var articles = require('../controllers/articles');
// Article authorization helpers
var hasAuthorization = function(req, res, next) {
if (req.article.user.id !== req.user.id) {
return res.send(401, 'User is not authorized');
}
next();
};
module.exports = function(Articles, app, auth) {
app.route('/articles')
.get(articles.all)
.post(auth.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.show)
.put(auth.requiresLogin, hasAuthorization, articles.update)
.delete(auth.requiresLogin, hasAuthorization, articles.destroy);
// Finish with setting up the articleId param
app.param('articleId', articles.article);
};
|
Use a proper display name for the test class descendant.
|
/*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.storage.memory;
import io.spine.server.aggregate.AggregateStorageTruncationTest;
import org.junit.jupiter.api.DisplayName;
@DisplayName("`InMemoryAggregateStorage`")
class InMemoryAggregateStorageTruncationTest extends AggregateStorageTruncationTest {
}
|
/*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.storage.memory;
import io.spine.server.aggregate.AggregateStorageTruncationTest;
import org.junit.jupiter.api.DisplayName;
@DisplayName("`AggregateStorage` running in-memory after truncation should")
public class InMemoryAggregateStorageTruncationTest extends AggregateStorageTruncationTest {
}
|
Add asserts to test method.
|
package com.ticketmanor.ui.jsf;
import static org.junit.Assert.*;
import java.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
public class LocalDateTimeJsfConverterTest {
LocalDateTimeJsfConverter target;
final String stringDate = "June 1, 2015 7:30 PM";
final LocalDateTime localDateTime = LocalDateTime.of(2015, 06, 01, 19, 30, 56, 0);
@Before
public void setUp() throws Exception {
target = new LocalDateTimeJsfConverter();
}
@Test
public void testGetAsObject() {
LocalDateTime asObject = (LocalDateTime) target.getAsObject(null, null, stringDate);
System.out.println("Converted to LocalDateTime: " + asObject);
assertEquals(2015, asObject.getYear());
assertEquals(19, asObject.getHour());
}
@Test
public void testGetAsString() {
final String asString = target.getAsString(null, null, localDateTime);
System.out.println("Converted to String" + asString);
assertEquals(stringDate, asString);
}
}
|
package com.ticketmanor.ui.jsf;
import static org.junit.Assert.*;
import java.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
public class LocalDateTimeJsfConverterTest {
LocalDateTimeJsfConverter target;
final String stringDate = "June 1, 2015 7:30 PM";
final LocalDateTime localDateTime = LocalDateTime.of(2015, 06, 01, 19, 30, 56, 0);
@Before
public void setUp() throws Exception {
target = new LocalDateTimeJsfConverter();
}
@Test
public void testGetAsObject() {
final Object asObject = target.getAsObject(null, null, stringDate);
System.out.println(asObject);
}
@Test
public void testGetAsString() {
final String asString = target.getAsString(null, null, localDateTime);
System.out.println(asString);
assertEquals(stringDate, asString);
}
}
|
Remove an example proxy server definition
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port"
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://hidemy.name/en/proxy-list/?country=US&type=h#list
* http://proxyservers.pro/proxy/list/protocol/http/country/US/
"""
PROXY_LIST = {
# "example1": "35.196.26.166:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port"
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://hidemy.name/en/proxy-list/?country=US&type=h#list
* http://proxyservers.pro/proxy/list/protocol/http/country/US/
"""
PROXY_LIST = {
# "example1": "35.196.26.166:3128", # (Example) - set your own proxy here
# "example2": "208.95.62.81:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
[FIX][INTERNAL] Support Rules: Fix Eventbus rule
Change-Id: I4069957e7e14de55ee8319073c46317e101b764d
|
/*global QUnit testRule*/
sap.ui.define([
"jquery.sap.global"
], function(/*jQuery*/) {
"use strict";
QUnit.module("sap.ui.core EventBus logs rule tests", {
beforeEach: function() {
this.listener = function(){};
sap.ui.getCore().getEventBus().subscribe("myChannel", "myEvent", this.listener);
//these 2 publications should be responsible for 2 issues being found
sap.ui.getCore().getEventBus().publish("otherChannel", "myEvent", {data: 47});
sap.ui.getCore().getEventBus().publish("myListener", {data: 47});
//event should be excluded as it starts with sap
sap.ui.getCore().getEventBus().publish("sap.ui", "__fireUpdate", {data: 47});
//event should not be counted as it successfully is subscribed to
sap.ui.getCore().getEventBus().publish("myChannel", "myEvent", {data: 47});
},
afterEach: function() {
sap.ui.getCore().getEventBus().unsubscribe("myChannel", "myEvent", this.listener);
}
});
testRule({
executionScopeType: "global",
libName: "sap.ui.core",
ruleId: "eventBusSilentPublish",
expectedNumberOfIssues: 2
});
});
|
/*global QUnit testRule*/
sap.ui.define([
"jquery.sap.global"
], function(/*jQuery*/) {
"use strict";
QUnit.module("sap.ui.core EventBus logs rule tests", {
beforeEach: function() {
sap.ui.getCore().getEventBus().subscribe("myChannel", "myChannel", function(){});
//these 2 publications should be responsible for 2 issues being found
sap.ui.getCore().getEventBus().publish("otherChannel", "myListener", {data: 47});
sap.ui.getCore().getEventBus().publish("myListener", {data: 47});
//event should be excluded as it starts with sap
sap.ui.getCore().getEventBus().publish("sap.ui", "__fireUpdate", {data: 47});
//event should not be counted as it successfully is subscribed to
sap.ui.getCore().getEventBus().publish("myChannel", {data: 47});
},
afterEach: function() {
sap.ui.getCore().getEventBus().unsubscribe("myChannel", "myListener", function(){});
}
});
testRule({
executionScopeType: "global",
libName: "sap.ui.core",
ruleId: "eventBusSilentPublish",
expectedNumberOfIssues: 2
});
});
|
Remove typo from sample JS test path
Signed-off-by: Robert Munteanu <1e9fedd098ac4a5f16a7ae3d8ed22e10bc2a35a7@adobe.com>
|
/*
* Copyright 2015 Adobe Systems Incorporated
*
* 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.
*/
new hobs.TestSuite("${artifactName} Tests", {path:"/apps/${appsFolderName}/tests/SampleTests.js", register: true})
.addTestCase(new hobs.TestCase("Hello World component on english page")
.navigateTo("/content/${contentFolderName}/en.html")
.asserts.location("/content/${contentFolderName}/en.html", true)
.asserts.visible(".helloworld", true)
)
.addTestCase(new hobs.TestCase("Hello World component on french page")
.navigateTo("/content/${contentFolderName}/fr.html")
.asserts.location("/content/${contentFolderName}/fr.html", true)
.asserts.visible(".helloworld", true)
);
|
/*
* Copyright 2015 Adobe Systems Incorporated
*
* 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.
*/
new hobs.TestSuite("${artifactName} Tests", {path:"/apps/${appsFolderName}l/tests/SampleTests.js", register: true})
.addTestCase(new hobs.TestCase("Hello World component on english page")
.navigateTo("/content/${contentFolderName}/en.html")
.asserts.location("/content/${contentFolderName}/en.html", true)
.asserts.visible(".helloworld", true)
)
.addTestCase(new hobs.TestCase("Hello World component on french page")
.navigateTo("/content/${contentFolderName}/fr.html")
.asserts.location("/content/${contentFolderName}/fr.html", true)
.asserts.visible(".helloworld", true)
);
|
Fix template exception breakpoints default.
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.python.debugger;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.jetbrains.python.debugger.pydev.ExceptionBreakpointCommandFactory;
import com.sun.istack.internal.NotNull;
/**
* @author traff
*/
public abstract class ExceptionBreakpointProperties<T> extends XBreakpointProperties<T> implements ExceptionBreakpointCommandFactory{
@Attribute("exception")
public String myException;
public String getException() {
return myException;
}
public abstract String getExceptionBreakpointId();
}
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.python.debugger;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.jetbrains.python.debugger.pydev.ExceptionBreakpointCommandFactory;
/**
* @author traff
*/
public abstract class ExceptionBreakpointProperties<T> extends XBreakpointProperties<T> implements ExceptionBreakpointCommandFactory{
@Attribute("exception")
public String myException;
public String getException() {
return myException;
}
public abstract String getExceptionBreakpointId();
}
|
Order module exports and comment for order
|
// @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exception from './exceptions/index'
import ColorRGB from './struct/color-rgb'
import ColorRGBA from './struct/color-rgba'
import Type from './plugin/type-descriptor'
import * as ProjectHelper from './helper/project-helper'
import LayerPluginBase from './plugin/layer-plugin-base'
// Core
export * as Project from './project/index'
export Renderer from './renderer/renderer'
export * as Services from './services'
export * as Exception from './exceptions/index'
// Structure
export ColorRGB from './struct/color-rgb'
export ColorRGBA from './struct/color-rgba'
// import shorthand
export Type from './plugin/type-descriptor'
export * as ProjectHelper from './helper/project-helper'
export LayerPluginBase from './plugin/layer-plugin-base'
export default {
// Core
Project,
Renderer,
Services,
Exception,
// Structure
ColorRGB,
ColorRGBA,
// import shorthand
Type,
ProjectHelper,
LayerPluginBase,
}
|
// @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import LayerPluginBase from './plugin/layer-plugin-base'
import Type from './plugin/type-descriptor'
import * as ProjectHelper from './helper/project-helper'
import * as Exception from './exceptions/index'
import ColorRGB from './struct/color-rgb'
import ColorRGBA from './struct/color-rgba'
export * as Project from './project/index'
export Renderer from './renderer/renderer'
export * as Services from './services'
export LayerPluginBase from './plugin/layer-plugin-base'
export Type from './plugin/type-descriptor'
export * as ProjectHelper from './helper/project-helper'
export * as Exception from './exceptions/index'
export ColorRGB from './struct/color-rgb'
export ColorRGBA from './struct/color-rgba'
export default {
Project,
Renderer,
Services,
Exception,
Type,
ProjectHelper,
ColorRGB,
ColorRGBA,
}
|
Fix read of wrong dictionnary
|
# Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class ProcurementRule(models.Model):
_inherit = 'procurement.rule'
def _get_stock_move_values(self, product_id, product_qty, product_uom,
location_id, name, origin, values, group_id):
vals = super(ProcurementRule, self)._get_stock_move_values(
product_id, product_qty, product_uom,
location_id, name, origin, values, group_id)
if 'orderpoint_id' in values:
vals['orderpoint_ids'] = [(4, values['orderpoint_id'].id)]
elif 'orderpoint_ids' in values:
vals['orderpoint_ids'] = [(4, o.id)
for o in values['orderpoint_ids']]
return vals
|
# Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class ProcurementRule(models.Model):
_inherit = 'procurement.rule'
def _get_stock_move_values(self, product_id, product_qty, product_uom,
location_id, name, origin, values, group_id):
vals = super(ProcurementRule, self)._get_stock_move_values(
product_id, product_qty, product_uom,
location_id, name, origin, values, group_id)
if 'orderpoint_id' in values:
vals['orderpoint_ids'] = [(4, values['orderpoint_id'].id)]
elif 'orderpoint_ids' in values:
vals['orderpoint_ids'] = [(4, o.id)
for o in vals['orderpoint_ids']]
return vals
|
Fix test for settings command
|
# Copyright 2014-2015 Ivan Kravets <me@ikravets.com>
#
# 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 platformio.commands.settings import cli
from platformio import app
def test_settings_check(clirunner, validate_cliresult):
result = clirunner.invoke(cli, ["get"])
assert result.exit_code == 0
assert not result.exception
assert len(result.output)
for item in app.DEFAULT_SETTINGS.items():
assert item[0] in result.output
|
# Copyright 2014-2015 Ivan Kravets <me@ikravets.com>
#
# 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 platformio.commands.settings import cli
from platformio import app
def test_settings_check(clirunner, validate_cliresult):
result = clirunner.invoke(cli, ["get"])
validate_cliresult(result)
assert len(result.output)
for item in app.DEFAULT_SETTINGS.items():
assert item[0] in result.output
|
[OWL-693][agent] Update agent version to 5.1.7
|
package g
import (
"time"
)
// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugin mechanism
// 5.1.6: Update cfg.json in release package. Program file is same as 5.1.5.
// 5.1.7: Fix failure of plugin updating.
const (
VERSION = "5.1.7"
COLLECT_INTERVAL = time.Second
URL_CHECK_HEALTH = "url.check.health"
NET_PORT_LISTEN = "net.port.listen"
DU_BS = "du.bs"
PROC_NUM = "proc.num"
)
|
package g
import (
"time"
)
// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugin mechanism
// 5.1.6: Update cfg.json in release package. Program file is same as 5.1.5.
const (
VERSION = "5.1.6"
COLLECT_INTERVAL = time.Second
URL_CHECK_HEALTH = "url.check.health"
NET_PORT_LISTEN = "net.port.listen"
DU_BS = "du.bs"
PROC_NUM = "proc.num"
)
|
Fix indentation error in some helpers
|
# -*- coding: utf-8 -*-
import os
import re
import argparse
def fix_fathatan(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
new_lines = []
for line in lines:
new_lines.append(re.sub(r'اً', 'ًا', line))
file_path = file_path.split(os.sep)
file_path[-1] = 'fixed_' + file_path[-1]
file_path = os.sep.join(file_path)
with open(file_path, 'w') as file:
file.write(''.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Changes after-Alif fathatan to before-Alit fathatan')
parser.add_argument('-in', '--file-path', help='File path to fix it', required=True)
args = parser.parse_args()
fix_fathatan(args.file_path)
|
# -*- coding: utf-8 -*-
import os
import re
import argparse
def fix_fathatan(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
new_lines = []
for line in lines:
new_lines.append(re.sub(r'اً', 'ًا', line))
file_path = file_path.split(os.sep)
file_path[-1] = 'fixed_' + file_path[-1]
file_path = os.sep.join(file_path)
with open(file_path, 'w') as file:
file.write(''.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Changes after-Alif fathatan to before-Alit fathatan')
parser.add_argument('-in', '--file-path', help='File path to fix it', required=True)
args = parser.parse_args()
fix_fathatan(args.file_path)
|
Add partial application plugin for babel.
|
const {join} = require("path")
module.exports = {
plugins: [
["module-resolver", {
cwd: __dirname,
root: ["src"],
alias: {
"package.json": join(__dirname, "package.json")
}
}],
"@babel/transform-runtime",
["@babel/proposal-decorators", {
legacy: true
}],
["@babel/proposal-class-properties", {
loose: true
}],
"@babel/proposal-partial-application",
"@babel/proposal-nullish-coalescing-operator",
"@babel/proposal-optional-catch-binding",
"@babel/proposal-optional-chaining",
"@babel/proposal-export-namespace-from",
"@babel/proposal-export-default-from",
"@babel/proposal-do-expressions",
["@babel/proposal-pipeline-operator", {
proposal: "minimal"
}],
["@babel/transform-modules-commonjs", {
mjsStrictNamespace: false
}],
]
}
|
const {join} = require("path")
module.exports = {
plugins: [
["module-resolver", {
cwd: __dirname,
root: ["src"],
alias: {
"package.json": join(__dirname, "package.json")
}
}],
"@babel/transform-runtime",
["@babel/proposal-decorators", {
legacy: true
}],
["@babel/proposal-class-properties", {
loose: true
}],
"@babel/plugin-proposal-partial-application",
"@babel/proposal-nullish-coalescing-operator",
"@babel/proposal-optional-catch-binding",
"@babel/proposal-optional-chaining",
"@babel/proposal-export-namespace-from",
"@babel/proposal-export-default-from",
"@babel/proposal-do-expressions",
["@babel/proposal-pipeline-operator", {
proposal: "minimal"
}],
["@babel/transform-modules-commonjs", {
mjsStrictNamespace: false
}],
]
}
|
Make the echo command actually echo all its parameters.
|
from __future__ import print_function
import shlex
from traceback import format_exception
from obj import Obj
import click
from click.testing import CliRunner
runner = CliRunner()
@click.group(name='')
@click.argument('user', required=True)
@click.pass_context
def command(ctx, user, **kwargs):
ctx.obj = Obj(user=user)
@command.command()
@click.pass_context
def about(ctx, **kwargs):
click.echo('This is the about command.')
@command.command()
@click.argument('stuff', nargs=-1, required=False)
@click.pass_context
def echo(ctx, stuff, **kwargs):
click.echo('This is the echo command. You are {}.'.format(ctx.obj.user))
if stuff:
click.echo(' '.join(stuff))
else:
click.echo('[no parameters]')
def run(user, cmd):
result = runner.invoke(command, [user,] + shlex.split(cmd))
print('run result: {}'.format(result))
if not result.output:
print('Exception: {}\nTraceback:\n {}'.format(result.exception, ''.join(format_exception(*result.exc_info))))
return 'Internal error.'
return result.output
# Import files with subcommands here--we don't use them directly, but we need
# to make sure they're loaded, since that's when they add their commands to
# our command object.
import list_commands
|
from __future__ import print_function
import shlex
from traceback import format_exception
from obj import Obj
import click
from click.testing import CliRunner
runner = CliRunner()
@click.group(name='')
@click.argument('user', required=True)
@click.pass_context
def command(ctx, user, **kwargs):
ctx.obj = Obj(user=user)
@command.command()
@click.pass_context
def about(ctx, **kwargs):
click.echo('This is the about command.')
@command.command()
@click.pass_context
def echo(ctx, **kwargs):
click.echo('This is the echo command. You are {}.'.format(ctx.obj.user))
def run(user, cmd):
result = runner.invoke(command, [user,] + shlex.split(cmd))
print('run result: {}'.format(result))
if not result.output:
print('Exception: {}\nTraceback:\n {}'.format(result.exception, ''.join(format_exception(*result.exc_info))))
return 'Internal error.'
return result.output
# Import files with subcommands here--we don't use them directly, but we need
# to make sure they're loaded, since that's when they add their commands to
# our command object.
import list_commands
|
Use base Repo name in updating UI.
|
from os.path import basename
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.system.updater import do_reboot
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
self._view.args["subtitle"] = "Please wait ..."
def on_service_start(self):
values = check_updates()
for val in values:
repo_name = basename(val.decode())
self._view.args["subtitle"] = "Working with {}... ".format(repo_name)
self.observer()
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Updating system configuration..."
self.observer()
run_ansible()
self._view.args["subtitle"] = "Restarting..."
self.observer()
do_reboot()
def view(self):
return self._view
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.system.updater import do_reboot
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
self._view.args["subtitle"] = "Please wait ..."
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with {}... ".format(str((val)))
self.observer()
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Updating system configuration..."
self.observer()
run_ansible()
self._view.args["subtitle"] = "Restarting..."
self.observer()
do_reboot()
def view(self):
return self._view
|
Add note about directed graphs
--HG--
extra : convert_revision : svn%3A3ed01bd8-26fb-0310-9e4c-ca1a4053419f/networkx/trunk%401776
|
"""
Ego graph.
"""
# Copyright (C) 2010 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
__author__ = """\n""".join(['Drew Conway <drew.conway@nyu.edu>',
'Aric Hagberg <hagberg@lanl.gov>'])
__all__ = ['ego_graph']
import networkx as nx
def ego_graph(G,n,radius=1,center=True):
"""Returns induced subgraph of neighbors centered at node n.
Parameters
----------
G : graph
A NetworkX Graph or DiGraph
n : node
A single node
radius : integer
Include all neighbors of distance<=radius from n
center : bool, optional
If False, do not include center node in graph
Notes
-----
For directed graphs D this produces the "out" neighborhood
or successors. If you want the neighborhood of predecessors
first reverse the graph with D.reverse(). If you want both
first convert the graph to an undirected graph using G=nx.Graph(D).
"""
sp=nx.single_source_shortest_path_length(G,n,cutoff=radius)
H=G.subgraph(sp.keys())
if not center:
H.remove_node(n)
return H
|
"""
Ego graph.
"""
# Copyright (C) 2010 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
__author__ = """\n""".join(['Drew Conway <drew.conway@nyu.edu>',
'Aric Hagberg <hagberg@lanl.gov>'])
__all__ = ['ego_graph']
import networkx as nx
def ego_graph(G,n,radius=1,center=True):
"""Returns induced subgraph of neighbors centered at node n.
Parameters
----------
G : graph
A NetworkX Graph or DiGraph
n : node
A single node
radius : integer
Include all neighbors of distance<=radius from n
center : bool, optional
If False, do not include center node in graph
"""
sp=nx.single_source_shortest_path_length(G,n,cutoff=radius)
H=G.subgraph(sp.keys())
if not center:
H.remove_node(n)
return H
|
Test for correct log term.
|
<?php
include_once(dirname(dirname(__DIR__)).'/src/raft/log.php');
class Raft_Log_Test extends PHPUnit_Framework_TestCase {
public function setUp() {
$this->log = new Raft_Log();
}
public function test_log_append_entry_is_pending() {
$this->assertEquals(0, $this->log->getCommitIndex());
$this->log->appendEntry('add', '2');
$this->assertEquals(0, $this->log->getCommitIndex());
$this->assertEquals('2', $this->log->getPendingTerm());
$this->assertEquals('add', $this->log->getPendingEntry());
}
public function test_commit_increases_commit_index() {
$this->assertEquals(0, $this->log->getCommitIndex());
$this->log->appendEntry('add', '2');
$this->log->commitEntry();
$this->assertEquals(1, $this->log->getCommitIndex());
$this->assertEquals(NULL, $this->log->getPendingTerm());
$this->assertEquals(NULL, $this->log->getPendingEntry());
}
public function test_commit_saves_correct_term() {
$this->assertEquals(0, $this->log->getCommitIndex());
$this->log->appendEntry('add', 2);
$this->log->commitEntry();
$this->log->appendEntry('add', 3);
$this->log->commitEntry();
$this->assertEquals(2, $this->log->getTermForIndex(0));
$this->assertEquals(3, $this->log->getTermForIndex(1));
}
}
|
<?php
include_once(dirname(dirname(__DIR__)).'/src/raft/log.php');
class Raft_Log_Test extends PHPUnit_Framework_TestCase {
public function setUp() {
$this->log = new Raft_Log();
}
public function test_log_append_entry_is_pending() {
$this->assertEquals(0, $this->log->getCommitIndex());
$this->log->appendEntry('add', '2');
$this->assertEquals(0, $this->log->getCommitIndex());
$this->assertEquals('2', $this->log->getPendingTerm());
$this->assertEquals('add', $this->log->getPendingEntry());
}
public function test_commit_increases_commit_index() {
$this->assertEquals(0, $this->log->getCommitIndex());
$this->log->appendEntry('add', '2');
$this->log->commitEntry();
$this->assertEquals(1, $this->log->getCommitIndex());
$this->assertEquals(NULL, $this->log->getPendingTerm());
$this->assertEquals(NULL, $this->log->getPendingEntry());
}
}
|
Check document dir before extending options
|
/**
* @Description: GridGallery is a tiny package that will generate a grid depending on
* the elements height. It is not required to have the same height
*
* @Author: Mohamed Hassan
* @Author Url: http://mohamedhassan.me
*
* @License: under MIT
* https://github.com/pencilpix/grid-gallery/blob/master/LICENSE
*/
((name, definition) => {
let theModule = definition(),
hasDefine = typeof define === 'function' && define.amd,
hasExports = typeof module !== 'undefined' && module.exports;
if(hasDefine)
define(theModule);
else if(hasExports)
module.exports = theModule;
else
window[name] = theModule;
})('GridGallery', () => {
const VERSION = '1.0.1';
const DEFAULTS = {
direction: 'left',
};
class GridGallery {
constructor( element, options ) {
this.options = Object.assign({}, GridGallery.DEFAULTS, options);
}
static get DEFAULTS () {
if(document.documentElement.dir === 'rtl')
DEFAULTS.direction = 'right';
else
DEFAULTS.direction = 'left';
return DEFAULTS;
}
}
return GridGallery;
});
|
/**
* @Description: GridGallery is a tiny package that will generate a grid depending on
* the elements height. It is not required to have the same height
*
* @Author: Mohamed Hassan
* @Author Url: http://mohamedhassan.me
*
* @License: under MIT
* https://github.com/pencilpix/grid-gallery/blob/master/LICENSE
*/
((name, definition) => {
let theModule = definition(),
hasDefine = typeof define === 'function' && define.amd,
hasExports = typeof module !== 'undefined' && module.exports;
if(hasDefine)
define(theModule);
else if(hasExports)
module.exports = theModule;
else
window[name] = theModule;
})('GridGallery', () => {
const VERSION = '1.0.1';
const DEFAULTS = {
direction: 'left',
};
class GridGallery {
constructor( element, options ) {
this.options = Object.assign({}, DEFAULTS, options);
}
}
return GridGallery;
});
|
Fix newlines on monsters' descriptions.
|
<?php
namespace Presenters;
class Monster extends \Robbo\Presenter\Presenter
{
function presentSymbol() {
list($fg, $bg) = colorPairToCSS($this->object->color);
return sprintf("<span style=\"color: %s; background: %s\">%s</span>",
$fg, $bg,
$this->object->symbol);
}
function presentNiceName() {
return ucfirst($this->object->name);
}
function presentFlags() {
return join(", ", $this->object->flags);
}
function presentDeathFunction() {
$death = (array) $this->object->death_function;
if(empty($death))
return "";
return join(", ", $death);
}
function presentSpecialAttacks() {
$attacks = (array) $this->object->special_attacks;
if(empty($attacks)) {
return "";
}
array_walk($attacks, function(&$attack) {
$attack = "$attack[0]: $attack[1]";
});
return join(",<br>", $attacks);
}
function presentSpecies() {
$links = array_map(function($species) {
return link_to_route('monster.species', $species, array($species));
}, $this->object->species);
return join(", ", $links);
}
function presentDamage() {
return "{$this->melee_dice}d{$this->melee_dice_sides}+{$this->melee_cut}";
}
function presentDescription() {
return preg_replace("/\\n/", "<br>", htmlspecialchars($this->object->description));
}
}
|
<?php
namespace Presenters;
class Monster extends \Robbo\Presenter\Presenter
{
function presentSymbol() {
list($fg, $bg) = colorPairToCSS($this->object->color);
return sprintf("<span style=\"color: %s; background: %s\">%s</span>",
$fg, $bg,
$this->object->symbol);
}
function presentNiceName() {
return ucfirst($this->object->name);
}
function presentFlags() {
return join(", ", $this->object->flags);
}
function presentDeathFunction() {
$death = (array) $this->object->death_function;
if(empty($death))
return "";
return join(", ", $death);
}
function presentSpecialAttacks() {
$attacks = (array) $this->object->special_attacks;
if(empty($attacks)) {
return "";
}
array_walk($attacks, function(&$attack) {
$attack = "$attack[0]: $attack[1]";
});
return join(",<br>", $attacks);
}
function presentSpecies() {
$links = array_map(function($species) {
return link_to_route('monster.species', $species, array($species));
}, $this->object->species);
return join(", ", $links);
}
function presentDamage() {
return "{$this->melee_dice}d{$this->melee_dice_sides}+{$this->melee_cut}";
}
}
|
Use just basic logging for requests
|
package com.jraska.github.client.network;
import android.content.Context;
import com.jraska.github.client.dagger.PerApp;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import timber.log.Timber;
import java.io.File;
@Module
public class NetworkModule {
@Provides @PerApp OkHttpClient provideOkHttpClient(Context context) {
HttpLoggingInterceptor.Logger logger = message -> Timber.tag("OkHttp").v(message);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(logger);
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
File cacheDir = context.getCacheDir();
Cache cache = new Cache(cacheDir, 1024 * 1024 * 4);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.cache(cache)
.build();
return client;
}
}
|
package com.jraska.github.client.network;
import android.content.Context;
import com.jraska.github.client.dagger.PerApp;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import timber.log.Timber;
import java.io.File;
@Module
public class NetworkModule {
@Provides @PerApp OkHttpClient provideOkHttpClient(Context context) {
HttpLoggingInterceptor.Logger logger = message -> Timber.tag("OkHttp").v(message);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(logger);
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
File cacheDir = context.getCacheDir();
Cache cache = new Cache(cacheDir, 1024 * 1024 * 4);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.cache(cache)
.build();
return client;
}
}
|
Set sourceRoot in source maps
This removes the full source path of whoever last published the package
from the stacktraces we show when `EXPO_DEBUG` is enabled and instead
uses `exp@<version>` or `xdl@<version>` as the path.
fbshipit-source-id: a12977a
|
const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const changed = require('gulp-changed');
const plumber = require('gulp-plumber');
const sourcemaps = require('gulp-sourcemaps');
const rimraf = require('rimraf');
const package = require('./package.json');
const paths = {
source: 'src/**/*.js',
build: 'build',
builtFiles: 'build/**/*.{js,map}',
nextBuild: 'expo-cli/build',
};
const tasks = {
babel() {
return gulp
.src(paths.source)
.pipe(changed(paths.build))
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(
sourcemaps.write('__sourcemaps__', {
sourceRoot: `/${package.name}@${package.version}/src`,
})
)
.pipe(gulp.dest(paths.build));
},
copy() {
return gulp.src(paths.builtFiles).pipe(gulp.dest(paths.nextBuild));
},
watchBabel(done) {
gulp.watch(paths.source, gulp.series([tasks.babel, tasks.copy]));
done();
},
};
gulp.task('build', gulp.series([tasks.babel, tasks.copy]));
gulp.task('watch', tasks.watchBabel);
gulp.task('clean', done => {
rimraf(paths.build, done);
});
gulp.task('default', gulp.series('watch'));
|
const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const changed = require('gulp-changed');
const plumber = require('gulp-plumber');
const sourcemaps = require('gulp-sourcemaps');
const rimraf = require('rimraf');
const paths = {
source: 'src/**/*.js',
build: 'build',
sourceRoot: path.join(__dirname, 'src'),
builtFiles: 'build/**/*.{js,map}',
nextBuild: 'expo-cli/build',
};
const tasks = {
babel() {
return gulp
.src(paths.source)
.pipe(changed(paths.build))
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(sourcemaps.write('__sourcemaps__', { sourceRoot: paths.sourceRoot }))
.pipe(gulp.dest(paths.build));
},
copy() {
return gulp.src(paths.builtFiles).pipe(gulp.dest(paths.nextBuild));
},
watchBabel(done) {
gulp.watch(paths.source, gulp.series([tasks.babel, tasks.copy]));
done();
},
};
gulp.task('build', gulp.series([tasks.babel, tasks.copy]));
gulp.task('watch', tasks.watchBabel);
gulp.task('clean', done => {
rimraf(paths.build, done);
});
gulp.task('default', gulp.series('watch'));
|
Update Nuclear version in about screen
|
import hass from '../util/home-assistant-js-instance';
import Polymer from '../polymer';
import nuclearObserver from '../util/bound-nuclear-behavior';
require('./partial-base');
const {
configGetters,
errorLogActions,
} = hass;
export default new Polymer({
is: 'partial-dev-info',
behaviors: [nuclearObserver],
properties: {
narrow: {
type: Boolean,
value: false,
},
showMenu: {
type: Boolean,
value: false,
},
hassVersion: {
type: String,
bindNuclear: configGetters.serverVersion,
},
polymerVersion: {
type: String,
value: Polymer.version,
},
nuclearVersion: {
type: String,
value: '1.3.0',
},
errorLog: {
type: String,
value: '',
},
},
attached() {
this.refreshErrorLog();
},
refreshErrorLog(ev) {
if (ev) ev.preventDefault();
this.errorLog = 'Loading error log…';
errorLogActions.fetchErrorLog().then(
log => this.errorLog = log || 'No errors have been reported.');
},
});
|
import hass from '../util/home-assistant-js-instance';
import Polymer from '../polymer';
import nuclearObserver from '../util/bound-nuclear-behavior';
require('./partial-base');
const {
configGetters,
errorLogActions,
} = hass;
export default new Polymer({
is: 'partial-dev-info',
behaviors: [nuclearObserver],
properties: {
narrow: {
type: Boolean,
value: false,
},
showMenu: {
type: Boolean,
value: false,
},
hassVersion: {
type: String,
bindNuclear: configGetters.serverVersion,
},
polymerVersion: {
type: String,
value: Polymer.version,
},
nuclearVersion: {
type: String,
value: '1.2.1',
},
errorLog: {
type: String,
value: '',
},
},
attached() {
this.refreshErrorLog();
},
refreshErrorLog(ev) {
if (ev) ev.preventDefault();
this.errorLog = 'Loading error log…';
errorLogActions.fetchErrorLog().then(
log => this.errorLog = log || 'No errors have been reported.');
},
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.