text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change extended ASCII character in docstring
Fix a – and replace it with a -
|
"""foo.py - a simple demo of importing a calss from C++"""
import ctypes
lib = ctypes.cdll.LoadLibrary('./libfoo.so')
class Foo(object):
"""The Foo class supports two methods, bar, and foobar..."""
def __init__(self, val):
lib.Foo_new.argtypes = [ctypes.c_int]
lib.Foo_new.restype = ctypes.c_void_p
lib.Foo_bar.argtypes = [ctypes.c_void_p]
lib.Foo_bar.restype = ctypes.c_char_p
lib.Foo_foobar.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.Foo_foobar.restype = ctypes.c_int
self.obj = lib.Foo_new(val)
def bar(self):
"""bar returns a string continaing the value"""
return (lib.Foo_bar(self.obj)).decode()
def foobar(self, val):
"""foobar takes an integer, and adds it to the value in the Foo class
- returning the result"""
return lib.Foo_foobar(self.obj, val)
|
"""foo.py – a simple demo of importing a calss from C++"""
import ctypes
lib = ctypes.cdll.LoadLibrary('./libfoo.so')
class Foo(object):
"""The Foo class supports two methods, bar, and foobar..."""
def __init__(self, val):
lib.Foo_new.argtypes = [ctypes.c_int]
lib.Foo_new.restype = ctypes.c_void_p
lib.Foo_bar.argtypes = [ctypes.c_void_p]
lib.Foo_bar.restype = ctypes.c_char_p
lib.Foo_foobar.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.Foo_foobar.restype = ctypes.c_int
self.obj = lib.Foo_new(val)
def bar(self):
"""bar returns a string continaing the value"""
return (lib.Foo_bar(self.obj)).decode()
def foobar(self, val):
"""foobar takes an integer, and adds it to the value in the Foo class
- returning the result"""
return lib.Foo_foobar(self.obj, val)
|
Change the energy creator container
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.containertype.UContainerType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.*;
import net.minecraft.inventory.container.ContainerType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestContainers {
public static final DeferredRegister<ContainerType<?>> CONTAINER_TYPES = DeferredRegister.create(ForgeRegistries.CONTAINERS, TestMod.MODID);
public static final RegistryObject<UContainerType<BasicTileEntityContainer>> BASIC = CONTAINER_TYPES.register("basic", () -> new UContainerType<>("basic", BasicTileEntityContainer::new));
public static final RegistryObject<ContainerType<BasicEnergyCreatorContainer>> BASIC_ENERGY_CREATOR = CONTAINER_TYPES.register("energy_creator", () -> new UContainerType<>("energy_creator", BasicEnergyCreatorContainer::new));
public static final ContainerType<BasicFluidInventoryContainer> BASIC_FLUID_INVENTORY = new UContainerType<>("fluid_inventory", BasicFluidInventoryContainer::new);
public static void register(IEventBus bus) {
CONTAINER_TYPES.register(bus);
}
}
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_core.containertype.UContainerType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.*;
import net.minecraft.inventory.container.ContainerType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestContainers {
public static final DeferredRegister<ContainerType<?>> CONTAINER_TYPES = DeferredRegister.create(ForgeRegistries.CONTAINERS, TestMod.MODID);
public static final RegistryObject<UContainerType<BasicTileEntityContainer>> BASIC = CONTAINER_TYPES.register("basic", () -> new UContainerType<>("basic", BasicTileEntityContainer::new));
public static final ContainerType<BasicEnergyCreatorContainer> BASIC_ENERGY_CREATOR = new UContainerType<>("energy_creator", BasicEnergyCreatorContainer::new);
public static final ContainerType<BasicFluidInventoryContainer> BASIC_FLUID_INVENTORY = new UContainerType<>("fluid_inventory", BasicFluidInventoryContainer::new);
public static void register(IEventBus bus) {
CONTAINER_TYPES.register(bus);
}
}
|
Fix didTransition deprecation on Ember 3.6+
|
import { VERSION } from '@ember/version';
// Taken from ember-test-helpers
function hasEmberVersion(major, minor) {
const numbers = VERSION.split('-')[0].split('.');
const actualMajor = parseInt(numbers[0], 10);
const actualMinor = parseInt(numbers[1], 10);
return actualMajor > major || (actualMajor === major && actualMinor >= minor);
}
export function initialize(appInstance) {
// Support Ember 1.13+
const owner = appInstance.lookup ? appInstance : appInstance.container;
const routerServicePresent = hasEmberVersion(3, 6);
const router = owner.lookup(
routerServicePresent ? 'service:router' : 'router:main'
);
const segment = owner.lookup('service:segment');
// Since Ember v3.6 didTransition is deprecated in favour of routeDidChange
const eventName = routerServicePresent ? 'routeDidChange' : 'didTransition';
router.on(eventName, function() {
const applicationRoute = owner.lookup('route:application');
if (segment && segment.isPageTrackEnabled()) {
if (typeof applicationRoute.trackPageView === 'function') {
applicationRoute.trackPageView();
} else {
segment.trackPageView();
}
}
if (segment && segment.isIdentifyUserEnabled()) {
if (
applicationRoute &&
typeof applicationRoute.identifyUser === 'function'
) {
applicationRoute.identifyUser();
}
}
});
}
export default {
name: 'segment',
initialize
};
|
export function initialize(appInstance) {
// Support Ember 1.13+
const owner = appInstance.lookup ? appInstance : appInstance.container;
const router = owner.lookup('router:main');
const segment = owner.lookup('service:segment');
router.on('didTransition', function() {
const applicationRoute = owner.lookup('route:application');
if (segment && segment.isPageTrackEnabled()) {
if (typeof applicationRoute.trackPageView === 'function') {
applicationRoute.trackPageView();
} else {
segment.trackPageView();
}
}
if (segment && segment.isIdentifyUserEnabled()) {
if (
applicationRoute &&
typeof applicationRoute.identifyUser === 'function'
) {
applicationRoute.identifyUser();
}
}
});
}
export default {
name: 'segment',
initialize
};
|
Add lang property to the html tag
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render ({ children, assets, title } = this.props) {
return (
<html lang='en'>
<head>
<title>{title}</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
<meta name='description' content='Analyze your site’s speed according to HTTP best practices.' />
<meta name='author' content='Jan Svager <https://www.svager.cz>' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: children }} />
<script defer src={`/${assets.init.js}`} />
<script defer src={`/${assets.react.js}`} />
<script defer src={`/${assets.app.js}`} />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render ({ children, assets, title } = this.props) {
return (
<html>
<head>
<title>{title}</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
<meta name='description' content='Analyze your site’s speed according to HTTP best practices.' />
<meta name='author' content='Jan Svager <https://www.svager.cz>' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: children }} />
<script defer src={`/${assets.init.js}`} />
<script defer src={`/${assets.react.js}`} />
<script defer src={`/${assets.app.js}`} />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
Change to open proto file from testdata
|
package generator
import (
"fmt"
"os"
"testing"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/google/go-cmp/cmp"
)
func TestGenerator_GenerateAllFiles(t *testing.T) {
type fields struct {
}
tests := []struct {
name string
fields fields
want *plugin.CodeGeneratorResponse
}{
{
name: "helloworld",
fields: fields{},
want: &plugin.CodeGeneratorResponse{
File: []*plugin.CodeGeneratorResponse_File{
{
Name: proto.String("foo"),
Content: proto.String("bar"),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p, err := os.Open(fmt.Sprintf("testdata/%s.proto", tt.name))
if err != nil {
t.Fatalf("failed to open proto file: %v", err)
}
g := &Generator{
w: p,
}
if diff := cmp.Diff(g.GenerateAllFiles(), tt.want); diff != "" {
t.Errorf("%s", diff)
}
})
}
}
|
package generator
import (
"io"
"reflect"
"testing"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
func TestGenerator_GenerateAllFiles(t *testing.T) {
type fields struct {
w io.Writer
}
tests := []struct {
name string
fields fields
want *plugin.CodeGeneratorResponse
}{
{
name: "helloworld",
fields: fields{
w: nil,
},
want: &plugin.CodeGeneratorResponse{
File: []*plugin.CodeGeneratorResponse_File{
{
Name: proto.String("foo"),
Content: proto.String("bar"),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Generator{
w: tt.fields.w,
}
if got := g.GenerateAllFiles(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Generator.GenerateAllFiles() = %v, want %v", got, tt.want)
}
})
}
}
|
Fix argument double encoding for HttpHead
To follow #157 that fixed double encoding on file download
|
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpHead extends CordovaHttp implements Runnable {
public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), false);
this.prepareRequest(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}
|
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpHead extends CordovaHttp implements Runnable {
public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), true);
this.prepareRequest(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}
|
Rename 'pwd' field in windows shadow.info output
This makes the field name consistent with the other shadow modules. Note
that the passwd field is not used at all in Windows user management, so
this is merely a cosmetic change.
|
'''
Manage the shadow file
'''
import salt.utils
def __virtual__():
'''
Only works on Windows systems
'''
if salt.utils.is_windows():
return 'shadow'
return False
def info(name):
'''
Return information for the specified user
This is just returns dummy data so that salt states can work.
CLI Example::
salt '*' shadow.info root
'''
ret = {
'name': name,
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
return ret
def set_password(name, password):
'''
Set the password for a named user.
CLI Example::
salt '*' shadow.set_password root mysecretpassword
'''
cmd = 'net user {0} {1}'.format(name, password)
ret = __salt__['cmd.run_all'](cmd)
return not ret['retcode']
|
'''
Manage the shadow file
'''
import salt.utils
def __virtual__():
'''
Only works on Windows systems
'''
if salt.utils.is_windows():
return 'shadow'
return False
def info(name):
'''
Return information for the specified user
This is just returns dummy data so that salt states can work.
CLI Example::
salt '*' shadow.info root
'''
ret = {
'name': name,
'pwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
return ret
def set_password(name, password):
'''
Set the password for a named user.
CLI Example::
salt '*' shadow.set_password root mysecretpassword
'''
cmd = 'net user {0} {1}'.format(name, password)
ret = __salt__['cmd.run_all'](cmd)
return not ret['retcode']
|
Fix type issue between Application and Container
ResourceFactory should take a Container, not an Application.
|
<?php
namespace JDesrosiers\Resourceful\ResourcefulServiceProvider;
use Pimple\Container;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ResourcesFactory
{
private $app;
public function __construct(Container $app)
{
$this->app = $app;
}
public function __invoke($schema)
{
$resource = $this->app["controllers_factory"];
$resource->after(function (Request $request, Response $response, Application $app) use ($schema) {
if ($response->isSuccessful()) {
$app["json-schema.describedBy"] = $schema;
}
});
return $resource;
}
}
|
<?php
namespace JDesrosiers\Resourceful\ResourcefulServiceProvider;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ResourcesFactory
{
private $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function __invoke($schema)
{
$resource = $this->app["controllers_factory"];
$resource->after(function (Request $request, Response $response, Application $app) use ($schema) {
if ($response->isSuccessful()) {
$app["json-schema.describedBy"] = $schema;
}
});
return $resource;
}
}
|
Fix data handler first position crash
|
/*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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.
*/
package org.traccar;
import org.traccar.helper.Log;
import org.traccar.model.Position;
public class DefaultDataHandler extends BaseDataHandler {
@Override
protected Position handlePosition(Position position) {
try {
Context.getDataManager().addPosition(position);
Position lastPosition = Context.getConnectionManager().getLastPosition(position.getDeviceId());
if (lastPosition == null || position.getFixTime().compareTo(lastPosition.getFixTime()) > 0) {
Context.getDataManager().updateLatestPosition(position);
}
} catch (Exception error) {
Log.warning(error);
}
return position;
}
}
|
/*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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.
*/
package org.traccar;
import org.traccar.helper.Log;
import org.traccar.model.Position;
public class DefaultDataHandler extends BaseDataHandler {
@Override
protected Position handlePosition(Position position) {
try {
Context.getDataManager().addPosition(position);
Position lastPosition = Context.getConnectionManager().getLastPosition(position.getDeviceId());
if (position.getFixTime().compareTo(lastPosition.getFixTime()) > 0) {
Context.getDataManager().updateLatestPosition(position);
}
} catch (Exception error) {
Log.warning(error);
}
return position;
}
}
|
Change order that fields are updated
|
package io.undertow.server.handlers;
import java.util.Date;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.DateUtils;
import io.undertow.util.Headers;
/**
* Class that adds the Date: header to a HTTP response.
*
* The current date string is cached, and is updated every second in a racey
* manner (i.e. it is possible for two thread to update it at once).
*
* @author Stuart Douglas
*/
public class DateHandler implements HttpHandler {
private final HttpHandler next;
private volatile String cachedDateString;
private volatile long nextUpdateTime = -1;
public DateHandler(final HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
long time = System.currentTimeMillis();
if(time < nextUpdateTime) {
exchange.getResponseHeaders().put(Headers.DATE, cachedDateString);
} else {
String dateString = DateUtils.toDateString(new Date(time));
cachedDateString = dateString;
nextUpdateTime = time + 1000;
exchange.getResponseHeaders().put(Headers.DATE, dateString);
}
next.handleRequest(exchange);
}
}
|
package io.undertow.server.handlers;
import java.util.Date;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.DateUtils;
import io.undertow.util.Headers;
/**
* Class that adds the Date: header to a HTTP response.
*
* The current date string is cached, and is updated every second in a racey
* manner (i.e. it is possible for two thread to update it at once).
*
* @author Stuart Douglas
*/
public class DateHandler implements HttpHandler {
private final HttpHandler next;
private volatile String cachedDateString;
private volatile long nextUpdateTime = -1;
public DateHandler(final HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
long time = System.currentTimeMillis();
if(time < nextUpdateTime) {
exchange.getResponseHeaders().put(Headers.DATE, cachedDateString);
} else {
nextUpdateTime = time + 1000;
String dateString = DateUtils.toDateString(new Date(time));
cachedDateString = dateString;
exchange.getResponseHeaders().put(Headers.DATE, dateString);
}
next.handleRequest(exchange);
}
}
|
Change how PSNR is computed
|
import keras.backend as K
import numpy as np
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples."""
mse = K.mean(K.square(y_true - y_pred), axis=(-3, -2, -1))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10))
def ssim(y_true, y_pred):
"""structural similarity measurement system."""
## K1, K2 are two constants, much smaller than 1
K1 = 0.04
K2 = 0.06
## mean, std, correlation
mu_x = K.mean(y_pred)
mu_y = K.mean(y_true)
sig_x = K.std(y_pred)
sig_y = K.std(y_true)
sig_xy = (sig_x * sig_y) ** 0.5
## L, number of pixels, C1, C2, two constants
L = 33
C1 = (K1 * L) ** 2
C2 = (K2 * L) ** 2
ssim = (2 * mu_x * mu_y + C1) * (2 * sig_xy * C2) * 1.0 / ((mu_x ** 2 + mu_y ** 2 + C1) * (sig_x ** 2 + sig_y ** 2 + C2))
return ssim
|
import keras.backend as K
import numpy as np
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples and channels."""
mse = K.mean(K.square(y_true - y_pred), axis=(1, 2))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10))
def ssim(y_true, y_pred):
"""structural similarity measurement system."""
## K1, K2 are two constants, much smaller than 1
K1 = 0.04
K2 = 0.06
## mean, std, correlation
mu_x = K.mean(y_pred)
mu_y = K.mean(y_true)
sig_x = K.std(y_pred)
sig_y = K.std(y_true)
sig_xy = (sig_x * sig_y) ** 0.5
## L, number of pixels, C1, C2, two constants
L = 33
C1 = (K1 * L) ** 2
C2 = (K2 * L) ** 2
ssim = (2 * mu_x * mu_y + C1) * (2 * sig_xy * C2) * 1.0 / ((mu_x ** 2 + mu_y ** 2 + C1) * (sig_x ** 2 + sig_y ** 2 + C2))
return ssim
|
Add FT to test if angular is loaded
|
# -*- coding: utf-8 -*-
import unittest
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
@unittest.skip
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the title of the browser contains '18xx Accountant'
self.assertEqual(self.browser.title, '18xx Accountant')
# There is a button that says "Start new game", she clicks it
page = game.Homepage(self.browser)
self.assertEqual(page.start_button.text, 'Start new game')
page.start_button.click()
# She lands on a new page, it lists a code for the game name
self.assertIn('/en/game/', self.browser.current_url)
housekeeping = game.Housekeeping(self.browser)
self.assertEqual(len(housekeeping.game_name.text), 4)
def test_loads_angular_application(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the Angular 2 app has loaded
app = self.browser.find_element_by_tag_name('app-root')
self.assertIn('app works!', app.text)
|
# -*- coding: utf-8 -*-
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the title of the browser contains '18xx Accountant'
self.assertEqual(self.browser.title, '18xx Accountant')
# There is a button that says "Start new game", she clicks it
page = game.Homepage(self.browser)
self.assertEqual(page.start_button.text, 'Start new game')
page.start_button.click()
# She lands on a new page, it lists a code for the game name
self.assertIn('/en/game/', self.browser.current_url)
housekeeping = game.Housekeeping(self.browser)
self.assertEqual(len(housekeeping.game_name.text), 4)
|
Create a Serializer in the Constructor of Persistent Drivers
Rather than creating it on demand (which is not as intuitive).
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue\Driver;
use PMG\Queue\Envelope;
use PMG\Queue\Serializer\Serializer;
use PMG\Queue\Serializer\NativeSerializer;
/**
* Base class for drivers that deal with persistent backends. This provides
* some utilities for serialization.
*
* @since 2.0
*/
abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver
{
/**
* @var Serializer
*/
private $serializer;
public function __construct(Serializer $serializer=null)
{
$this->serializer = $serializer ?: static::createDefaultSerializer();
}
protected function serialize(Envelope $env)
{
return $this->getSerializer()->serialize($env);
}
protected function unserialize($data)
{
return $this->getSerializer()->unserialize($data);
}
protected function getSerializer()
{
return $this->serializer;
}
protected static function createDefaultSerializer()
{
return new NativeSerializer();
}
}
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue\Driver;
use PMG\Queue\Envelope;
use PMG\Queue\Serializer\Serializer;
use PMG\Queue\Serializer\NativeSerializer;
/**
* Base class for drivers that deal with persistent backends. This provides
* some utilities for serialization.
*
* @since 2.0
*/
abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver
{
/**
* @var Serializer
*/
private $serializer;
public function __construct(Serializer $serializer=null)
{
$this->serializer = $serializer;
}
protected function serialize(Envelope $env)
{
return $this->getSerializer()->serialize($env);
}
protected function unserialize($data)
{
return $this->getSerializer()->unserialize($data);
}
protected function getSerializer()
{
if (!$this->serializer) {
$this->serializer = new NativeSerializer();
}
return $this->serializer;
}
}
|
:bug: Use binary system instead of decimal for size error
|
export function isImage(file) {
if (file.type.split('/')[0] === 'image') {
return true;
}
}
export function convertBytesToMbsOrKbs(filesize) {
let size = '';
if (filesize >= 1048576) {
size = (filesize / 1048576) + ' megabytes';
} else if (filesize >= 1024) {
size = (filesize / 1024) + ' kilobytes';
} else {
size = filesize + ' bytes';
}
return size;
}
export async function createFileFromUrl(url) {
const response = await fetch(url);
const data = await response.blob();
const metadata = {type: data.type};
const filename = url.replace(/\?.+/, '').split('/').pop();
return new File([data], filename, metadata);
}
export function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event?.target?.result);
};
reader.onerror = (event) => {
reader.abort();
reject(event);
};
reader.readAsDataURL(file);
});
}
|
export function isImage(file) {
if (file.type.split('/')[0] === 'image') {
return true;
}
}
export function convertBytesToMbsOrKbs(filesize) {
let size = '';
// I know, not technically correct...
if (filesize >= 1000000) {
size = (filesize / 1000000) + ' megabytes';
} else if (filesize >= 1000) {
size = (filesize / 1000) + ' kilobytes';
} else {
size = filesize + ' bytes';
}
return size;
}
export async function createFileFromUrl(url) {
const response = await fetch(url);
const data = await response.blob();
const metadata = {type: data.type};
const filename = url.replace(/\?.+/, '').split('/').pop();
return new File([data], filename, metadata);
}
export function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event?.target?.result);
};
reader.onerror = (event) => {
reader.abort();
reject(event);
};
reader.readAsDataURL(file);
});
}
|
Fix no default; .controller is r/o
|
"use strict";
import Controller from "./Controller";
import View from "./View";
// private properties
const _controller = Symbol();
export default class ViewController extends View {
constructor(options = {}) {
super(options);
let {view} = options;
this[_controller] = new Controller(options);
if (view) { this.addSubview(view); }
}
get controller() {
return this[_controller];
}
get model() {
return this.controller && this.controller.model;
}
get view() {
return this.controller && this.controller.view;
}
destroy() {
if (this.controller) {
this.controller.destroy();
}
this[_controller] = null;
super.destroy();
}
}
|
"use strict";
import Controller from "./Controller";
import View from "./View";
// private properties
const _controller = Symbol();
export default class ViewController extends View {
constructor(options) {
super(options);
let {view} = options;
this[_controller] = new Controller(options);
if (view) { this.addSubview(view); }
}
get controller() {
return this[_controller];
}
get model() {
return this.controller && this.controller.model;
}
get view() {
return this.controller && this.controller.view;
}
destroy() {
if (this.controller) {
this.controller.destroy();
}
this.controller = null;
super.destroy();
}
}
|
Simplify datasets functions a bit
|
"""Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
URL = 'http://astrofrog.github.io/wcsaxes-datasets/'
def get_hdu(filename, cache=True):
path = download_file(URL + filename, cache=cache)
return fits.open(path)[0]
def msx_hdu(cache=True):
return get_hdu('msx.fits', cache=cache)
def rosat_hdu(cache=True):
return get_hdu('rosat.fits', cache=cache)
def twoMASS_k_hdu(cache=True):
return get_hdu('2MASS_k.fits', cache=cache)
def l1448_co_hdu(cache=True):
return get_hdu('L1448_13CO_subset.fits', cache=cache)
def bolocam_hdu(cache=True):
return get_hdu('bolocam_v2.0.fits', cache=cache)
|
"""Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
def msx_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/msx.fits", cache=cache)
return fits.open(filename)[0]
def rosat_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/rosat.fits", cache=cache)
return fits.open(filename)[0]
def twoMASS_k_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/2MASS_k.fits", cache=cache)
return fits.open(filename)[0]
def l1448_co_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/L1448_13CO_subset.fits", cache=cache)
return fits.open(filename)[0]
def bolocam_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/bolocam_v2.0.fits", cache=cache)
return fits.open(filename)[0]
|
Bug: Make fullmatch work on python 2.7.
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
Change title of meta transactions page in docs sidebar
|
#!/usr/bin/env node
const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');
const baseDir = process.argv[2];
const files = proc.execFileSync(
'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');
console.log('.API');
function getPageTitle (directory) {
if (directory === 'metatx') {
return 'Meta Transactions';
} else {
return startCase(directory);
}
}
const links = files.map((file) => {
const doc = file.replace(baseDir, '');
const title = path.parse(file).name;
return {
xref: `* xref:${doc}[${getPageTitle(title)}]`,
title,
};
});
// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});
for (const link of sortedLinks) {
console.log(link.xref);
}
|
#!/usr/bin/env node
const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');
const baseDir = process.argv[2];
const files = proc.execFileSync(
'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');
console.log('.API');
const links = files.map((file) => {
const doc = file.replace(baseDir, '');
const title = path.parse(file).name;
return {
xref: `* xref:${doc}[${startCase(title)}]`,
title,
};
});
// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});
for (const link of sortedLinks) {
console.log(link.xref);
}
|
Add strict mode to support generation script
|
'use strict'
var fs = require('fs'),
words = require('./');
fs.writeFileSync('Supported-words.md',
'Supported Words:\n' +
'=================\n' +
'\n' +
'| word | polarity | valence |\n' +
'|:----:|:--------:|:-------:|\n' +
Object.keys(words).map(function (word) {
var valence = words[word];
return '| ' + [
word,
valence > 0 ? ':smile:' : ':frowning:',
valence > 0 ? '+' + valence : valence
].join(' | ') + ' |';
}).join('\n') +
'\n'
);
|
var fs = require('fs'),
words = require('./');
fs.writeFileSync('Supported-words.md',
'Supported Words:\n' +
'=================\n' +
'\n' +
'| word | polarity | valence |\n' +
'|:----:|:--------:|:-------:|\n' +
Object.keys(words).map(function (word) {
var valence = words[word];
return '| ' + [
word,
valence > 0 ? ':smile:' : ':frowning:',
valence > 0 ? '+' + valence : valence
].join(' | ') + ' |';
}).join('\n') +
'\n'
);
|
Add query param support for getAll users request
|
<?php
namespace RIPS\Connector\Requests;
class UserRequests extends BaseRequest
{
// @var string
protected $uri = '/users';
/**
* Get all users
*
* @param array $queryParams
* @return array
*/
public function getAll(array $queryParams)
{
$response = $this->client->get($this->uri, [
'query' => $queryParams,
]);
return $this->handleResponse($response);
}
/**
* Get a user by user ID
*
* @param int $userId
* @return array
*/
public function getById(int $userId)
{
$response = $this->client->get("{$this->uri}/{$userId}");
return $this->handleResponse($response);
}
/**
* Invite a new user
*
* @param array $input
* @return array
*/
public function invite(array $input)
{
$response = $this->client->post("{$this->uri}/invite/ui", [
'form_params' => ['user' => $input],
]);
return $this->handleResponse($response);
}
}
|
<?php
namespace RIPS\Connector\Requests;
class UserRequests extends BaseRequest
{
// @var string
protected $uri = '/users';
/**
* Get all users
*
* @return array
*/
public function getAll()
{
$response = $this->client->get($this->uri);
return $this->handleResponse($response);
}
/**
* Get a user by user ID
*
* @param int $userId
* @return array
*/
public function getById(int $userId)
{
$response = $this->client->get("{$this->uri}/{$userId}");
return $this->handleResponse($response);
}
/**
* Invite a new user
*
* @param array $input
* @return array
*/
public function invite(array $input)
{
$response = $this->client->post("{$this->uri}/invite/ui", [
'form_params' => ['user' => $input],
]);
return $this->handleResponse($response);
}
}
|
Move process event listeners to top. Add 'exit' listener.
|
'use strict';
process.on('SIGINT', function() {
logger.notice('SIGINT received. Express server shutting down');
process.exit();
});
process.on('exit', function(code){
logger.warn('Node.js server exiting with error code: ' + code);
});
var express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
timeout = require('connect-timeout'),
port = process.env.PORT || 3000,
constants = require('./app/config/constants'),
config = require('./app/config/config'),
middleware = require('./app/scripts'),
routes = require('./app/routes'),
logger = require('./app/util/logger');
// Configure application
var app = express();
app.enable('trust proxy'); // required for nginx
app.use(middleware.requestLogger);
app.use(middleware.csrfHeader);
app.use(middleware.poweredByHeader);
app.use(bodyParser());
app.use(cookieParser());
app.use(timeout((config.timeout || 10) * 1000));
// Register routes
app.use(constants.LOCAL_PATH, routes.local);
app.use(constants.BASE_PATH, routes.services);
app.use(middleware.notFound);
app.use(middleware.error);
// Third party integrations
if (config.newRelicKey) {
require('newrelic');
}
// Start server
app.listen(port);
logger.notice('Express server listening on port ' + port);
|
'use strict';
var express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
timeout = require('connect-timeout'),
port = process.env.PORT || 3000,
constants = require('./app/config/constants'),
config = require('./app/config/config'),
middleware = require('./app/scripts'),
routes = require('./app/routes'),
logger = require('./app/util/logger');
// Configure application
var app = express();
app.enable('trust proxy'); // required for nginx
app.use(middleware.requestLogger);
app.use(middleware.csrfHeader);
app.use(middleware.poweredByHeader);
app.use(bodyParser());
app.use(cookieParser());
app.use(timeout((config.timeout || 10) * 1000));
// Register routes
app.use(constants.LOCAL_PATH, routes.local);
app.use(constants.BASE_PATH, routes.services);
app.use(middleware.notFound);
app.use(middleware.error);
// Third party integrations
if (config.newRelicKey) {
require('newrelic');
}
process.on('SIGINT', function() {
logger.notice('Express server shutting down');
process.exit();
});
// Start server
app.listen(port);
logger.notice('Express server listening on port ' + port);
|
Fix read the docs url.
|
#! /usr/bin/env python
# encoding: utf-8
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
name='pagseguro-sdk',
version="0.1.0",
description='SDK para utilização do PagSeguro em Python',
url='http://pagseguro-sdk.readthedocs.org/',
author='Jean O. Rodrigues',
author_email='github@jean.bz',
download_url='https://github.com/jeanmask/pagseguro-sdk/archive/v0.1.0.tar.gz',
license='MIT',
packages=['pagseguro'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
#! /usr/bin/env python
# encoding: utf-8
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
name='pagseguro-sdk',
version="0.1.0",
description='SDK para utilização do PagSeguro em Python',
url='https://pagseguro-sdk.readthedocs.com/',
author='Jean O. Rodrigues',
author_email='github@jean.bz',
download_url='https://github.com/jeanmask/pagseguro-sdk/archive/v0.1.0.tar.gz',
license='MIT',
packages=['pagseguro'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Add check to print_layer_shapes to fail explicitely on model used connected to other models.
|
from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to the model.
"""
# This is to handle the case where a model has been connected to a previous
# layer (and therefore get_input would recurse into previous layer's
# output).
if hasattr(model.layers[0], 'previous'):
# TODO: If the model is used as a part of another model, get_input will
# return the input of the whole model and this won't work. So this is
# not handled yet
raise Exception("This function doesn't work on model used as subparts "
" for other models")
input_var = model.get_input(train=False)
input_tmp = np.zeros(input_shape, dtype=np.float32)
print("input shape : ", input_shape)
for l in model.layers:
shape_f = theano.function([input_var], l.get_output(train=False).shape)
out_shape = shape_f(input_tmp)
print('shape after', l.get_config()['name'], ":", out_shape)
|
from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to the model.
"""
input_var = model.get_input(train=False)
input_tmp = np.zeros(input_shape, dtype=np.float32)
print("input shape : ", input_shape)
for l in model.layers:
shape_f = theano.function([input_var], l.get_output(train=False).shape)
out_shape = shape_f(input_tmp)
print('shape after', l.get_config()['name'], ":", out_shape)
|
Add ball speed and change move function
|
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var Ball = function(x, y, radius, context) {
this.x = x;
this.y = y;
this.radius = radius || 10;
this.startAngle = 0;
this.endAngle = (Math.PI / 180) * 360;
this.context = context
this.speed = 0
}
Ball.prototype.draw = function () {
context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle);
context.fillStyle = "white"
context.fill();
return this;
};
Ball.prototype.move = function () {
if (this.x < canvas.width - this.radius && this.y < canvas.height - this.radius ){
this.x += this.speed;
// this.y += this.speed;
}
return this;
};
var golfBall = new Ball(350, 450, 5, 0);
requestAnimationFrame(function gameLoop() {
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.closePath();
golfBall.draw().move();
requestAnimationFrame(gameLoop);
});
module.exports = Ball;
|
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var Ball = function(x, y, radius, context) {
this.x = x;
this.y = y;
this.radius = radius || 10;
this.startAngle = 0;
this.endAngle = (Math.PI / 180) * 360;
this.context = context
}
Ball.prototype.draw = function () {
context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle);
context.fillStyle = "white"
context.fill();
return this;
};
Ball.prototype.move = function () {
if (this.x < canvas.width - this.radius){
this.x++;
}
return this;
};
var golfBall = new Ball(350, 550, 5, 0);
requestAnimationFrame(function gameLoop() {
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.closePath();
golfBall.draw().move();
requestAnimationFrame(gameLoop);
});
module.exports = Ball;
|
Add some ways to get warnings.
|
var tap = require("tap")
var normalize = require("../lib/normalize")
var path = require("path")
var fs = require("fs")
var _ = require("underscore")
var async = require("async")
var data, clonedData
var warn
tap.test("consistent normalization", function(t) {
path.resolve(__dirname, "./fixtures/read-package-json.json")
fs.readdir (__dirname + "/fixtures", function (err, entries) {
// entries = ['coffee-script.json'] // uncomment to limit to a specific file
verifyConsistency = function(entryName, next) {
warn = function(msg) {
// t.equal("",msg) // uncomment to have some kind of logging of warnings
}
filename = __dirname + "/fixtures/" + entryName
fs.readFile(filename, function(err, contents) {
if (err) return next(err)
data = JSON.parse(contents.toString())
normalize(data, warn)
clonedData = _.clone(data)
normalize(data, warn)
t.deepEqual(clonedData, data,
"Normalization of " + entryName + "is consistent.")
next(null)
}) // fs.readFile
} // verifyConsistency
async.forEach(entries, verifyConsistency, function(err) {
if (err) throw err
t.end()
})
}) // fs.readdir
}) // tap.test
|
var tap = require("tap")
var normalize = require("../lib/normalize")
var path = require("path")
var fs = require("fs")
var _ = require("underscore")
var async = require("async")
var data, clonedData
tap.test("consistent normalization", function(t) {
path.resolve(__dirname, "./fixtures/read-package-json.json")
fs.readdir (__dirname + "/fixtures", function (err, entries) {
verifyConsistency = function(entryName, next) {
filename = __dirname + "/fixtures/" + entryName
fs.readFile(filename, function(err, contents) {
if (err) return next(err)
data = JSON.parse(contents.toString())
normalize(data)
clonedData = _.clone(data)
normalize(data)
t.deepEqual(data, clonedData,
"Normalization of " + entryName + "is consistent.")
next(null)
}) // fs.readFile
} // verifyConsistency
async.forEach(entries, verifyConsistency, function(err) {
if (err) throw err
t.end()
})
}) // fs.readdir
}) // tap.test
|
Correct name of package (for production).
|
# coding: utf-8
"""
A simple module to fetch Cavelink values by parsing the HTML page of sensors.
"""
from setuptools import find_packages, setup
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='cavelink',
version='1.1.0',
author='Sébastien Pittet',
author_email='sebastien@pittet.org',
description='Fetch Cavelink data by parsing the webpage of sensors.',
long_description=long_description,
url='https://github.com/SebastienPittet/cavelink',
keywords='speleo cave sensor',
packages=find_packages(),
license='MIT',
platforms='any',
install_requires=['python-dateutil', 'requests'],
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience'
]
)
|
# coding: utf-8
"""
A simple module to fetch Cavelink values by parsing the HTML page of sensors.
"""
from setuptools import find_packages, setup
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='example_cavelink',
version='1.1.0',
author='Sébastien Pittet',
author_email='sebastien@pittet.org',
description='Fetch Cavelink data by parsing the webpage of sensors.',
long_description=long_description,
url='https://github.com/SebastienPittet/cavelink',
keywords='speleo cave sensor',
packages=find_packages(),
license='MIT',
platforms='any',
install_requires=['python-dateutil', 'requests'],
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience'
]
)
|
BAP-9940: Create controller DELETE list action
Fix cs
|
<?php
namespace Oro\Bundle\ApiBundle\Processor;
use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
use Oro\Component\ChainProcessor\ProcessorBag;
class DeleteListProcessor extends RequestActionProcessor
{
/** @var ConfigProvider */
protected $configProvider;
/** @var MetadataProvider */
protected $metadataProvider;
/**
* @param ProcessorBag $processorBag
* @param string $action
* @param ConfigProvider $configProvider
* @param MetadataProvider $metadataProvider
*/
public function __construct(
ProcessorBag $processorBag,
$action,
ConfigProvider $configProvider,
MetadataProvider $metadataProvider
) {
parent::__construct($processorBag, $action);
$this->configProvider = $configProvider;
$this->metadataProvider = $metadataProvider;
}
/**
* {@inheritdoc}
*/
protected function createContextObject()
{
return new DeleteListContext($this->configProvider, $this->metadataProvider);
}
}
|
<?php
namespace Oro\Bundle\ApiBundle\Processor;
use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
use Oro\Component\ChainProcessor\ProcessorBag;
class DeleteListProcessor extends RequestActionProcessor
{
/** @var ConfigProvider */
protected $configProvider;
/** @var MetadataProvider */
protected $metadataProvider;
/**
* @param ProcessorBag $processorBag
* @param string $action
* @param ConfigProvider $configProvider
* @param MetadataProvider $metadataProvider
*/
public function __construct(
ProcessorBag $processorBag,
$action,
ConfigProvider $configProvider,
MetadataProvider $metadataProvider
) {
parent::__construct($processorBag, $action);
$this->configProvider = $configProvider;
$this->metadataProvider = $metadataProvider;
}
/**
* {@inheritdoc}
*/
protected function createContextObject()
{
return new DeleteListContext($this->configProvider, $this->metadataProvider);
}
}
|
Fix end to end testing by increasing mocha timeout (again)
Signed-off-by: Joe Walker <7a17872fbb32c7d760c9a16ee3076daead11efcf@mozilla.com>
|
/* eslint prefer-arrow-callback: 0 */
import expect from 'expect';
import { Application } from 'spectron';
import { quickTest } from '../../build-config';
import { getBuiltExecutable } from '../../build/utils';
describe('application launch', function() {
if (quickTest) {
it.skip('all tests');
return;
}
this.timeout(30000);
const executable = getBuiltExecutable();
beforeEach(function() {
this.app = new Application({
path: executable.fullPath,
cwd: executable.cwd,
env: process.env,
});
return this.app.start();
});
it('shows an initial window', async function() {
const count = await this.app.client.getWindowCount();
expect(count).toEqual(1);
});
afterEach(function() {
if (this.app && this.app.isRunning()) {
return this.app.stop();
}
return undefined;
});
});
|
/* eslint prefer-arrow-callback: 0 */
import expect from 'expect';
import { Application } from 'spectron';
import { quickTest } from '../../build-config';
import { getBuiltExecutable } from '../../build/utils';
describe('application launch', function() {
if (quickTest) {
it.skip('all tests');
return;
}
this.timeout(20000);
const executable = getBuiltExecutable();
beforeEach(function() {
this.app = new Application({
path: executable.fullPath,
cwd: executable.cwd,
env: process.env,
});
return this.app.start();
});
it('shows an initial window', async function() {
const count = await this.app.client.getWindowCount();
expect(count).toEqual(1);
});
afterEach(function() {
if (this.app && this.app.isRunning()) {
return this.app.stop();
}
return undefined;
});
});
|
Handle expired projects in join lookup
If a project is expired, notify the user but do not carry on to the
join-this-project page.
|
function show_lookup_error(msg) {
$('#finderror').append(msg);
$('#findname').select();
}
function handle_lookup(data) {
if (data.code == 0) {
// Project lookup was successful
// redirect to join-this-project.php?project_id=id
// get project from value field, and project_id from that
var project = data.value
if (project.expired) {
show_lookup_error("Project " + project.project_name + " has expired.");
} else {
var url = "join-this-project.php?project_id=" + project.project_id;
window.location.href = url;
}
} else {
// Handle error case
show_lookup_error(data.output);
}
}
function handle_error(jqXHR, textStatus, errorThrown) {
// An unknown error has occurred. Pop up a dialog box.
alert("An unknown error occurred.");
}
function lookup_project(project_name) {
// Clear out any previous errors
$('#finderror').empty();
var lookup_url = "/secure/lookup-project.php"
var data = {name: project_name}
$.post(lookup_url, data, handle_lookup, 'json').fail(handle_error);
}
function do_lookup_project(event) {
event.preventDefault();
lookup_project($('#findname').val());
}
$(document).ready( function () {
/* datatables.net (for sortable/searchable tables) */
$('#projects').DataTable({paging: false});
$('#findbtn').click(do_lookup_project);
} );
|
function handle_lookup(data) {
if (data.code == 0) {
// Project lookup was successful
// redirect to join-this-project.php?project_id=id
// get project from value field, and project_id from that
var project = data.value
var url = "join-this-project.php?project_id=" + project.project_id;
window.location.href = url;
} else {
// Handle error case
$('#finderror').append(data.output);
$('#findname').select();
}
}
function handle_error(jqXHR, textStatus, errorThrown) {
// An unknown error has occurred. Pop up a dialog box.
alert("An unknown error occurred.");
}
function lookup_project(project_name) {
// Clear out any previous errors
$('#finderror').empty();
var lookup_url = "/secure/lookup-project.php"
var data = {name: project_name}
$.post(lookup_url, data, handle_lookup, 'json').fail(handle_error);
}
function do_lookup_project(event) {
event.preventDefault();
lookup_project($('#findname').val());
}
$(document).ready( function () {
/* datatables.net (for sortable/searchable tables) */
$('#projects').DataTable({paging: false});
$('#findbtn').click(do_lookup_project);
} );
|
Create test database in memory.
|
"""
Test settings for ``eventkit`` app.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django_nose',
'eventkit',
'eventkit.tests',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'eventkit.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Default: django.test.runner.DiscoverRunner
TIME_ZONE = 'Australia/Sydney' # Default: America/Chicago
USE_TZ = True # Default: False
# DYNAMIC FIXTURES ############################################################
DDF_FILL_NULLABLE_FIELDS = False
|
"""
Test settings for ``eventkit`` app.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django_nose',
'eventkit',
'eventkit.tests',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'eventkit.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Default: django.test.runner.DiscoverRunner
TIME_ZONE = 'Australia/Sydney' # Default: America/Chicago
USE_TZ = True # Default: False
# DYNAMIC FIXTURES ############################################################
DDF_FILL_NULLABLE_FIELDS = False
|
Check the warning "type" correctly for SSL warnings
After some refactoring work, the SSL warning JS code was no longer
checking the warning "type" correctly. This CL fixes that.
BUG=418851
Review URL: https://codereview.chromium.org/616743002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#297393}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Should match SSLBlockingPageCommands in ssl_blocking_page.cc.
var SSL_CMD_DONT_PROCEED = 0;
var SSL_CMD_PROCEED = 1;
var SSL_CMD_MORE = 2;
var SSL_CMD_RELOAD = 3;
var SSL_CMD_HELP = 4;
var SSL_CMD_CLOCK = 5;
function setupSSLDebuggingInfo() {
if (!loadTimeData.getString('type') == 'SSL')
return;
// The titles are not internationalized because this is debugging information
// for bug reports, help center posts, etc.
appendDebuggingField('Subject', loadTimeData.getString('subject'));
appendDebuggingField('Issuer', loadTimeData.getString('issuer'));
appendDebuggingField('Expires on', loadTimeData.getString('expirationDate'));
appendDebuggingField('Current date', loadTimeData.getString('currentDate'));
appendDebuggingField('PEM encoded chain', loadTimeData.getString('pem'));
$('error-code').addEventListener('click', toggleDebuggingInfo);
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Should match SSLBlockingPageCommands in ssl_blocking_page.cc.
var SSL_CMD_DONT_PROCEED = 0;
var SSL_CMD_PROCEED = 1;
var SSL_CMD_MORE = 2;
var SSL_CMD_RELOAD = 3;
var SSL_CMD_HELP = 4;
var SSL_CMD_CLOCK = 5;
function setupSSLDebuggingInfo() {
if (!loadTimeData.getBoolean('ssl'))
return;
// The titles are not internationalized because this is debugging information
// for bug reports, help center posts, etc.
appendDebuggingField('Subject', loadTimeData.getString('subject'));
appendDebuggingField('Issuer', loadTimeData.getString('issuer'));
appendDebuggingField('Expires on', loadTimeData.getString('expirationDate'));
appendDebuggingField('Current date', loadTimeData.getString('currentDate'));
appendDebuggingField('PEM encoded chain', loadTimeData.getString('pem'));
$('error-code').addEventListener('click', toggleDebuggingInfo);
}
|
Check that class is instantiated correctly
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.crypto.random;
import static org.junit.Assert.fail;
import java.security.GeneralSecurityException;
import java.util.Properties;
import org.apache.commons.crypto.conf.ConfigurationKeys;
public class TestOsCryptoRandom extends AbstractRandomTest {
@Override
public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
Properties props = new Properties();
props.setProperty(
ConfigurationKeys.SECURE_RANDOM_CLASSES_KEY,
OsCryptoRandom.class.getName());
CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
if (!(random instanceof OsCryptoRandom)) {
fail("The CryptoRandom should be: "
+ OsCryptoRandom.class.getName());
}
return random;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.crypto.random;
import java.util.Properties;
public class TestOsCryptoRandom extends AbstractRandomTest {
@Override
public CryptoRandom getCryptoRandom() {
return new OsCryptoRandom(new Properties());
}
}
|
Stop writing generated code unnecessarily
|
import pyxb.binding.generate
import pyxb.binding.datatypes as xs
import pyxb.binding.basis
import pyxb.utils.domutils
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="structure">
<xs:complexType><xs:anyAttribute processContents="lax"/></xs:complexType>
</xs:element>
</xs:schema>'''
#file('schema.xsd', 'w').write(xsd)
code = pyxb.binding.generate.GeneratePython(schema_text=xsd)
#file('code.py', 'w').write(code)
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
AttributeNamespace = pyxb.namespace.NamespaceInstance('URN:attr:200908231005')
class TestTrac_200908231005 (unittest.TestCase):
def testParsing (self):
xmls = '<structure xmlns:attr="%s" attr:field="value"/>' % (AttributeNamespace.uri(),)
instance = CreateFromDocument(xmls)
wam = instance.wildcardAttributeMap()
self.assertEqual(1, len(wam))
self.assertEqual('value', wam.get(AttributeNamespace.createExpandedName('field')))
if __name__ == '__main__':
unittest.main()
|
import pyxb.binding.generate
import pyxb.binding.datatypes as xs
import pyxb.binding.basis
import pyxb.utils.domutils
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="structure">
<xs:complexType><xs:anyAttribute processContents="lax"/></xs:complexType>
</xs:element>
</xs:schema>'''
#file('schema.xsd', 'w').write(xsd)
code = pyxb.binding.generate.GeneratePython(schema_text=xsd)
file('code.py', 'w').write(code)
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
AttributeNamespace = pyxb.namespace.NamespaceInstance('URN:attr:200908231005')
class TestTrac_200908231005 (unittest.TestCase):
def testParsing (self):
xmls = '<structure xmlns:attr="%s" attr:field="value"/>' % (AttributeNamespace.uri(),)
instance = CreateFromDocument(xmls)
wam = instance.wildcardAttributeMap()
self.assertEqual(1, len(wam))
self.assertEqual('value', wam.get(AttributeNamespace.createExpandedName('field')))
if __name__ == '__main__':
unittest.main()
|
Expand single-trial plot to include multiple subjects.
|
import climate
import lmj.plot
import source
import plots
@climate.annotate(
subjects='plot data from these subjects',
marker=('plot data for this mocap marker', 'option'),
trial_num=('plot data for this trial', 'option', None, int),
)
def main(marker='r-fing-index', trial_num=0, *subjects):
with plots.space() as ax:
for i, subject in enumerate(subjects):
subj = source.Subject(subject)
for b in subj.blocks:
trial = b.trials[trial_num]
trial.load()
x, y, z = trial.marker(marker)
ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7)
if __name__ == '__main__':
climate.call(main)
|
import climate
import lmj.plot
import source
def main(subject):
subj = source.Subject(subject)
trial = subj.blocks[0].trials[0]
trial.load()
ax = lmj.plot.axes(111, projection='3d', aspect='equal')
x, y, z = trial.marker('r-fing-index')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('l-fing-index')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('r-heel')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('l-heel')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('r-knee')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('l-knee')
ax.plot(x, z, zs=y)
lmj.plot.show()
if __name__ == '__main__':
climate.call(main)
|
Fix queries that don't use parameters
|
<?php
App::uses('Model', 'Model');
/**
* A standard CakePHP AppModel with the find method overriden.
* The code from it should be put in app/Model/AppModel.php
*/
class AppModel extends Model {
/**
* Instance of the Cacher object, so we don't have to create it on every call
*
* @var object Cacher instance
*/
protected $_Cacher = null;
/**
* Overrides Model::find to transparently load data from cache
*/
public function find($type, $params = array(), $useCache = true) {
if ($useCache && $this->Behaviors->enabled('Cacheable')){
if (!isset($this->_Cacher)) {
App::import('Model', 'Cacher.Cacher');
$this->_Cacher = new Cacher;
}
return $this->_Cacher->find($this, $type, $params);
} else {
return parent::find($type, $params);
}
}
}
|
<?php
App::uses('Model', 'Model');
/**
* A standard CakePHP AppModel with the find method overriden.
* The code from it should be put in app/Model/AppModel.php
*/
class AppModel extends Model {
/**
* Instance of the Cacher object, so we don't have to create it on every call
*
* @var object Cacher instance
*/
protected $_Cacher = null;
/**
* Overrides Model::find to transparently load data from cache
*/
public function find($type, $params, $useCache = true) {
if ($useCache && $this->Behaviors->enabled('Cacheable')){
if (!isset($this->_Cacher)) {
App::import('Model', 'Cacher.Cacher');
$this->_Cacher = new Cacher;
}
return $this->_Cacher->find($this, $type, $params);
} else {
return parent::find($type, $params);
}
}
}
|
Update to make sure we log an error with an invalid key
|
"""Handle auth and authz activities in bookie"""
import logging
from pyramid.httpexceptions import HTTPForbidden
LOG = logging.getLogger(__name__)
class Authorize(object):
"""Context manager to check if the user is authorized
use:
with Authorize(some_key):
# do work
Will return NotAuthorized if it fails
"""
def __init__(self, submitted_key, config_key):
"""Create the context manager"""
self.api_key = config_key
self.check_key = submitted_key
def __enter__(self):
"""Verify api key set in constructor"""
if self.api_key != self.check_key:
LOG.error('Invalid API Key! {0} v {1}'.format(self.api_key,
self.check_key))
raise HTTPForbidden('Invalid Authorization')
def __exit__(self, exc_type, exc_value, traceback):
"""No cleanup work to do after usage"""
pass
|
"""Handle auth and authz activities in bookie"""
from pyramid.httpexceptions import HTTPForbidden
class Authorize(object):
"""Context manager to check if the user is authorized
use:
with Authorize(some_key):
# do work
Will return NotAuthorized if it fails
"""
def __init__(self, submitted_key, config_key):
"""Create the context manager"""
self.api_key = config_key
self.check_key = submitted_key
def __enter__(self):
"""Verify api key set in constructor"""
if self.api_key != self.check_key:
raise HTTPForbidden('Invalid Authorization')
def __exit__(self, exc_type, exc_value, traceback):
"""No cleanup work to do after usage"""
pass
|
Remove code for pingPong, leaving pingPongType and isPingPong as functions
|
var pingPongType = function(i) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
return pingPongType(i);
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (isPingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
|
var pingPong = function(i) {
if (isPingPong(i)) {
return pingPongType(i)
} else {
return false;
}
}
var pingPongType = function(i) {
if ((i % 3 === 0) && (i % 5 != 0)) {
return "ping";
} else if ((i % 5 === 0) && (i % 3 !=0)) {
return "pong";
} else if (i % 15 === 0){
return "pingpong";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)){
return true;
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (pingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
|
Add factory method for creating the service container
|
<?php
namespace Noback\PHPUnitTestServiceContainer\PHPUnit;
use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;
/**
* Extend from this test case to make use of a service container in your tests
*/
abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase
{
/**
* @var ServiceContainerInterface
*/
protected $container;
/**
* Return an array of ServiceProviderInterface instances you want to use in this test case
*
* @return ServiceProviderInterface[]
*/
abstract protected function getServiceProviders();
/**
* When overriding this method, make sure you call parent::setUp()
*/
protected function setUp()
{
$this->container = $this->createServiceContainer();
$this->container->setUp();
}
protected function createServiceContainer()
{
$container = new ServiceContainer();
foreach ($this->getServiceProviders() as $serviceProvider) {
$container->register($serviceProvider);
}
return $container;
}
/**
* When overriding this method, make sure you call parent::tearDown()
*/
protected function tearDown()
{
$this->container->tearDown();
$this->container = null;
}
}
|
<?php
namespace Noback\PHPUnitTestServiceContainer\PHPUnit;
use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;
/**
* Extend from this test case to make use of a service container in your tests
*/
abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase
{
/**
* @var ServiceContainerInterface
*/
protected $container;
/**
* Return an array of ServiceProviderInterface instances you want to use in this test case
*
* @return ServiceProviderInterface[]
*/
abstract protected function getServiceProviders();
/**
* When overriding this method, make sure you call parent::setUp()
*/
protected function setUp()
{
$this->container = new ServiceContainer();
foreach ($this->getServiceProviders() as $serviceProvider) {
$this->container->register($serviceProvider);
}
}
/**
* When overriding this method, make sure you call parent::tearDown()
*/
protected function tearDown()
{
$this->container->tearDown();
$this->container = null;
}
}
|
Set up exp time for JWT
|
import * as m from '../models'
import parse from 'co-body'
import jwt from 'koa-jwt'
import {JWT_KEY} from '../config'
export default ({api}) => {
api.post('/auth', async ctx => {
const body = await parse.json(ctx)
try {
if (!body.username) throw new Error('Username is required')
if (!body.password) throw new Error('Password is required')
const user = await m.User.findOne({_id: body.username})
if (!user) ctx.throw(401, 'Wrong username or password. Login failed')
const isValidPw = await user.checkPassword(body.password)
if (!isValidPw) ctx.throw(401, 'Wrong username or password. Login failed')
const usertoken = jwt.sign(
{username: body.username, role: 'user'}, JWT_KEY, {expiresIn: '1h'}
)
ctx.status = 200
ctx.body = {
usertoken, username: body.username, exp: jwt.decode(usertoken).exp
}
} catch (err) {
ctx.throw(400, err)
}
})
return api
}
|
import * as m from '../models'
import parse from 'co-body'
import jwt from 'koa-jwt'
import {JWT_KEY} from '../config'
export default ({api}) => {
api.post('/auth', async ctx => {
const body = await parse.json(ctx)
try {
if (!body.username) throw new Error('Username is required')
if (!body.password) throw new Error('Password is required')
const user = await m.User.findOne({_id: body.username})
if (!user) ctx.throw(401, 'Wrong username or password. Login failed')
const isValidPw = await user.checkPassword(body.password)
if (!isValidPw) ctx.throw(401, 'Wrong username or password. Login failed')
ctx.status = 200
ctx.body = {
usertoken: jwt.sign({username: body.username, role: 'user'}, JWT_KEY),
username: body.username
}
} catch (err) {
ctx.throw(400, err)
}
})
return api
}
|
Add hash to bundle filename
|
var webpack = require("webpack")
var HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// devtool: "eval", // Transformed code
devtool: "source-map", // Original code
entry: {
bench: "./src/index.js",
},
output: {
filename: "[name]-bundle-[hash].js",
path: __dirname + "/dist",
},
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: ["babel-loader"],
},
{
test: /\.json$/,
exclude: /node_modules/,
loaders: ["json-loader"],
},
],
},
plugins: [
new webpack.ProvidePlugin({
React: "react", // For babel JSX transformation which generates React.createElement.
}),
new HtmlWebpackPlugin({title: "OpenChordCharts sample data bench"}),
],
resolve: {
extensions: ["", ".js", ".jsx"],
},
}
|
var webpack = require("webpack")
var HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// devtool: "eval", // Transformed code
devtool: "source-map", // Original code
entry: {
bench: "./src/index.js",
},
output: {
filename: "[name].js",
path: __dirname + "/dist",
},
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: ["babel-loader"],
},
{
test: /\.json$/,
exclude: /node_modules/,
loaders: ["json-loader"],
},
],
},
plugins: [
new webpack.ProvidePlugin({
React: "react", // For babel JSX transformation which generates React.createElement.
}),
new HtmlWebpackPlugin({title: "OpenChordCharts sample data bench"}),
],
resolve: {
extensions: ["", ".js", ".jsx"],
},
}
|
Fix Mercurial "Last Modified" query
Summary:
To determine when a file was last modified, we currently run `hg log ... -b branch ... file`. However, this is incorrect, because Mercurial does not interpret "-b x" as "all ancestors of the commit named x" like Git does, and we don't care about where the modification happened anyway (we always have a resolved commit as a starting point). I think this got copy-pasta'd from the History query.
Instead, drop the branch-specific qualifier and find the last modification, period.
Test Plan: Mercurial commit views of commits not on the repository's default branch are no longer broken.
Reviewers: DurhamGoode, vrana, chad
Reviewed By: chad
CC: aran
Differential Revision: https://secure.phabricator.com/D5146
|
<?php
final class DiffusionMercurialLastModifiedQuery
extends DiffusionLastModifiedQuery {
protected function executeQuery() {
$drequest = $this->getRequest();
$repository = $drequest->getRepository();
$path = $drequest->getPath();
list($hash) = $repository->execxLocalCommand(
'log --template %s --limit 1 --rev %s:0 -- %s',
'{node}',
$drequest->getCommit(),
nonempty(ltrim($path, '/'), '.'));
$commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
'repositoryID = %d AND commitIdentifier = %s',
$repository->getID(),
$hash);
if ($commit) {
$commit_data = $commit->loadCommitData();
} else {
$commit_data = null;
}
return array($commit, $commit_data);
}
}
|
<?php
final class DiffusionMercurialLastModifiedQuery
extends DiffusionLastModifiedQuery {
protected function executeQuery() {
$drequest = $this->getRequest();
$repository = $drequest->getRepository();
$path = $drequest->getPath();
// TODO: Share some of this with History query.
list($hash) = $repository->execxLocalCommand(
'log --template %s --limit 1 -b %s --rev %s:0 -- %s',
'{node}',
$drequest->getBranch(),
$drequest->getCommit(),
nonempty(ltrim($path, '/'), '.'));
$commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
'repositoryID = %d AND commitIdentifier = %s',
$repository->getID(),
$hash);
if ($commit) {
$commit_data = $commit->loadCommitData();
} else {
$commit_data = null;
}
return array($commit, $commit_data);
}
}
|
Add non-breaking spaces to navigation bar
|
/**
*
* Nav.react.js
*
* This component renders the navigation bar
*
*/
import React, { Component } from 'react';
import { Link } from 'react-router';
import { logout } from '../actions/AppActions';
import LoadingIndicator from './LoadingIndicator.react';
class Nav extends Component {
render() {
// Render either the Log In and register buttons, or the logout button
// based on the current authentication state.
const navButtons = this.props.loggedIn ? (
<a href="#" className="btn btn--login btn--nav" onClick={::this._logout}>{this.props.currentlySending ? <LoadingIndicator /> : "Logout"}</a>
) : (
<div>
<Link to="/register" className="btn btn--login btn--nav">Register</Link>
<Link to="/login" className="btn btn--login btn--nav">Log In</Link>
</div>
);
return(
<div className="nav">
<div className="nav__wrapper">
<Link to="/" className="nav__logo-wrapper"><h1 className="nav__logo">Login Flow</h1></Link>
{ navButtons }
</div>
</div>
);
}
_logout() {
this.props.dispatch(logout());
}
}
Nav.propTypes = {
loggedIn: React.PropTypes.bool.isRequired
}
export default Nav;
|
/**
*
* Nav.react.js
*
* This component renders the navigation bar
*
*/
import React, { Component } from 'react';
import { Link } from 'react-router';
import { logout } from '../actions/AppActions';
import LoadingIndicator from './LoadingIndicator.react';
class Nav extends Component {
render() {
// Render either the Log In and register buttons, or the logout button
// based on the current authentication state.
const navButtons = this.props.loggedIn ? (
<a href="#" className="btn btn--login btn--nav" onClick={::this._logout}>{this.props.currentlySending ? <LoadingIndicator /> : "Logout"}</a>
) : (
<div>
<Link to="/register" className="btn btn--login btn--nav">Register</Link>
<Link to="/login" className="btn btn--login btn--nav">Log In</Link>
</div>
);
return(
<div className="nav">
<div className="nav__wrapper">
<Link to="/" className="nav__logo-wrapper"><h1 className="nav__logo">Login Flow</h1></Link>
{ navButtons }
</div>
</div>
);
}
_logout() {
this.props.dispatch(logout());
}
}
Nav.propTypes = {
loggedIn: React.PropTypes.bool.isRequired
}
export default Nav;
|
Use str methods instead of string module
|
"""
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a Docker image matches the given specification type
login Log in to a biobox container with mounted test data
Biobox types:
short_read_assembler Assemble short reads into contigs
"""
import sys
from fn import F
import biobox_cli.util.misc as util
import biobox_cli.util.functional as fn
def run():
args = input_args()
opts = util.parse_docopt(__doc__, args, True)
util.select_module("command", opts["<command>"]).run(args)
def input_args():
"""
Get command line args excluding those consisting of only whitespace
"""
return fn.thread([
sys.argv[1:],
F(map, str.strip),
F(filter, fn.is_not_empty)])
|
"""
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a Docker image matches the given specification type
login Log in to a biobox container with mounted test data
Biobox types:
short_read_assembler Assemble short reads into contigs
"""
import sys, string
from fn import F
import biobox_cli.util.misc as util
import biobox_cli.util.functional as fn
def run():
args = input_args()
opts = util.parse_docopt(__doc__, args, True)
util.select_module("command", opts["<command>"]).run(args)
def input_args():
"""
Get command line args excluding those consisting of only whitespace
"""
return fn.thread([
sys.argv[1:],
F(map, string.strip),
F(filter, fn.is_not_empty)])
|
Check for eslint instead of jshint
|
/*global describe, before, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('angular with gulp and browserify generator', function () {
before(function(done) {
helpers.run(path.join(__dirname, '../generators/app'))
.withOptions({
skipInstall: true,
})
.withPrompts({
appname: 'temp'
})
.on('end', done);
});
it('it should create dotfiles files', function () {
assert.file([
'package.json',
'gulpfile.babel.js',
'.eslintrc',
'.gitignore'
]);
});
it('it should create nested files and folders', function () {
assert.file([
'app/index.html',
'app/js/main.js',
'app/js/controllers/index.js',
'gulp/index.js',
'gulp/tasks/browserify.js',
'test/karma.conf.js',
'test/e2e/example_spec.js',
'test/unit/controllers/example_spec.js'
]);
});
it('should generate correct package.json', function () {
assert.fileContent('package.json', /"name": "temp"/);
assert.noFileContent('package.json', /"author":/);
});
});
|
/*global describe, before, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('angular with gulp and browserify generator', function () {
before(function(done) {
helpers.run(path.join(__dirname, '../generators/app'))
.withOptions({
skipInstall: true,
})
.withPrompts({
appname: 'temp'
})
.on('end', done);
});
it('it should create dotfiles files', function () {
assert.file([
'package.json',
'gulpfile.babel.js',
'.jshintrc',
'.gitignore'
]);
});
it('it should create nested files and folders', function () {
assert.file([
'app/index.html',
'app/js/main.js',
'app/js/controllers/index.js',
'gulp/index.js',
'gulp/tasks/browserify.js',
'test/karma.conf.js',
'test/e2e/example_spec.js',
'test/unit/controllers/example_spec.js'
]);
});
it('should generate correct package.json', function () {
assert.fileContent('package.json', /"name": "temp"/);
assert.noFileContent('package.json', /"author":/);
});
});
|
Add debug tool to view particle count
|
// A bit of pseudo-code
//
// tickModel
// var dt
// for each canvas
// canvasParticles = canvasParticles.filterOut(particlesOutsideOrTimeout)
//
// for each particle in canvasParticles
// tick(particle)
//
// for each startOptions
// var newParticles = createParticles(imageUrls, startOptions, dt)
// canvasParticles = [].concat(canvasParticles, newParticles)
//
// tickView
// drawCanvas(canvasId, loadedImages, canvasParticles)
//
var tickState = require('./tickState')
var drawState = require('./drawState')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// DEBUG
// console.log('num of particles', state.canvases.reduce(function (acc, c) {
// return c.waves.reduce((ac, w) => {
// return ac + w.particles.length
// }, acc)
// }, 0))
// Draw; View current model
drawState(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
|
// A bit of pseudo-code
//
// tickModel
// var dt
// for each canvas
// canvasParticles = canvasParticles.filterOut(particlesOutsideOrTimeout)
//
// for each particle in canvasParticles
// tick(particle)
//
// for each startOptions
// var newParticles = createParticles(imageUrls, startOptions, dt)
// canvasParticles = [].concat(canvasParticles, newParticles)
//
// tickView
// drawCanvas(canvasId, loadedImages, canvasParticles)
//
var tickState = require('./tickState')
var drawState = require('./drawState')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// Draw; View current model
drawState(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
|
Add CDN url to allowed hosts.
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
Fix bug in validation method
|
const validate = (values) => {
const errors = {};
if (!values.title || values.title.trim() === '') {
errors.title = 'Book title is required';
}
if (!values.author || values.author.trim() === '') {
errors.author = 'Book author is required';
}
if (!values.description || values.description.trim() === '') {
errors.description = 'Book description is required';
}
if (!values.subject) {
errors.subject = 'Book subject is required';
}
if (!values.description || values.description.trim() === '') {
errors.description = 'Book description is required';
}
if (!values.imageURL || values.imageURL.trim() === '') {
errors.imageURL = 'ImageURL is required';
}
if (!values.quantity) {
errors.quantity = 'quantity is required';
}
if (values.quantity && values.quantity <= 0) {
errors.quantity = 'quantity must be greater than 0';
}
return errors;
};
export default validate;
|
const validate = (values) => {
const errors = {};
if (!values.title || values.title.trim() === '') {
errors.title = 'Book title is required';
}
if (!values.author || values.author.trim() === '') {
errors.author = 'Book author is required';
}
if (!values.description || values.description.trim() === '') {
errors.description = 'Book description is required';
}
if (!values.subject) {
errors.subject = 'Book subject is required';
}
if (!values.description || values.description.trim() === '') {
errors.description = 'Book description is required';
}
if (!values.imageURL || values.imageURL.trim() === '') {
errors.imageURL = 'ImageURL is required';
}
if (!values.quantity || values.quantity.trim() === '') {
errors.quantity = 'quantity is required';
}
if (values.quantity && values.quantity <= 0) {
errors.quantity = 'quantity must be greater than 0';
}
return errors;
};
export default validate;
|
FIX Add namespace import for Member
|
<?php
namespace SilverStripe\ContentReview\Models;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ORM\DataObject;
use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
class ContentReviewLog extends DataObject
{
/**
* @var array
*/
private static $db = array(
"Note" => "Text",
);
/**
* @var array
*/
private static $has_one = array(
"Reviewer" => Member::class,
"SiteTree" => SiteTree::class,
);
/**
* @var array
*/
private static $summary_fields = array(
"Note" => array("title" => "Note"),
"Created" => array("title" => "Reviewed at"),
"Reviewer.Title" => array("title" => "Reviewed by"),
);
/**
* @var string
*/
private static $default_sort = "Created DESC";
private static $table_name = 'ContentReviewLog';
/**
* @param mixed $member
*
* @return bool
*/
public function canView($member = null)
{
return (bool) Security::getCurrentUser();
}
}
|
<?php
namespace SilverStripe\ContentReview\Models;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ORM\DataObject;
use SilverStripe\Security\Security;
class ContentReviewLog extends DataObject
{
/**
* @var array
*/
private static $db = array(
"Note" => "Text",
);
/**
* @var array
*/
private static $has_one = array(
"Reviewer" => Member::class,
"SiteTree" => SiteTree::class,
);
/**
* @var array
*/
private static $summary_fields = array(
"Note" => array("title" => "Note"),
"Created" => array("title" => "Reviewed at"),
"Reviewer.Title" => array("title" => "Reviewed by"),
);
/**
* @var string
*/
private static $default_sort = "Created DESC";
private static $table_name = 'ContentReviewLog';
/**
* @param mixed $member
*
* @return bool
*/
public function canView($member = null)
{
return (bool) Security::getCurrentUser();
}
}
|
Watch also files in grunt/
|
/*
* WATCH: Run predefined tasks whenever watched file patterns are added, changed or deleted
*/
module.exports = {
options: {
spawn: false,
livereload: true
},
/*
* TARGET: Build Bolts css file changes
*/
boltCss: {
files: [
'<%= path.src.sass %>/**/*.scss'
],
tasks: [
'sass:boltCss'
]
},
/*
* TARGET: Build Bolts js file changes
*/
boltJs: {
files: '<%= files.boltJs %>',
tasks: [
'jshint:boltJs',
'uglify:boltJs'
]
},
/*
* TARGET: Watch Gruntfile changes and then reload
*/
gruntfile: {
files: [
'Gruntfile.js',
'grunt/*.js',
'grunt/*.yml'
],
options: {
reload: true
}
}
};
|
/*
* WATCH: Run predefined tasks whenever watched file patterns are added, changed or deleted
*/
module.exports = {
options: {
spawn: false,
livereload: true
},
/*
* TARGET: Build Bolts css file changes
*/
boltCss: {
files: [
'<%= path.src.sass %>/**/*.scss'
],
tasks: [
'sass:boltCss'
]
},
/*
* TARGET: Build Bolts js file changes
*/
boltJs: {
files: '<%= files.boltJs %>',
tasks: [
'jshint:boltJs',
'uglify:boltJs'
]
},
/*
* TARGET: Watch Gruntfile changes and then reload
*/
gruntfile: {
files: [
'Gruntfile.js'
],
options: {
reload: true
}
}
};
|
Change the scope of events inside calendar.
|
<?php
namespace Plummer\Calendar;
abstract class CalendarAbstract implements CalendarInterface, \IteratorAggregate
{
protected $name;
private $events;
protected $recurrenceTypes;
public function __construct($name)
{
$this->name = $name;
}
public function addEvents($events)
{
foreach($events as $key => $event) {
$this->events[$key] = $event;
}
}
public function addRecurrenceTypes($recurrenceTypes)
{
foreach($recurrenceTypes as $key => $recurrenceType) {
$this->recurrenceTypes[$key] = $recurrenceType;
}
}
public function getIterator()
{
return new \ArrayIterator($this->events);
}
abstract public function addEvent(EventInterface $event);
abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType);
abstract public function getEvents();
}
|
<?php
namespace Plummer\Calendar;
abstract class CalendarAbstract implements CalendarInterface, \IteratorAggregate
{
protected $name;
protected $events;
protected $recurrenceTypes;
public function __construct($name)
{
$this->name = $name;
}
public function addEvents($events)
{
foreach($events as $key => $event) {
$this->events[$key] = $event;
}
}
public function addRecurrenceTypes($recurrenceTypes)
{
foreach($recurrenceTypes as $key => $recurrenceType) {
$this->recurrenceTypes[$key] = $recurrenceType;
}
}
public function getIterator()
{
return new \ArrayIterator($this->events);
}
abstract public function addEvent(EventInterface $event);
abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType);
abstract public function getEvents();
}
|
Update pe net server constants
|
package protocolsupport.injector.pe;
import io.netty.channel.Channel;
import protocolsupport.api.ProtocolVersion;
import raknetserver.pipeline.raknet.RakNetPacketConnectionEstablishHandler.PingHandler;
public class PENetServerConstants {
public static final PingHandler PING_HANDLER = new PingHandler() {
@Override
public String getServerInfo(Channel channel) {
//TODO: fake pspe packets for ping passthrough
return String.join(";",
"MCPE",
"ProtocolSupportBungeePE",
String.valueOf(ProtocolVersion.MINECRAFT_PE.getId()), POCKET_VERSION,
"0", "1"
);
}
@Override
public void executeHandler(Runnable runnable) {
runnable.run();
}
};
public static final int USER_PACKET_ID = 0xFE;
public static final String POCKET_VERSION = "1.2.6";
}
|
package protocolsupport.injector.pe;
import io.netty.channel.Channel;
import raknetserver.pipeline.raknet.RakNetPacketConnectionEstablishHandler.PingHandler;
public class PENetServerConstants {
public static final PingHandler PING_HANDLER = new PingHandler() {
@Override
public String getServerInfo(Channel channel) {
//TODO: fake pspe packets for ping passthrough
return String.join(";",
"MCPE",
"ProtocolSupportBungeePE",
String.valueOf(CURRENT_PROTOCOL), POCKET_VERSION,
"0", "1"
);
}
@Override
public void executeHandler(Runnable runnable) {
runnable.run();
}
};
public static final int USER_PACKET_ID = 0xFE;
public static final int TEST_PORT = 2222;
public static final int CURRENT_PROTOCOL = 141;
public static final String POCKET_VERSION = "1.2.5.15";
}
|
Return something in the response.
|
// 在 Cloud code 里初始化 Express 框架
var express = require('express');
var app = express();
// App 全局配置
app.set('views','cloud/views'); // 设置模板目录
app.set('view engine', 'ejs'); // 设置 template 引擎
app.use(express.bodyParser()); // 读取请求 body 的中间件
// 使用 Express 路由 API 服务 /hello 的 HTTP GET 请求
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
app.get('/issue_webhook', function(req, res) {
console.dir(req);
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
// 最后,必须有这行代码来使 express 响应 HTTP 请求
app.listen();
|
// 在 Cloud code 里初始化 Express 框架
var express = require('express');
var app = express();
// App 全局配置
app.set('views','cloud/views'); // 设置模板目录
app.set('view engine', 'ejs'); // 设置 template 引擎
app.use(express.bodyParser()); // 读取请求 body 的中间件
// 使用 Express 路由 API 服务 /hello 的 HTTP GET 请求
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
app.get('/issue_webhook', function(req, res) {
console.dir(req);
});
// 最后,必须有这行代码来使 express 响应 HTTP 请求
app.listen();
|
Update wording when adding an interaction
|
const { POLICY_FEEDBACK_PERMISSIONS } = require('../constants')
module.exports = function ({
returnLink,
errors = [],
permissions = [],
}) {
const options = [
{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example a significant assist or an event',
},
]
if (permissions.includes(POLICY_FEEDBACK_PERMISSIONS.create)) {
options.push({
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, an issue or comment on government policy from a company',
})
}
return {
buttonText: 'Continue',
errors,
children: [{
options,
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
}],
}
}
|
const { POLICY_FEEDBACK_PERMISSIONS } = require('../constants')
module.exports = function ({
returnLink,
errors = [],
permissions = [],
}) {
const options = [
{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
]
if (permissions.includes(POLICY_FEEDBACK_PERMISSIONS.create)) {
options.push({
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, an issue or comment on government policy from a company',
})
}
return {
buttonText: 'Continue',
errors,
children: [{
options,
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
}],
}
}
|
Add adaptor for multiple argument functions
|
// Matching the public exports in husl-colors/husl
function expandParams(f) {
return function(c1, c2, c3) {
return f([c1, c2, c3])
}
}
module['exports'] = {};
module['exports']["fromRGB"] = expandParams(husl.Husl.rgbToHusl);
module['exports']["fromHex"] = husl.Husl.hexToHusl;
module['exports']["toRGB"] = expandParams(husl.Husl.huslToRgb);
module['exports']["toHex"] = expandParams(husl.Husl.huslToHex);
module['exports']['p'] = {};
module['exports']['p']["fromRGB"] = expandParams(husl.Husl.rgbToHuslp);
module['exports']['p']["fromHex"] = husl.Husl.hexToHuslp;
module['exports']['p']["toRGB"] = expandParams(husl.Husl.huslpToRgb);
module['exports']['p']["toHex"] = expandParams(husl.Husl.huslpToHex);
|
// Matching the public exports in husl-colors/husl
module['exports'] = {};
module['exports']["fromRGB"] = husl.Husl.rgbToHusl;
module['exports']["fromHex"] = husl.Husl.hexToHusl;
module['exports']["toRGB"] = husl.Husl.huslToRgb;
module['exports']["toHex"] = husl.Husl.huslToHex;
module['exports']['p'] = {};
module['exports']['p']["fromRGB"] = husl.Husl.rgbToHuslp;
module['exports']['p']["fromHex"] = husl.Husl.hexToHuslp;
module['exports']['p']["toRGB"] = husl.Husl.huslpToRgb;
module['exports']['p']["toHex"] = husl.Husl.huslpToHex;
|
Fix l4 change addFilter to filter
|
<?php namespace Tappleby\AuthToken;
use Illuminate\Support\ServiceProvider;
class AuthTokenServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['tappleby.auth.token'] = $this->app->share(function($app) {
return new AuthTokenManager($app);
});
$this->app['tappleby.auth.token.filter'] = $this->app->share(function($app) {
$driver = $app['tappleby.auth.token']->driver();
$events = $app['events'];
return new AuthTokenFilter($driver, $events);
});
$this->app['tappleby.auth.token.controller'] = $this->app->share(function($app) {
$driver = $app['tappleby.auth.token']->driver();
return new AuthTokenController($driver);
});
$this->app['router']->filter('auth.token', 'tappleby.auth.token.filter');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('tappleby.auth.token', 'tappleby.auth.token.filter', 'tappleby.auth.token.controller');
}
}
|
<?php namespace Tappleby\AuthToken;
use Illuminate\Support\ServiceProvider;
class AuthTokenServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['tappleby.auth.token'] = $this->app->share(function($app) {
return new AuthTokenManager($app);
});
$this->app['tappleby.auth.token.filter'] = $this->app->share(function($app) {
$driver = $app['tappleby.auth.token']->driver();
$events = $app['events'];
return new AuthTokenFilter($driver, $events);
});
$this->app['tappleby.auth.token.controller'] = $this->app->share(function($app) {
$driver = $app['tappleby.auth.token']->driver();
return new AuthTokenController($driver);
});
$this->app['router']->addFilter('auth.token', 'tappleby.auth.token.filter');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('tappleby.auth.token', 'tappleby.auth.token.filter', 'tappleby.auth.token.controller');
}
}
|
Change port for webpack dev server hot reload
|
/*eslint no-var:0 */
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react'],
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}],
sassLoader: {
includePaths: [path.resolve(__dirname, './styles')]
}
}
}
|
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react'],
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}],
sassLoader: {
includePaths: [path.resolve(__dirname, './styles')]
}
}
}
|
Add buckets to the byte array params.
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imagepipeline.memory;
import android.util.SparseIntArray;
import com.facebook.common.util.ByteConstants;
/**
* Provides pool parameters ({@link PoolParams}) for {@link SharedByteArray}
*/
public class DefaultSharedByteArrayParams {
// the default max buffer size we'll use
public static final int DEFAULT_MAX_BYTE_ARRAY_SIZE = 4 * ByteConstants.MB;
// the min buffer size we'll use
private static final int DEFAULT_MIN_BYTE_ARRAY_SIZE = 128 * ByteConstants.KB;
private DefaultSharedByteArrayParams() {
}
public static SparseIntArray generateBuckets(int min, int max) {
SparseIntArray buckets = new SparseIntArray();
for (int i = min; i <= max; i*=2) {
buckets.put(i, 1);
}
return buckets;
}
public static PoolParams get() {
return new PoolParams(
DEFAULT_MAX_BYTE_ARRAY_SIZE,
DEFAULT_MAX_BYTE_ARRAY_SIZE,
generateBuckets(DEFAULT_MIN_BYTE_ARRAY_SIZE, DEFAULT_MAX_BYTE_ARRAY_SIZE),
DEFAULT_MIN_BYTE_ARRAY_SIZE,
DEFAULT_MAX_BYTE_ARRAY_SIZE
);
}
}
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imagepipeline.memory;
import com.facebook.common.util.ByteConstants;
/**
* Provides pool parameters ({@link PoolParams}) for {@link SharedByteArray}
*/
public class DefaultSharedByteArrayParams {
// the default max buffer size we'll use
private static final int DEFAULT_MAX_BYTE_ARRAY_SIZE = 4 * ByteConstants.MB;
// the min buffer size we'll use
private static final int DEFAULT_MIN_BYTE_ARRAY_SIZE = 128 * ByteConstants.KB;
private DefaultSharedByteArrayParams() {
}
public static PoolParams get() {
return new PoolParams(
DEFAULT_MAX_BYTE_ARRAY_SIZE,
DEFAULT_MAX_BYTE_ARRAY_SIZE,
null,
DEFAULT_MIN_BYTE_ARRAY_SIZE,
DEFAULT_MAX_BYTE_ARRAY_SIZE
);
}
}
|
Check auth status before retrieving notifications
|
app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
return {
restrict: 'E',
templateUrl: config.partialsDir + '/broadcast_block.html',
link: function(scope, element, attrs) {
var notifications = Restangular.all('notifications');
var updateNotifications = function() {
notifications.getList().then(function(response) {
if (response.length) {
scope.selectedNotification = response[0];
} else {
scope.selectedNotification = undefined;
}
});
};
scope.markAsSeen = function(notification) {
notification.patch().then(updateNotifications);
};
if (AuthService.isAuthenticated()) {
updateNotifications();
}
}
};
}]);
|
app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
return {
restrict: 'E',
templateUrl: config.partialsDir + '/broadcast_block.html',
link: function(scope, element, attrs) {
var notifications = Restangular.all('notifications');
var updateNotifications = function() {
notifications.getList().then(function(response) {
if (response.length) {
scope.selectedNotification = response[0];
} else {
scope.selectedNotification = undefined;
}
});
};
updateNotifications();
scope.markAsSeen = function(notification) {
notification.patch().then(updateNotifications);
};
}
};
}]);
|
Use security token interface for encoding access tokens.
|
exports = module.exports = function(negotiateTokenContent, negotiateTokenType, tokens) {
return function issueToken(ctx, options, cb) {
console.log('ISSUE TOKEN!');
console.log(ctx);
if (typeof options == 'function') {
cb = options;
options = undefined;
}
options = options || {};
var topts = negotiateTokenType(ctx.client, ctx.audience);
console.log(topts);
var copts = negotiateTokenContent(ctx.audience);
console.log(copts);
copts.dialect = options.dialect || copts.dialect;
copts.confidential = false;
copts.audience = ctx.audience;
//copts.type = 'http://schemas.modulate.io/tokens/jwt/twilio';
//copts.dialect = 'http://schemas.modulate.io/tokens/jwt/twilio';
tokens.encode('access', ctx, copts, function(err, token) {
if (err) { return cb(err); }
return cb(null, token);
});
};
};
exports['@implements'] = 'http://schemas.authnomicon.org/js/aaa/oauth2/util/issueToken';
exports['@singleton'] = true;
exports['@require'] = [
'./negotiateTokenContent',
'./negotiateTokenType',
'http://i.bixbyjs.org/security/tokens'
];
|
exports = module.exports = function(negotiateTokenContent, negotiateTokenType, Tokens) {
return function issueToken(ctx, options, cb) {
console.log('ISSUE TOKEN!');
console.log(ctx);
if (typeof options == 'function') {
cb = options;
options = undefined;
}
options = options || {};
var topts = negotiateTokenType(ctx.client, ctx.audience);
console.log(topts);
var copts = negotiateTokenContent(ctx.audience);
console.log(copts);
copts.dialect = options.dialect || copts.dialect;
copts.confidential = false;
//copts.type = 'http://schemas.modulate.io/tokens/jwt/twilio';
//copts.dialect = 'http://schemas.modulate.io/tokens/jwt/twilio';
Tokens.cipher(ctx, copts, function(err, token) {
if (err) { return cb(err); }
return cb(null, token);
});
};
};
exports['@implements'] = 'http://schemas.authnomicon.org/js/aaa/oauth2/util/issueToken';
exports['@singleton'] = true;
exports['@require'] = [
'./negotiateTokenContent',
'./negotiateTokenType',
'http://i.bixbyjs.org/tokens'
];
|
Set the version to 0.3.1
|
/*******************************************************************************
* Copyright 2012-present Pixate, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.pixate.freestyle;
/**
* Holds version information. This info, for example, is being used with the
* pings.
*
* @author Shalom Gibly
*/
public interface Version {
public static String PIXATE_FREESTYLE_VERSION = "0.3.1";
public static int PIXATE_FREESTYLE_API_VERSION = 2;
}
|
/*******************************************************************************
* Copyright 2012-present Pixate, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.pixate.freestyle;
/**
* Holds version information. This info, for example, is being used with the
* pings.
*
* @author Shalom Gibly
*/
public interface Version {
public static String PIXATE_FREESTYLE_VERSION = "0.3";
public static int PIXATE_FREESTYLE_API_VERSION = 2;
}
|
Return ProjectSearchSerializer on ProjectResourceViewSet if action != 'Create'
|
from ovp_projects import serializers
from ovp_projects import models
from ovp_users import models as users_models
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import response
from rest_framework import status
class ProjectResourceViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
ProjectResourceViewSet resource endpoint
"""
queryset = models.Project.objects.all()
lookup_field = 'slug'
lookup_value_regex = '[^/]+' # default is [^/.]+ - here we're allowing dots in the url slug field
def get_serializer_class(self):
if self.action == 'create':
return serializers.ProjectCreateSerializer
return serializers.ProjectSearchSerializer
def create(self, request, *args, **kwargs):
user = users_models.User.objects.all().first()
request.data['owner'] = user.pk
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
headers = self.get_success_headers(serializer.data)
return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
|
from ovp_projects import serializers
from ovp_projects import models
from ovp_users import models as users_models
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import response
from rest_framework import status
class ProjectResourceViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
ProjectResourceViewSet resource endpoint
"""
queryset = models.Project.objects.all()
lookup_field = 'slug'
lookup_value_regex = '[^/]+' # default is [^/.]+ - here we're allowing dots in the url slug field
def get_serializer_class(self):
#if self.action == 'create':
return serializers.ProjectCreateSerializer
def create(self, request, *args, **kwargs):
user = users_models.User.objects.all().first()
request.data['owner'] = user.pk
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
headers = self.get_success_headers(serializer.data)
return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
|
Update Spinner to use es6 class.
|
/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
class Spinner extends React.Component {
render() {
return (
<div className="spinner-container">
<div className="spinner-loading">Loading...</div>
</div>
);
}
};
YUI.add('loading-spinner', function() {
juju.components.Spinner = Spinner;
}, '0.1.0', {
requires: []
});
|
/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const Spinner = React.createClass({
displayName: 'Spinner',
render: function() {
return (
<div className="spinner-container">
<div className="spinner-loading">Loading...</div>
</div>
);
}
});
YUI.add('loading-spinner', function() {
juju.components.Spinner = Spinner;
}, '0.1.0', {
requires: []
});
|
Implement the Python side of Canvas.fillRect
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class FakeCanvas:
def fillRect(self, x, y, width, height):
pass
# Your code here
|
Add second line of message display.
|
import _ from 'lodash'
import spark from 'spark'
const debug = require('debug')('sentry:routes:devices:publish')
const Membership = require('mongoose').model('Membership')
export default async (req, res) => {
const accessToken = req.currentAccount.particleAccessToken
spark.login({ accessToken })
debug('logged into Particle')
const memberships = await Membership.where({}).sort('name')
debug('memberships', memberships)
const csv = memberships.map((m) => {
const token = m.accessToken
const status = 1
const line1 = ' Welcome in '
const line2 = m.name
return `${token}\t${status}\t${line1}\t${line2}`
})
debug('csv', csv)
const chunks = _.chunk(csv, 10)
debug('chunks', chunks)
// Clear out existing members
await spark.publishEvent('sentry/wipe-members')
// Buffer the list of members so the device doesn't
// crash.
await Promise.all(chunks.map(async (chunk) => {
return await spark.publishEvent('sentry/append-members', chunk.join('\n'))
}))
req.flash('success', `Updating all devices with ${memberships.length} memberships`)
res.redirect('/devices')
}
|
import _ from 'lodash'
import spark from 'spark'
const debug = require('debug')('sentry:routes:devices:publish')
const Membership = require('mongoose').model('Membership')
export default async (req, res) => {
const accessToken = req.currentAccount.particleAccessToken
spark.login({ accessToken })
debug('logged into Particle')
const memberships = await Membership.where({}).sort('name')
debug('memberships', memberships)
const csv = memberships.map((m) => {
const token = m.accessToken
const status = 1
const message = 'Hello'
return `${token}\t${status}\t${message}`
})
debug('csv', csv)
const chunks = _.chunk(csv, 10)
debug('chunks', chunks)
// Clear out existing members
await spark.publishEvent('sentry/wipe-members')
// Buffer the list of members so the device doesn't
// crash.
await Promise.all(chunks.map(async (chunk) => {
return await spark.publishEvent('sentry/append-members', chunk.join('\n'))
}))
req.flash('success', `Updating all devices with ${memberships.length} memberships`)
res.redirect('/devices')
}
|
Add functions for creating/removing databases, return statements
|
var Q = require('q'),
_ = require('lodash');
// Constants
var VALID_DB_TYPES = ['rethinkdb'];
function ThrowawayDB(options) {
var self = this;
self.options = options || {db: 'rethinkdb'};
// Ensure db has been specified
if (!_.has(self.options, 'db') ||
_.isUndefined(self.options.db) ||
!_.contains(VALID_DB_TYPES, self.options.db)) {
throw new Error("Invalid/missing database type");
}
}
/**
* Load data for the database from a file
*
* @param {string} type - Type of data file (ex. json, binary)
* @param {string} filePath - Path to the file that contains the data to be loaded
* @returns ThrowawayDB instance
*/
ThrowawayDB.prototype.loadDataFromFile = function(type, filePath) {
return this;
};
/**
* Start the database process for the database
* @returns ThrowawayDB instance
*/
ThrowawayDB.prototype.start = function() {
return this;
};
/**
* Create database
*
* @param {string} dbName - Database to create
* @returns ThrowawayDB instance
*/
ThrowawayDB.prototype.createDB = function(dbName) {
return this;
};
/**
* Delete database
*
* @param {string} dbName - Database to delete
* @returns ThrowawayDB instance
*/
ThrowawayDB.prototype.deleteDB = function(dbName) {
return this;
};
exports.ThrowawayDB = ThrowawayDB;
|
var Q = require('q'),
_ = require('lodash');
// Constants
var VALID_DB_TYPES = ['rethinkdb'];
function ThrowawayDB(options) {
var self = this;
self.options = options || {db: 'rethinkdb'};
// Ensure db has been specified
if (!_.has(self.options, 'db') ||
_.isUndefined(self.options.db) ||
!_.contains(VALID_DB_TYPES, self.options.db)) {
throw new Error("Invalid/missing database type");
}
}
/**
* Load data for the database from a file
*
* @param {string} type - Type of data file (ex. json, binary)
* @param {string} filePath - Path to the file that contains the data to be loaded
* @returns ThrowawayDB instance
*/
ThrowawayDB.prototype.loadDataFromFile = function(type, filePath) {
};
/**
* Start the server
*/
ThrowawayDB.prototype.start = function() {
console.log("Staritng DB!");
};
exports.ThrowawayDB = ThrowawayDB;
|
Connect to transactionalDigest queue as exclusive consumer
|
<?php
/**
* mbc-transactional-digest
*
* Collect transactional campaign sign up message requests in a certain time period and
* compose a single digest message request.
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';
// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'));
echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
<?php
/**
* mbc-transactional-digest
*
* Collect transactional campaign sign up message requests in a certain time period and
* compose a single digest message request.
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';
// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer(), 'consumeQueue'));
echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
Remove white space between print and ()
TrivialFix
Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c
|
#!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.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.
import binascii
import sys
import dns
import dns.message
import dns.rdatatype
unhexed = binascii.unhexlify(sys.argv[1])
response = dns.message.from_wire(unhexed)
print(response.to_text())
|
#!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.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.
import binascii
import sys
import dns
import dns.message
import dns.rdatatype
unhexed = binascii.unhexlify(sys.argv[1])
response = dns.message.from_wire(unhexed)
print (response.to_text())
|
Update test expectations follow change of concrete error type
|
package sqlite3
import (
"database/sql"
"io/ioutil"
"os"
"path"
"testing"
)
func TestFailures(t *testing.T) {
dirName, err := ioutil.TempDir("", "sqlite3")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dirName)
dbFileName := path.Join(dirName, "test.db")
f, err := os.Create(dbFileName)
if err != nil {
t.Error(err)
}
f.Write([]byte{1, 2, 3, 4, 5})
f.Close()
db, err := sql.Open("sqlite3", dbFileName)
if err == nil {
_, err = db.Exec("drop table foo")
}
sqliteErr := err.(Error)
if sqliteErr.Code != ErrNotADB {
t.Error("wrong error code for corrupted DB")
}
if err.Error() == "" {
t.Error("wrong error string for corrupted DB")
}
db.Close()
}
|
package sqlite3
import (
"database/sql"
"io/ioutil"
"os"
"path"
"testing"
)
func TestFailures(t *testing.T) {
dirName, err := ioutil.TempDir("", "sqlite3")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dirName)
dbFileName := path.Join(dirName, "test.db")
f, err := os.Create(dbFileName)
if err != nil {
t.Error(err)
}
f.Write([]byte{1, 2, 3, 4, 5})
f.Close()
db, err := sql.Open("sqlite3", dbFileName)
if err == nil {
_, err = db.Exec("drop table foo")
}
if err.Code != ErrNotADB {
t.Error("wrong error code for corrupted DB")
}
if err.Error() == "" {
t.Error("wrong error string for corrupted DB")
}
db.Close()
}
|
Remove self-closing tags in JavaDoc
|
package rx.android.eventbus;
import rx.Observer;
import rx.Subscription;
import rx.subjects.Subject;
public interface EventBus {
/**
* Subscribes <code>observer</code> to <code>queue</code>.
* <p>
* This variant always delivers notifications on the Android main thread.
*/
<T> Subscription subscribe(Queue<T> queue, Observer<T> observer);
/**
* Subscribes <code>observer</code> to <code>queue</code>.
* <p>
* Unlike {@link #subscribe(Queue, rx.Observer)}, this variant delivers notifications
* on the same thread as the event source.
*/
<T> Subscription subscribeImmediate(Queue<T> queue, Observer<T> observer);
/**
* Publishes an event by putting it on the given <code>queue</code>.
*/
<T> void publish(Queue<T> queue, T event);
/**
* @return The Rx {@link rx.subjects.Subject} backing the given event <code>queue</code>.
*/
<T> Subject<T, T> queue(Queue<T> queue);
}
|
package rx.android.eventbus;
import rx.Observer;
import rx.Subscription;
import rx.subjects.Subject;
public interface EventBus {
/**
* Subscribes <code>observer</code> to <code>queue</code>.
* <p/>
* This variant always delivers notifications on the Android main thread.
*/
<T> Subscription subscribe(Queue<T> queue, Observer<T> observer);
/**
* Subscribes <code>observer</code> to <code>queue</code>.
* <p/>
* Unlike {@link #subscribe(Queue, rx.Observer)}, this variant delivers notifications
* on the same thread as the event source.
*/
<T> Subscription subscribeImmediate(Queue<T> queue, Observer<T> observer);
/**
* Publishes an event by putting it on the given <code>queue</code>.
*/
<T> void publish(Queue<T> queue, T event);
/**
* @return The Rx {@link rx.subjects.Subject} backing the given event <code>queue</code>.
*/
<T> Subject<T, T> queue(Queue<T> queue);
}
|
Fix query string on the client
|
const axios = require('axios')
const createHistory = require('history').createBrowserHistory
const queryString = require('query-string')
const history = createHistory()
history.listen((location, action) => {
if (action === 'POP') {
if (location.state) {
XHR.injectResponseInHtml(location.state.data)
} else {
window.location.href = location.pathname + location.search
}
}
})
const XHR = {
getOutlet () {
return document.getElementById('xhr-outlet')
},
injectResponseInHtml (data) {
const outlet = this.getOutlet()
if (!outlet) { return }
outlet.outerHTML = data
},
updateOutlet (res, params) {
this.injectResponseInHtml(res.data)
if (params) {
history.push(`?${queryString.stringify(params)}`, { data: res.data })
}
return res
},
request (url, params = {}, showLoader = true) {
const outlet = this.getOutlet()
if (!outlet) { return }
if (showLoader) {
outlet.classList.add('u-loading')
}
return axios
.get(`${url}?${queryString.stringify(params)}`, {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
})
.then(res => this.updateOutlet(res, params))
},
}
module.exports = XHR
|
const axios = require('axios')
const createHistory = require('history').createBrowserHistory
const { buildQueryString } = require('../../../src/lib/url-helpers')
const history = createHistory()
history.listen((location, action) => {
if (action === 'POP') {
if (location.state) {
XHR.injectResponseInHtml(location.state.data)
} else {
window.location.href = location.pathname + location.search
}
}
})
const XHR = {
getOutlet () {
return document.getElementById('xhr-outlet')
},
injectResponseInHtml (data) {
const outlet = this.getOutlet()
if (!outlet) { return }
outlet.outerHTML = data
},
updateOutlet (res, params) {
this.injectResponseInHtml(res.data)
if (params) {
history.push(buildQueryString(params), { data: res.data })
}
return res
},
request (url, params = {}, showLoader = true) {
const outlet = this.getOutlet()
if (!outlet) { return }
if (showLoader) {
outlet.classList.add('u-loading')
}
return axios
.get(url, {
params,
headers: { 'X-Requested-With': 'XMLHttpRequest' },
})
.then(res => this.updateOutlet(res, params))
},
}
module.exports = XHR
|
Revert to setting target with noOp
|
module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
setTarget(() => {});
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(mutableTarget, handler)
};
};
|
module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(() => {}, handler)
};
};
|
Add group call invitation model
|
import thinky from './thinky';
var thinkyType = thinky.type;
export var Person = thinky.createModel("person", {
id: thinkyType.string(),
email: thinkyType.string()
});
export var Field = thinky.createModel("field", {
id: thinkyType.string(),
label: thinkyType.string(),
type: thinkyType.string().enum(['NUMBER', 'STRING', 'BOOLEAN']),
choices: []
})
export var Note = thinky.createModel("note", {
id: thinkyType.string(),
about: {
table: thinkyType.string(),
id: thinkyType.string()
},
fieldId: thinkyType.string(),
value: thinkyType.any(),
source: {
table: thinkyType.string(),
id: thinkyType.string()
}
})
// An invitation gets sent to volunteers and they can pick one group call.
export var GroupCallInvitation = thinky.createModel("group_call_invitation", {
id: thinkyType.string(),
topic: thinkyType.string(),
groupCalls: [GroupCall]
})
export var GroupCall = thinky.createModel("group_call", {
id: thinkyType.string(),
scheduledTime: thinkyType.date(),
maxSignups: thinkyType.number(),
signups: [{
personId: thinkyType.string(),
attended: thinkyType.boolean()
}]
})
|
var thinky = require('thinky')();
var thinkyType = thinky.type;
export var Person = thinky.createModel("person", {
id: thinkyType.string(),
email: thinkyType.string()
});
export var Field = thinky.createModel("field", {
id: thinkyType.string(),
label: thinkyType.string(),
type: thinkyType.string().enum(['NUMBER', 'STRING', 'BOOLEAN']), // TODO: Change this to use the same enum from the graphql schema
choices: []
})
export var Note = thinky.createModel("note", {
id: thinkyType.string(),
about: {
table: thinkyType.string(),
id: thinkyType.string()
},
fieldId: thinkyType.string(),
value: thinkyType.any(),
source: {
table: thinkyType.string(),
id: thinkyType.string()
}
})
export var GroupCall = thinky.createModel("group_call", {
id: thinkyType.string(),
invitees: [{
personId: thinkyType.string(),
signedUp: thinkyType.boolean(),
attended: thinkyType.boolean()
}]
})
|
Change `composedUrl` to use the abstracted s/ URL
|
/**
* HiveModel.js
*/
(function (spiderOakApp, window, undefined) {
"use strict";
var console = window.console || {};
console.log = console.log || function(){};
var Backbone = window.Backbone,
_ = window._,
$ = window.$,
s = window.s;
spiderOakApp.HiveModel = spiderOakApp.FolderModel.extend({
defaults: {
hasHive: true
},
parse: function(resp, xhr) {
if (resp.syncfolder) {
resp.syncfolder.name = s("SpiderOak Hive");
return resp.syncfolder;
}
else {
this.set("hasHive", false);
return this.attributes;
}
},
composedUrl: function(bare) {
var urlTail = this.get("url");
var urlHead = this.url;
if (bare) {
urlHead = urlHead && urlHead.split("?")[0];
urlTail = urlTail && urlTail.split("?")[0];
}
return (urlHead || "") + (urlTail || "");
}
});
})(window.spiderOakApp = window.spiderOakApp || {}, window);
|
/**
* HiveModel.js
*/
(function (spiderOakApp, window, undefined) {
"use strict";
var console = window.console || {};
console.log = console.log || function(){};
var Backbone = window.Backbone,
_ = window._,
$ = window.$,
s = window.s;
spiderOakApp.HiveModel = spiderOakApp.FolderModel.extend({
defaults: {
hasHive: true
},
parse: function(resp, xhr) {
if (resp.syncfolder) {
resp.syncfolder.name = s("SpiderOak Hive");
return resp.syncfolder;
}
else {
this.set("hasHive", false);
return this.attributes;
}
},
composedUrl: function(bare) {
var urlTail = encodeURI(this.get("device_path"));
var urlHead = this.url.replace("s\/","") + this.get("device_encoded");
if (bare) {
urlHead = urlHead && urlHead.split("?")[0];
urlTail = urlTail && urlTail.split("?")[0];
}
return (urlHead || "") + (urlTail || "");
}
});
})(window.spiderOakApp = window.spiderOakApp || {}, window);
|
Use 'rb' mode explicitly in file_md5sum and allow for custom encoding
|
# -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, blocksize=65536, encoding="utf-8"):
if unzip:
opener = gzip.open
else:
opener = open
hasher = hashlib.md5()
with opener(fname, "rb") as src:
buf = src.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = src.read(blocksize)
return hasher.hexdigest()
def isexecfile(fname):
return os.path.isfile(fname) and os.access(fname, os.X_OK)
def which(program):
# can not do anything meaningful without PATH
if "PATH" not in os.environ:
return
for possible in os.environ["PATH"].split(":"):
qualname = os.path.join(possible, program)
if isexecfile(qualname):
return qualname
return
|
# -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener = gzip.open
else:
opener = open
hasher = hashlib.md5()
with opener(fname, mode) as src:
buf = src.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = src.read(blocksize)
return hasher.hexdigest()
def isexecfile(fname):
return os.path.isfile(fname) and os.access(fname, os.X_OK)
def which(program):
# can not do anything meaningful without PATH
if "PATH" not in os.environ:
return
for possible in os.environ["PATH"].split(":"):
qualname = os.path.join(possible, program)
if isexecfile(qualname):
return qualname
return
|
Update deprecated allow_tags to format_html
|
from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "webmention"
verbose_name_plural = "webmentions"
def __str__(self):
return self.source
def source_for_admin(self):
return format_html('<a href="{href}">{href}</a>'.format(href=self.source))
source_for_admin.short_description = "source"
def response_to_for_admin(self):
return format_html('<a href="{href}">{href}</a>'.format(href=self.response_to))
response_to_for_admin.short_description = "response to"
def invalidate(self):
if self.id:
self.current = False
self.save()
def update(self, source, target, response_body):
self.response_body = response_body
self.source = source
self.response_to = target
self.current = True
self.save()
|
from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "webmention"
verbose_name_plural = "webmentions"
def __str__(self):
return self.source
def source_for_admin(self):
return '<a href="{href}">{href}</a>'.format(href=self.source)
source_for_admin.allow_tags = True
source_for_admin.short_description = "source"
def response_to_for_admin(self):
return '<a href="{href}">{href}</a>'.format(href=self.response_to)
response_to_for_admin.allow_tags = True
response_to_for_admin.short_description = "response to"
def invalidate(self):
if self.id:
self.current = False
self.save()
def update(self, source, target, response_body):
self.response_body = response_body
self.source = source
self.response_to = target
self.current = True
self.save()
|
Use the SameContents checker in backups tests.
|
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package backups_test
import (
jc "github.com/juju/testing/checkers"
gc "launchpad.net/gocheck"
"github.com/juju/juju/state/backups"
"github.com/juju/juju/testing"
)
var getFilesToBackup = *backups.GetFilesToBackup
var _ = gc.Suite(&sourcesSuite{})
type sourcesSuite struct {
testing.BaseSuite
}
func (s *sourcesSuite) TestGetFilesToBackup(c *gc.C) {
files, err := getFilesToBackup()
c.Assert(err, gc.IsNil)
c.Check(files, jc.SameContents, []string{
"/etc/init/juju-db.conf",
"/home/ubuntu/.ssh/authorized_keys",
"/var/lib/juju/nonce.txt",
"/var/lib/juju/server.pem",
"/var/lib/juju/shared-secret",
"/var/lib/juju/system-identity",
"/var/lib/juju/tools",
"/var/log/juju/all-machines.log",
"/var/log/juju/machine-0.log",
})
}
|
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package backups_test
import (
"sort"
gc "launchpad.net/gocheck"
"github.com/juju/juju/state/backups"
"github.com/juju/juju/testing"
)
var getFilesToBackup = *backups.GetFilesToBackup
var _ = gc.Suite(&sourcesSuite{})
type sourcesSuite struct {
testing.BaseSuite
}
func (s *sourcesSuite) TestGetFilesToBackup(c *gc.C) {
files, err := getFilesToBackup()
c.Assert(err, gc.IsNil)
sort.Strings(files)
c.Check(files, gc.DeepEquals, []string{
"/etc/init/juju-db.conf",
"/home/ubuntu/.ssh/authorized_keys",
"/var/lib/juju/nonce.txt",
"/var/lib/juju/server.pem",
"/var/lib/juju/shared-secret",
"/var/lib/juju/system-identity",
"/var/lib/juju/tools",
"/var/log/juju/all-machines.log",
"/var/log/juju/machine-0.log",
})
}
|
Fix potentially broken selfcheck if two errors occur
|
/*
The Company module exposes functionality needed in the company section
of the dashboard.
*/
var Inventory = (function ($, tools) {
// Perform self check, display error if missing deps
var performSelfCheck = function () {
var errors = false
if ($ == undefined) {
console.error('jQuery missing!')
errors = true
}
if (tools == undefined) {
console.error('Dashboard tools missing!')
errors = true
}
if (errors) return false
return true
}
return {
// Bind them buttons and other initial functionality here
init: function () {
if (!performSelfCheck()) return
$('#inventory_item_list').tablesorter()
}
}
})(jQuery, Dashboard.tools)
$(document).ready(function () {
Inventory.init()
})
|
/*
The Company module exposes functionality needed in the company section
of the dashboard.
*/
var Inventory = (function ($, tools) {
// Perform self check, display error if missing deps
var performSelfCheck = function () {
var errors = false
if ($ == undefined) {
console.error('jQuery missing!')
errors = !errors
}
if (tools == undefined) {
console.error('Dashboard tools missing!')
errors = !errors
}
if (errors) return false
return true
}
return {
// Bind them buttons and other initial functionality here
init: function () {
if (!performSelfCheck()) return
$('#inventory_item_list').tablesorter()
}
}
})(jQuery, Dashboard.tools)
$(document).ready(function () {
Inventory.init()
})
|
Fix deprecated RepositoryRestConfigurerAdapter in the configs.
|
package hello.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.core.EvoInflectorRelProvider;
@Configuration
public class Hateoas {
private final static Logger log = LoggerFactory.getLogger(Hateoas.class);
@Bean
public RelProvider relProvider() {
log.info("Using EvoInflectorRelProvider for HATEOAS relations");
return new EvoInflectorRelProvider();
}
@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return new RepositoryRestConfigurer() {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setBasePath("/api");
}
};
}
}
|
package hello.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.core.EvoInflectorRelProvider;
@Configuration
public class Hateoas {
private final static Logger log = LoggerFactory.getLogger(Hateoas.class);
@Bean
public RelProvider relProvider() {
log.info("Using EvoInflectorRelProvider for HATEOAS relations");
return new EvoInflectorRelProvider();
}
@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return new RepositoryRestConfigurerAdapter() {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setBasePath("/api");
}
};
}
}
|
Write the formatted date data out as a module
|
from datetime import datetime, timedelta
from pprint import pformat
import sys
from icalendar import Calendar
def data_for_vevent(ev):
start_date, end_date = [ev[which].dt.replace(tzinfo=None) + timedelta(hours=-9)
for which in ('DTSTART', 'DTEND')]
return (start_date.date(), str(ev['SUMMARY']), start_date, end_date)
def main(argv):
# TODO: specify filename?
cal_str = open('ical.ics').read()
cal = Calendar.from_string(cal_str)
vevents = (ev for ev in cal.walk() if ev.name == 'VEVENT')
event_datas = (data_for_vevent(ev) for ev in vevents)
ordered_event_data = sorted(event_datas, key=lambda d: d[0])
with open('giants_schedule.py', 'w') as outfile:
outfile.write('import datetime\n\n\n')
outfile.write('schedule = ')
outfile.write(pformat(tuple(ordered_event_data)))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
from datetime import datetime, timedelta
import sys
from icalendar import Calendar
def data_for_vevent(ev):
start_date, end_date = [ev[which].dt.replace(tzinfo=None) + timedelta(hours=-9) for which in ('DTSTART', 'DTEND')]
# TODO: convert to PT
return (start_date.date(), str(ev['SUMMARY']), start_date, end_date)
def main(argv):
# TODO: specify filename?
cal_str = open('ical.ics').read()
cal = Calendar.from_string(cal_str)
vevents = (ev for ev in cal.walk() if ev.name == 'VEVENT')
event_datas = (data_for_vevent(ev) for ev in vevents)
ordered_event_data = sorted(event_datas, key=lambda d: d[0])
for data in ordered_event_data:
print str(data)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Change dev package time stamp
|
#!/usr/bin/python
import time
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=APPVER.replace('github', 'dev%d' % time.time()),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Partially supported protocols: IRC, Finger
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat'],
install_requires=['SocksipyChain >= 2.0.9']
)
|
#!/usr/bin/python
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=APPVER.replace('github',
'dev'+date.today().isoformat().replace('-', '')),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Partially supported protocols: IRC, Finger
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat'],
install_requires=['SocksipyChain >= 2.0.9']
)
|
Bring in pytest and pytest-cov
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
'pytest',
'pytest-cov'
]
dist = setup(
name='cloudpickle',
version='0.1.0',
description='Extended pickling support for Python objects',
author='Cloudpipe',
author_email='cloudpipe@googlegroups.com',
url='https://github.com/cloudpipe/cloudpickle',
install_requires=requirements,
license='LICENSE.txt',
packages=['cloudpickle'],
long_description=open('README.md').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering',
'Topic :: System :: Distributed Computing',
],
test_suite='tests',
tests_require=test_requirements
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
dist = setup(
name='cloudpickle',
version='0.1.0',
description='Extended pickling support for Python objects',
author='Cloudpipe',
author_email='cloudpipe@googlegroups.com',
url='https://github.com/cloudpipe/cloudpickle',
install_requires=requirements,
license='LICENSE.txt',
packages=['cloudpickle'],
long_description=open('README.md').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering',
'Topic :: System :: Distributed Computing',
],
test_suite='tests',
tests_require=test_requirements
)
|
Revert "mapped actions to dispatch"
This reverts commit 499dd4856650c0c4bde580c70ef6d46749fd2f48.
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
class BookList extends Component {
renderList() {
return this.props.books.map((book) => {
return (
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render() {
return (
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
)
}
}
function mapStateToProps(state) {
// Whatever is returned from here
// shows up as props inside of BookList
return {
books: state.books
};
}
export default connect(mapStateToProps)(BookList);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { bingActionCreators } from 'redux';
class BookList extends Component {
renderList() {
return this.props.books.map((book) => {
return (
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render() {
return (
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
)
}
}
function mapStateToProps(state) {
// Whatever is returned from here
// shows up as props inside of BookList
return {
books: state.books
};
}
// Anything returned from teh function will end up as props
// on the BookList container
function mapDispatchToProps(dispatch) {
// Whenever selectBook is called, the result should be passed
// to all of our reducers
return bingActionCreators({ selectBook: selectBook }, dispatch);
}
// Promote BookList from a component to a container - it needs to know
// about this new dispatch method selectBook. Make it available
// as a prop.
export default connect(mapStateToProps, mapDispatchToProps)(BookList);
|
Clean controller and add JsonResponse for success callback.
On branch master
modified: Parsley/ServerBundle/Controller/ValidationController.php
|
<?php
namespace Parsley\ServerBundle\Controller ;
use Symfony\Bundle\FrameworkBundle\Controller\Controller ;
use Symfony\Component\HttpFoundation\JsonResponse ;
use Symfony\Component\Form\FormRegistryInterface ;
class ValidationController extends Controller
{
public function validationAction ( $form_service_name , $field_to_compare )
{
list ( $field , $errors ) = $this -> get ( 'parsley_server_form_generator' ) -> validateField ( $form_service_name , $field_to_compare ) ;
$response = new JsonResponse ( ) ;
if ( count ( $errors ) == 0 )
{
$response -> setData ( array (
'success' => ''
) ) ;
}
else
{
$message = '' ;
foreach ( $errors as $error )
{
$message .= $error ;
}
$response -> setData ( array (
'error' => $message
) ) ;
}
return $response ;
}
}
|
<?php
namespace Parsley\ServerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller ;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\FormRegistryInterface ;
class ValidationController extends Controller
{
public function validationAction($form_service_name, $field_to_compare)
{
list($field, $errors) = $this->get('parsley_server_form_generator')->validateField($form_service_name, $field_to_compare);
if(count($errors) == 0){
$response = new Response(1);
return $response;
} else {
$message = "";
foreach($errors as $error){
$message .= $error;
}
$response = new JsonResponse();
$response->setData(array(
'error' => $message
));
return $response;
}
}
}
|
Convert file from buffer to a string.
|
if (global.GENTLY) require = GENTLY.hijack(require);
var Configuration = function(api) {
this.api = api;
this.fs = require('fs');
this.path = require('path');
};
Configuration.prototype = {
upload: function(content) {
this.api.put('/', {'configuration': content}, function(json) {
console.log('Sphinx configuration updated');
});
},
uploadFromFile: function(path) {
this.upload(this.fs.readFileSync(path).toString());
},
uploadSettings: function(setting, file_name, content) {
this.api.post('add_file', {
'setting': setting,
'file_name': file_name,
'content': content
}, function(json) { console.log('Uploaded ' + file_name + ' content')});
},
uploadSettingsFromFile: function(setting, path) {
this.uploadSettings(setting, this.path.basename(path),
this.fs.readFileSync(path));
}
}
module.exports = Configuration;
|
if (global.GENTLY) require = GENTLY.hijack(require);
var Configuration = function(api) {
this.api = api;
this.fs = require('fs');
this.path = require('path');
};
Configuration.prototype = {
upload: function(content) {
this.api.put('/', {'configuration': content}, function(json) {
console.log('Sphinx configuration updated');
});
},
uploadFromFile: function(path) {
this.upload(this.fs.readFileSync(path));
},
uploadSettings: function(setting, file_name, content) {
this.api.post('add_file', {
'setting': setting,
'file_name': file_name,
'content': content
}, function(json) { console.log('Uploaded ' + file_name + ' content')});
},
uploadSettingsFromFile: function(setting, path) {
this.uploadSettings(setting, this.path.basename(path),
this.fs.readFileSync(path));
}
}
module.exports = Configuration;
|
Check extra text for null
|
package de.danoeh.antennapod.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import de.danoeh.antennapod.core.preferences.UserPreferences;
/**
* Lets the user start the OPML-import process.
*/
public class OpmlImportFromIntentActivity extends OpmlImportBaseActivity {
private static final String TAG = "OpmlImportFromIntentAct";
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(UserPreferences.getTheme());
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith("/")) {
uri = Uri.parse("file://" + uri.toString());
} else {
String extraText = getIntent().getStringExtra(Intent.EXTRA_TEXT);
if(extraText != null) {
uri = Uri.parse(extraText);
}
}
importUri(uri);
}
@Override
protected boolean finishWhenCanceled() {
return true;
}
}
|
package de.danoeh.antennapod.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import de.danoeh.antennapod.core.preferences.UserPreferences;
/**
* Lets the user start the OPML-import process.
*/
public class OpmlImportFromIntentActivity extends OpmlImportBaseActivity {
private static final String TAG = "OpmlImportFromIntentAct";
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(UserPreferences.getTheme());
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith("/")) {
uri = Uri.parse("file://" + uri.toString());
} else {
uri = Uri.parse(getIntent().getStringExtra(Intent.EXTRA_TEXT));
}
importUri(uri);
}
@Override
protected boolean finishWhenCanceled() {
return true;
}
}
|
Remove duplicate fields from ZoneTransferRequest object
The fields id, version, created_at, updated_at are defined in the
PersistentObjectMixin which ZoneTransferRequest extends, so this
patch removes them from ZoneTransferRequest.
Change-Id: Iff20a31b4a208bff0bc879677a9901fedc43226b
Closes-Bug: #1403274
|
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Graham Hayes <graham.hayes@hp.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 designate.objects import base
class ZoneTransferRequest(base.DictObjectMixin, base.PersistentObjectMixin,
base.DesignateObject,):
FIELDS = {
'domain_id': {},
'key': {},
'description': {},
'tenant_id': {},
'target_tenant_id': {},
'status': {},
'domain_name': {},
}
class ZoneTransferRequestList(base.ListObjectMixin, base.DesignateObject):
LIST_ITEM_TYPE = ZoneTransferRequest
|
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Graham Hayes <graham.hayes@hp.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 designate.objects import base
class ZoneTransferRequest(base.DictObjectMixin, base.DesignateObject,
base.PersistentObjectMixin):
FIELDS = {
'domain_id': {},
'key': {},
'description': {},
'tenant_id': {},
'target_tenant_id': {},
'status': {},
'id': {},
'created_at': {},
'domain_name': {},
'updated_at': {},
'version': {},
}
class ZoneTransferRequestList(base.ListObjectMixin, base.DesignateObject):
LIST_ITEM_TYPE = ZoneTransferRequest
|
Define public $serverService in class
|
<?php
namespace GearmanMonitor\Controller;
class ServerController
{
public $serverService;
public function __construct($twig, $serverService)
{
$this->serverService = $serverService;
$this->twig = $twig;
}
public function indexAction()
{
$servers = [
[
'address' => '127.0.0.1',
'name' => 'KAPPA'
],
[
'address' => '192.168.155.1',
'name' => 'CHARMANDER'
]
];
$servers = $this->serverService->getStatuses($servers);
return $this->twig->render('server.twig', [
'servers' => $servers
]);
}
}
|
<?php
namespace GearmanMonitor\Controller;
class ServerController
{
public function __construct($twig, $serverService)
{
$this->serverService = $serverService;
$this->twig = $twig;
}
public function indexAction()
{
$servers = [
[
'address' => '127.0.0.1',
'name' => 'KAPPA'
],
[
'address' => '192.168.155.1',
'name' => 'CHARMANDER'
]
];
$servers = $this->serverService->getStatuses($servers);
return $this->twig->render('server.twig', [
'servers' => $servers
]);
}
}
|
Upgrade CNI config version to 0.3.0
Was using the default version of 0.2.0, didn't load with 0.4.0. closes https://github.com/kubernetes/minikube/issues/4406
|
/*
Copyright 2018 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeadm
// defaultCNIConfig is the CNI config which is provisioned when --enable-default-cni
// has been passed to `minikube start`.
//
// The config is being written to /etc/cni/net.d/k8s.conf and /etc/rkt/net.d/k8s.conf.
const defaultCNIConfig = `
{
"cniVersion": "0.3.0",
"name": "rkt.kubernetes.io",
"type": "bridge",
"bridge": "mybridge",
"mtu": 1460,
"addIf": "true",
"isGateway": true,
"ipMasq": true,
"ipam": {
"type": "host-local",
"subnet": "10.1.0.0/16",
"gateway": "10.1.0.1",
"routes": [
{
"dst": "0.0.0.0/0"
}
]
}
}
`
|
/*
Copyright 2018 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeadm
// defaultCNIConfig is the CNI config which is provisioned when --enable-default-cni
// has been passed to `minikube start`.
//
// The config is being written to /etc/cni/net.d/k8s.conf and /etc/rkt/net.d/k8s.conf.
const defaultCNIConfig = `
{
"name": "rkt.kubernetes.io",
"type": "bridge",
"bridge": "mybridge",
"mtu": 1460,
"addIf": "true",
"isGateway": true,
"ipMasq": true,
"ipam": {
"type": "host-local",
"subnet": "10.1.0.0/16",
"gateway": "10.1.0.1",
"routes": [
{
"dst": "0.0.0.0/0"
}
]
}
}
`
|
Change protocol format to use the FULL url instead of just the path
|
package com.usepropeller.routable;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class RouterActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String url;
Bundle extras = intent.getExtras();
if (extras.containsKey("url")) {
url = extras.getString("url");
}
else {
Uri data = intent.getData();
String protocol = data.getScheme() + "://";
url = data.toString().replaceFirst(protocol, "");
if (Router.sharedRouter().getRootUrl() != null) {
Router.sharedRouter().open(Router.sharedRouter().getRootUrl());
}
}
Router.sharedRouter().open(url);
setResult(RESULT_OK, null);
finish();
}
}
|
package com.usepropeller.routable;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class RouterActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String url;
Bundle extras = intent.getExtras();
if (extras.containsKey("url")) {
url = extras.getString("url");
}
else {
Uri data = intent.getData();
url = data.getPath();
if (url.startsWith("/")) {
url = url.substring(1);
}
if (Router.sharedRouter().getRootUrl() != null) {
Router.sharedRouter().open(Router.sharedRouter().getRootUrl());
}
}
Router.sharedRouter().open(url);
setResult(RESULT_OK, null);
finish();
}
}
|
Load correct provider from config file
|
<?php namespace Studious\Autologin;
use Illuminate\Support\ServiceProvider;
use Studious\Autologin\Autologin;
class AutologinServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerAutologinProvider();
$this->registerAutologin();
}
protected function registerAutologinProvider()
{
$this->app['autologin.provider'] = $this->app->share(function($app)
{
$provider = $app['config']['autologin::provider'];
return new $provider;
});
}
protected function registerAutologin()
{
$this->app['autologin'] = $this->app->share(function($app)
{
return new Autologin($app['config'], $app['url'], $app['autologin.provider']);
});
}
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
$this->package('studious/autologin');
include __DIR__.'/../../routes.php';
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('autologin', 'autologin.provider');
}
}
|
<?php namespace Studious\Autologin;
use Illuminate\Support\ServiceProvider;
use Studious\Autologin\Autologin;
class AutologinServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerAutologinProvider();
$this->registerAutologin();
}
protected function registerAutologinProvider()
{
$this->app['autologin.provider'] = $this->app->share(function($app)
{
$provider = $app['config']['studious/autologin::provider'];
$provider = 'Studious\Autologin\Providers\EloquentAutologinProvider';
return new $provider;
});
}
protected function registerAutologin()
{
$this->app['autologin'] = $this->app->share(function($app)
{
return new Autologin($app['config'], $app['url'], $app['autologin.provider']);
});
}
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
$this->package('studious/autologin');
include __DIR__.'/../../routes.php';
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
|
Update for Sphinx 1.0 intersphinx format and remove broken Sphinx inventory
|
# -*- coding: utf-8 -*-
import sys, os
needs_sphinx = '1.0'
extensions = ['sphinx.ext.intersphinx', 'sphinxcontrib.issuetracker']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinxcontrib-ansi'
copyright = u'2010, Sebastian Wiesner'
version = '0.5'
release = '0.5'
exclude_patterns = ['_build']
html_theme = 'default'
html_static_path = []
intersphinx_mapping = {'python': ('http://docs.python.org/', None)}
# broken in Sphinx 1.0
# 'sphinx': ('http://sphinx.pocoo.org/', None)}
issuetracker = 'bitbucket'
issuetracker_user = 'birkenfeld'
issuetracker_project = 'sphinx-contrib'
def setup(app):
app.add_description_unit('confval', 'confval',
'pair: %s; configuration value')
|
# -*- coding: utf-8 -*-
import sys, os
needs_sphinx = '1.0'
extensions = ['sphinx.ext.intersphinx', 'sphinxcontrib.issuetracker']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinxcontrib-ansi'
copyright = u'2010, Sebastian Wiesner'
version = '0.5'
release = '0.5'
exclude_patterns = ['_build']
html_theme = 'default'
html_static_path = []
intersphinx_mapping = {'http://docs.python.org/': None,
'http://sphinx.pocoo.org/': None,}
issuetracker = 'bitbucket'
issuetracker_user = 'birkenfeld'
issuetracker_project = 'sphinx-contrib'
def setup(app):
app.add_description_unit('confval', 'confval',
'pair: %s; configuration value')
|
fixed: Add transition time and take redraw function into requestAnimationFrame
|
'use strict';
angular.module('chemartApp')
.factory('moleculeDrawer', function (centerAtoms, canvas) {
return function (molecule) {
var currentMolecule = canvas.getMolecule();
var time = 400;
centerAtoms(molecule);
for (var i in molecule.atoms) {
if (typeof currentMolecule.atoms[i] !== 'undefined') {
new TWEEN.Tween(currentMolecule.atoms[i].position)
.to(molecule.atoms[i].position, time)
.easing(TWEEN.Easing.Circular.Out)
.start();
}
}
var endTime = Date.now() + time;
function animate() {
if (Date.now() < endTime) {
requestAnimationFrame(animate);
}
TWEEN.update();
canvas.update();
}
requestAnimationFrame(animate);
setTimeout(function () {
canvas.clear();
canvas.attach(molecule);
}, time);
};
});
|
'use strict';
angular.module('chemartApp')
.factory('moleculeDrawer', function (centerAtoms, canvas) {
return function (molecule) {
var currentMolecule = canvas.getMolecule();
var time = 200;
centerAtoms(molecule);
for (var i in molecule.atoms) {
if (typeof currentMolecule.atoms[i] !== 'undefined') {
new TWEEN.Tween(currentMolecule.atoms[i].position)
.to(molecule.atoms[i].position, time)
.easing(TWEEN.Easing.Circular.Out)
.start();
}
}
var endTime = Date.now() + time;
animate();
function animate() {
if (Date.now() < endTime) {
requestAnimationFrame(animate);
}
TWEEN.update();
canvas.update();
}
setTimeout(function () {
canvas.clear();
canvas.attach(molecule);
}, time);
};
});
|
Add px if needed before prefixing
Since the list in `appendPxIfNeeded` does not include prefixed variants.
|
/* @flow */
import appendPxIfNeeded from './append-px-if-needed';
import camelCasePropsToDashCase from './camel-case-props-to-dash-case';
import mapObject from './map-object';
import {getPrefixedStyle} from './prefixer';
function createMarkupForStyles(style: Object): string {
return Object.keys(style).map(property => {
return property + ': ' + style[property] + ';';
}).join('\n');
}
export default function cssRuleSetToString(
selector: string,
rules: Object,
userAgent: ?string,
): string {
if (!rules) {
return '';
}
const rulesWithPx = mapObject(
rules,
(value, key) => appendPxIfNeeded(key, value)
);
const prefixedRules = getPrefixedStyle(rulesWithPx, userAgent);
const cssPrefixedRules = camelCasePropsToDashCase(prefixedRules);
const serializedRules = createMarkupForStyles(cssPrefixedRules);
return selector + '{' + serializedRules + '}';
}
|
/* @flow */
import appendPxIfNeeded from './append-px-if-needed';
import camelCasePropsToDashCase from './camel-case-props-to-dash-case';
import mapObject from './map-object';
import {getPrefixedStyle} from './prefixer';
function createMarkupForStyles(style: Object): string {
return Object.keys(style).map(property => {
return property + ': ' + style[property] + ';';
}).join('\n');
}
export default function cssRuleSetToString(
selector: string,
rules: Object,
userAgent: ?string,
): string {
if (!rules) {
return '';
}
const prefixedRules = getPrefixedStyle(rules, userAgent);
const rulesWithPx = mapObject(
prefixedRules,
(value, key) => appendPxIfNeeded(key, value)
);
const cssPrefixedRules = camelCasePropsToDashCase(rulesWithPx);
const serializedRules = createMarkupForStyles(cssPrefixedRules);
return selector + '{' + serializedRules + '}';
}
|
Add `_RESOURCE_ROOT_` const for themes and plugins paths
Useful for multisite or some server configuration.
|
<?php
// PARVULA CMS
// Define some useful constants
if (!defined('_ROOT_')) {
define('_ROOT_', '');
}
if (!defined('_USER_ROOT_')) {
define('_USER_ROOT_', _ROOT_);
}
if (!defined('_RESOURCE_ROOT_')) {
define('_RESOURCE_ROOT_', _ROOT_);
}
define('_APP_', _ROOT_ . 'app/');
define('_DATA_', _USER_ROOT_ . 'data/');
define('_STATIC_', _USER_ROOT_ . 'static/');
define('_VENDOR_', _ROOT_ . 'vendor/');
// Data
define('_PAGES_', _DATA_ . 'pages/');
define('_CONFIG_', _DATA_ . 'config/');
define('_USERS_', _DATA_ . 'users/');
define('_LOGS_', _DATA_ . 'logs/');
// Static
define('_UPLOADS_', _STATIC_ . 'files/');
define('_COMPONENTS_', _STATIC_ . 'components/');
define('_BIN_', _APP_ . 'bin/');
define('_THEMES_', _RESOURCE_ROOT_ . 'themes/');
define('_PLUGINS_', _RESOURCE_ROOT_ . 'plugins/');
define('_VERSION_', '0.7.2');
require_once _APP_ . 'bootstrap.php';
|
<?php
// Define some useful constants
if (!defined('_ROOT_')) {
define('_ROOT_', '');
}
if (!defined('_USER_ROOT_')) {
define('_USER_ROOT_', '');
}
define('_APP_', _ROOT_ . 'app/');
define('_DATA_', _USER_ROOT_ . 'data/');
define('_STATIC_', _USER_ROOT_ . 'static/');
define('_VENDOR_', _ROOT_ . 'vendor/');
// Data
define('_PAGES_', _DATA_ . 'pages/');
define('_CONFIG_', _DATA_ . 'config/');
define('_USERS_', _DATA_ . 'users/');
define('_LOGS_', _DATA_ . 'logs/');
// Static
define('_UPLOADS_', _STATIC_ . 'files/');
define('_COMPONENTS_', _STATIC_ . 'components/');
define('_BIN_', _APP_ . 'bin/');
define('_THEMES_', _ROOT_ . 'themes/');
define('_PLUGINS_', _ROOT_ . 'plugins/');
define('_VERSION_', '0.7.1');
require_once _APP_ . 'bootstrap.php';
|
OAK-5793: Improve coverage for security code in oak-core
Missing license header
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1784852 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
|
package org.apache.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
|
Add update to period scheudle helper method
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
export class PeriodSchedule extends Realm.Object {
getUseablePeriodsForProgram(program, maxOrdersPerPeriod) {
const periods = this.periods.filter(
period => period.requisitionsForProgram(program) < maxOrdersPerPeriod
);
return periods;
}
addPeriodIfUnique(period) {
if (this.periods.filtered('id == $0', period.id).length > 0) return;
this.periods.push(period);
}
}
export default PeriodSchedule;
PeriodSchedule.schema = {
name: 'PeriodSchedule',
primaryKey: 'id',
properties: {
id: 'string',
name: { type: 'string', default: 'Placeholder Name' },
periods: { type: 'list', objectType: 'Period' },
},
};
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
export class PeriodSchedule extends Realm.Object {
getUseablePeriodsForProgram(program, maxOrdersPerPeriod) {
const periods = this.periods.filter(
period => period.numberOfRequisitionsForProgram(program) < maxOrdersPerPeriod
);
return periods;
}
addPeriodIfUnique(period) {
if (this.periods.filtered('id == $0', period.id).length > 0) return;
this.periods.push(period);
}
}
export default PeriodSchedule;
PeriodSchedule.schema = {
name: 'PeriodSchedule',
primaryKey: 'id',
properties: {
id: 'string',
name: { type: 'string', default: 'Placeholder Name' },
periods: { type: 'list', objectType: 'Period' },
},
};
|
Reset carousel timer when click prev/next buttons
|
/*
Carousel
*/
var prevBtn = document.getElementById("previous");
var slider = document.getElementById("slider");
var nextBtn = document.getElementById("next");
var currentSlide = 0;
function prevSlide() {
slider.children[currentSlide].classList.remove("myActive");
if (currentSlide === 0) {
currentSlide = slider.children.length - 1;
} else {
currentSlide--;
}
slider.children[currentSlide].classList.add("myActive");
}
function nextSlide() {
slider.children[currentSlide].classList.remove("myActive");
if (currentSlide === slider.children.length - 1) {
currentSlide = 0;
} else {
currentSlide++;
}
slider.children[currentSlide].classList.add("myActive");
}
var autoPlay = window.setInterval(nextSlide, 5000);
prevBtn.onclick = function() { window.clearInterval(autoPlay); prevSlide(); autoPlay = window.setInterval(nextSlide, 5000); };
nextBtn.onclick = function() { window.clearInterval(autoPlay); nextSlide(); autoPlay = window.setInterval(nextSlide, 5000); };
|
/*
Carousel
*/
var prevBtn = document.getElementById("previous");
var slider = document.getElementById("slider");
var nextBtn = document.getElementById("next");
var currentSlide = 0;
function prevSlide() {
slider.children[currentSlide].classList.remove("myActive");
if (currentSlide === 0) {
currentSlide = slider.children.length - 1;
} else {
currentSlide--;
}
slider.children[currentSlide].classList.add("myActive");
}
function nextSlide() {
slider.children[currentSlide].classList.remove("myActive");
if (currentSlide === slider.children.length - 1) {
currentSlide = 0;
} else {
currentSlide++;
}
slider.children[currentSlide].classList.add("myActive");
}
prevBtn.onclick = prevSlide;
nextBtn.onclick = nextSlide;
var autoPlay = window.setInterval(nextSlide, 5000);
|
Fix a bug where Java SCS did not generate TAN correct from file
|
package scs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
/**
* Created by mep on 26.11.14.
*/
public class FileParser {
private File file;
private String destination;
private String amount;
public FileParser(File file) {
this.file = file;
}
public void parse() throws IOException {
List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
for(String line : lines) {
if(line.startsWith("destination:")) {
destination = line.substring(12);
}
if(line.startsWith("amount:")) {
amount = line.substring(7);
// we are ready now !
return;
}
}
}
public String getDestination() {
return destination;
}
public String getAmount() {
return amount;
}
}
|
package scs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
/**
* Created by mep on 26.11.14.
*/
public class FileParser {
private File file;
private String destination;
private String amount;
public FileParser(File file) {
this.file = file;
}
public void parse() throws IOException {
List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
for(String line : lines) {
if(line.startsWith("destination:")) {
destination = line.substring(12);
}
if(line.startsWith("amount:")) {
amount = line.substring(8);
// we are ready now !
return;
}
}
}
public String getDestination() {
return destination;
}
public String getAmount() {
return amount;
}
}
|
Fix unicode in parsable text
|
from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
if mode not in ["rst","HTML"]:
raise Exception("Unknown text parser: "+ mode)
self.content = content
self.mode = mode
def parse(self):
"""Returns parsed text"""
if self.mode == "HTML":
return self.content
else:
return self.rst(self.content)
def __str__(self):
"""Returns parsed text"""
return self.parse()
def __unicode__(self):
"""Returns parsed text"""
return self.parse()
def rst(self,s):
"""Parses reStructuredText"""
parts = core.publish_parts(source=s,writer_name='html')
return parts['body_pre_docinfo']+parts['fragment']
|
from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
if mode not in ["rst","HTML"]:
raise Exception("Unknown text parser: "+ mode)
self.content = content
self.mode = mode
def parse(self):
"""Returns parsed text"""
if self.mode == "HTML":
return self.content
else:
return self.rst(self.content)
def __str__(self):
"""Returns parsed text"""
return self.parse()
def rst(self,s):
"""Parses reStructuredText"""
parts = core.publish_parts(source=s,writer_name='html')
return parts['body_pre_docinfo']+parts['fragment']
|
Add trial cumulative reward plot
|
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import universe
seed = 91231
n_trials = 20
n_steps = 1000
steps_to_reward = 14
max_reward = n_steps // steps_to_reward * 5.
uni = universe.Universe('grid_world', world='2d_world1')
uni.show()
reward = []
for i in range(n_trials):
reward_trial = []
np.random.seed(1234 + i)
uni.reset_agent_position()
uni.reset_agent_reward()
for _ in range(n_steps):
uni.step()
reward_trial.append(uni._agent._total_reward)
reward.append(reward_trial)
print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward))
for i in range(n_trials):
plt.plot(reward[i])
plt.show()
|
# -*- coding: utf-8 -*-
import numpy as np
import universe
seed = 91231
n_trials = 20
n_steps = 1000
steps_to_reward = 9
max_reward = n_steps // steps_to_reward * 5.
uni = universe.Universe('grid_world', world='2d_world0')
uni.show()
reward = []
for i in range(n_trials):
np.random.seed(1234 + i)
uni.reset_agent_position()
uni.reset_agent_reward()
for _ in range(n_steps):
uni.step()
reward.append(uni._agent._total_reward)
print('total reward after {steps} steps: {reward}/{max_reward}'.format(steps=n_steps, reward=uni._agent._total_reward, max_reward=max_reward))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.