text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix fatal error when Timber is not installed | <?php
class Maera_Development {
function __construct() {
if ( self::dev_mode() ) {
$this->jetpack_dev_mode();
$this->no_timber_caching();
}
}
/**
* Detect if dev mode is active OR if we're on the customizer
* @return bool
*/
public static function dev_mode() {
global $wp_customize;
$theme_options = get_option( 'maera_admin_options', array() );
if ( isset( $theme_options['dev_mode'] ) && 0 == $theme_options['dev_mode'] && ! isset( $wp_customize ) ) {
return false;
} else {
return true;
}
}
/**
* set JETPACK_DEV_DEBUG to true if not already defined
*/
function jetpack_dev_mode() {
if ( ! defined( 'JETPACK_DEV_DEBUG' ) ) {
define( 'JETPACK_DEV_DEBUG', true);
}
}
function no_timber_caching() {
// Early exit if TimberLoader does not exist
if ( ! class_exists( 'TimberLoader' ) ) {
return;
}
TimberLoader::CACHE_NONE;
}
}
| <?php
class Maera_Development {
function __construct() {
if ( self::dev_mode() ) {
$this->jetpack_dev_mode();
$this->no_timber_caching();
}
}
/**
* Detect if dev mode is active OR if we're on the customizer
* @return bool
*/
public static function dev_mode() {
global $wp_customize;
$theme_options = get_option( 'maera_admin_options', array() );
if ( isset( $theme_options['dev_mode'] ) && 0 == $theme_options['dev_mode'] && ! isset( $wp_customize ) ) {
return false;
} else {
return true;
}
}
/**
* set JETPACK_DEV_DEBUG to true if not already defined
*/
function jetpack_dev_mode() {
if ( ! defined( 'JETPACK_DEV_DEBUG' ) ) {
define( 'JETPACK_DEV_DEBUG', true);
}
}
function no_timber_caching() {
TimberLoader::CACHE_NONE;
}
}
|
Check if ability exists before seeding | <?php
declare(strict_types=1);
use Illuminate\Database\Seeder;
class CortexFoundationSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$abilities = [
['name' => 'access-adminarea', 'title' => 'Access adminarea'],
['name' => 'access-managerarea', 'title' => 'Access managerarea'],
['name' => 'list', 'title' => 'List media', 'entity_type' => 'media'],
['name' => 'create', 'title' => 'Create media', 'entity_type' => 'media'],
['name' => 'update', 'title' => 'Update media', 'entity_type' => 'media'],
['name' => 'delete', 'title' => 'Delete media', 'entity_type' => 'media'],
];
collect($abilities)->each(function (array $ability) {
app('cortex.auth.ability')->firstOrCreate([
'name' => $ability['name'],
'entity_type' => $ability['entity_type'],
], $ability);
});
}
}
| <?php
declare(strict_types=1);
use Illuminate\Database\Seeder;
class CortexFoundationSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$abilities = [
['name' => 'access-adminarea', 'title' => 'Access adminarea'],
['name' => 'access-managerarea', 'title' => 'Access managerarea'],
['name' => 'list', 'title' => 'List media', 'entity_type' => 'media'],
['name' => 'create', 'title' => 'Create media', 'entity_type' => 'media'],
['name' => 'update', 'title' => 'Update media', 'entity_type' => 'media'],
['name' => 'delete', 'title' => 'Delete media', 'entity_type' => 'media'],
];
collect($abilities)->each(function (array $ability) {
app('cortex.auth.ability')->create($ability);
});
}
}
|
Use python's built in system for percent-encoding | from urllib.request import urlopen, quote
import Utilities
FILENAME_CUE = "File:"
IMAGE_LOCATION_CUE = '<div class="fullMedia"><a href="https://upload.wikimedia.org/wikipedia/commons/'
IMAGE_LOCATION_URL_START = 'https://upload.wikimedia.org/wikipedia/commons/'
def directUrlOfFile(mediaPageURL):
"""Returns (success, url)"""
filenameStart = mediaPageURL.find(FILENAME_CUE) + len(FILENAME_CUE)
filename = mediaPageURL[filenameStart:]
filename_percent_encoded = quote(filename)
print(filename, filename_percent_encoded)
lines = urlopen(mediaPageURL).readlines()
for item in lines:
item = item.decode('utf-8')
item = item.replace('href="//', 'href="https://')
if item.find(IMAGE_LOCATION_CUE) == 0\
and filename_percent_encoded.replace('_','').replace(' ','') in item.replace('_','').replace(' ',''): # Remove spaces and underscores when checking, they seem inconsistent
indexOfCueEnd = item.index(IMAGE_LOCATION_CUE) + len(IMAGE_LOCATION_CUE)
image_location_short = item[indexOfCueEnd : item.find('"', indexOfCueEnd)]
image_location_full = IMAGE_LOCATION_URL_START + image_location_short
return True, image_location_full
return False, None | from urllib.request import urlopen
import Utilities
FILENAME_CUE = "File:"
IMAGE_LOCATION_CUE = '<div class="fullMedia"><a href="https://upload.wikimedia.org/wikipedia/commons/'
IMAGE_LOCATION_URL_START = 'https://upload.wikimedia.org/wikipedia/commons/'
def directUrlOfFile(mediaPageURL):
"""Returns (success, url)"""
filenameStart = mediaPageURL.find(FILENAME_CUE) + len(FILENAME_CUE)
filename = mediaPageURL[filenameStart:]
filename_percent_encoded = Utilities.percentEncode(filename)
print(filename, filename_percent_encoded)
lines = urlopen(mediaPageURL).readlines()
for item in lines:
item = item.decode('utf-8')
item = item.replace('href="//', 'href="https://')
if item.find(IMAGE_LOCATION_CUE) == 0\
and filename_percent_encoded.replace('_','').replace(' ','') in item.replace('_','').replace(' ',''): # Remove spaces and underscores when checking, they seem inconsistent
indexOfCueEnd = item.index(IMAGE_LOCATION_CUE) + len(IMAGE_LOCATION_CUE)
image_location_short = item[indexOfCueEnd : item.find('"', indexOfCueEnd)]
image_location_full = IMAGE_LOCATION_URL_START + image_location_short
return True, image_location_full
return False, None |
Set PHPFramework version to 1.5-dev | <?php
namespace AppZap\PHPFramework\Configuration;
use AppZap\PHPFramework\Mvc\ApplicationPartMissingException;
class DefaultConfiguration {
/**
* @param $application
* @throws ApplicationPartMissingException
*/
public static function initialize($application) {
$projectRoot = self::getProjectRoot();
$applicationDirectoryPath = $projectRoot . $application;
$applicationDirectory = realpath($applicationDirectoryPath);
if (!is_dir($applicationDirectory)) {
throw new ApplicationPartMissingException('Application folder ' . htmlspecialchars($applicationDirectoryPath) . ' not found', 1410538265);
}
$applicationDirectory .= '/';
Configuration::set('phpframework', 'db.migrator.directory', $applicationDirectory . '_sql/');
Configuration::set('phpframework', 'project_root', $projectRoot);
Configuration::set('application', 'application', $application);
Configuration::set('application', 'application_directory', $applicationDirectory);
Configuration::set('application', 'routes_file', $applicationDirectory . 'routes.php');
Configuration::set('application', 'templates_directory', $applicationDirectory . 'templates/');
Configuration::set('phpframework', 'version', '1.5-dev');
}
/**
* @return string
*/
protected static function getProjectRoot() {
if (isset($_ENV['AppZap\PHPFramework\ProjectRoot'])) {
$projectRoot = $_ENV['AppZap\PHPFramework\ProjectRoot'];
} else {
$projectRoot = getcwd();
}
$projectRoot = rtrim($projectRoot, '/') . '/';
return $projectRoot;
}
}
| <?php
namespace AppZap\PHPFramework\Configuration;
use AppZap\PHPFramework\Mvc\ApplicationPartMissingException;
class DefaultConfiguration {
/**
* @param $application
* @throws ApplicationPartMissingException
*/
public static function initialize($application) {
$projectRoot = self::getProjectRoot();
$applicationDirectoryPath = $projectRoot . $application;
$applicationDirectory = realpath($applicationDirectoryPath);
if (!is_dir($applicationDirectory)) {
throw new ApplicationPartMissingException('Application folder ' . htmlspecialchars($applicationDirectoryPath) . ' not found', 1410538265);
}
$applicationDirectory .= '/';
Configuration::set('phpframework', 'db.migrator.directory', $applicationDirectory . '_sql/');
Configuration::set('phpframework', 'project_root', $projectRoot);
Configuration::set('application', 'application', $application);
Configuration::set('application', 'application_directory', $applicationDirectory);
Configuration::set('application', 'routes_file', $applicationDirectory . 'routes.php');
Configuration::set('application', 'templates_directory', $applicationDirectory . 'templates/');
Configuration::set('phpframework', 'version', '1.4');
}
/**
* @return string
*/
protected static function getProjectRoot() {
if (isset($_ENV['AppZap\PHPFramework\ProjectRoot'])) {
$projectRoot = $_ENV['AppZap\PHPFramework\ProjectRoot'];
} else {
$projectRoot = getcwd();
}
$projectRoot = rtrim($projectRoot, '/') . '/';
return $projectRoot;
}
}
|
Use CC template for oneclick payments | <?php
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
namespace Adyen\Payment\Block\Info;
class Oneclick extends Cc
{
/**
* @var string
*/
protected $_template = 'Adyen_Payment::info/adyen_cc.phtml';
}
| <?php
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
namespace Adyen\Payment\Block\Info;
class Oneclick extends Cc
{
/**
* @var string
*/
protected $_template = 'Adyen_Payment::info/adyen_oneclick.phtml';
}
|
Check for bot.isAlive not needed | module.exports = inject
function inject (bot) {
bot.isAlive = true
bot._client.on('respawn', (packet) => {
bot.isAlive = false
bot.emit('respawn')
})
bot._client.once('update_health', (packet) => {
if (packet.health > 0) {
bot.emit('spawn')
}
})
bot._client.on('update_health', (packet) => {
bot.health = packet.health
bot.food = packet.food
bot.foodSaturation = packet.foodSaturation
bot.emit('health')
if (bot.health <= 0) {
bot.isAlive = false
bot.emit('death')
bot._client.write('client_command', { payload: 0 })
} else if (bot.health > 0 && !bot.isAlive) {
bot.isAlive = true
bot.emit('spawn')
}
})
}
| module.exports = inject
function inject (bot) {
bot.isAlive = true
bot._client.on('respawn', (packet) => {
bot.isAlive = false
bot.emit('respawn')
})
bot._client.once('update_health', (packet) => {
if (bot.isAlive && packet.health > 0) {
bot.emit('spawn')
}
})
bot._client.on('update_health', (packet) => {
bot.health = packet.health
bot.food = packet.food
bot.foodSaturation = packet.foodSaturation
bot.emit('health')
if (bot.health <= 0) {
bot.isAlive = false
bot.emit('death')
bot._client.write('client_command', { payload: 0 })
} else if (bot.health > 0 && !bot.isAlive) {
bot.isAlive = true
bot.emit('spawn')
}
})
}
|
Add explanatory note for the req-unixsockets version dependency | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=[
'pbr>=1.8',
'requests!=2.8.0,>=2.5.2',
# >= 0.1.5 needed for HTTP_PROXY support
'requests-unixsocket>=0.1.5',
],
pbr=True)
| # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=[
'pbr>=1.8',
'requests!=2.8.0,>=2.5.2',
'requests-unixsocket>=0.1.5',
],
pbr=True)
|
Store more data about a mod in the registry | import modinfo
import sys
class Mod():
"""The Mod class
This is supposed to act like a superclass for mods.
Execution order is as follows:
mod_load -> mod_complete
"""
def mod_info(self):
"""Get the mod info
Returns:
A tuple with the name, version, and author
"""
raise Exception("Mod info isn't overriden")
def mod_load(self):
"""Executes when a mod is loaded
This is where you put patcher code
Other mods may not be fully loaded yet. If you want this functionality, see mod_complete
"""
pass
def mod_complete(self):
"""Executes when all mods are loaded"""
pass
def loadable_mod(modclass):
"""Annotation to add a Mod subclass to the mod list
Args:
modclass (Mod): The Mod class
Raises:
Exception: If the given class is not a subclass of Mod
"""
if not issubclass(modclass, Mod):
raise Exception("Class must be a subclass of Mod")
mod = modclass() # Create a new instance of the class
mod_name, version, author = mod.mod_info()
mod.mod_load() # Load the mod
modinfo.add_mod(modclass.__module__, (mod, mod_name, version, author, sys.modules[modclass.__module__]))
| import modinfo
class Mod():
"""The Mod class
This is supposed to act like a superclass for mods.
Execution order is as follows:
mod_load -> mod_complete
"""
def mod_info(self):
"""Get the mod info
Returns:
A tuple with the name, version, and author
"""
raise Exception("Mod info isn't overriden")
def mod_load(self):
"""Executes when a mod is loaded
This is where you put patcher code
Other mods may not be fully loaded yet. If you want this functionality, see mod_complete
"""
pass
def mod_complete(self):
"""Executes when all mods are loaded"""
pass
def loadable_mod(modclass):
"""Annotation to add a Mod subclass to the mod list
Args:
modclass (Mod): The Mod class
Raises:
Exception: If the given class is not a subclass of Mod
"""
if not issubclass(modclass, Mod):
raise Exception("Class must be a subclass of Mod")
mod = modclass() # Create a new instance of the class
mod_name, _, _ = mod.mod_info() # Get just the mod name
mod.mod_load() # Load the mod
modinfo.add_mod(mod_name, mod)
|
Add location header to be a safe giver in CORS | package vaccination.security;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.setHeader("Access-Control-Expose-Headers", "Location");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
| package vaccination.security;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
|
Add method to retrieve all registered commands | package org.telegram.telegrambots.api.commands;
import java.util.Collection;
import java.util.Map;
/**
*
*/
public interface ICommandRegistery {
/**
* register a command
*
* @param command the command to register
* @return whether the command could be registered, was not already registered
*/
boolean register(Command command);
/**
* register multiple commands
*
* @param commands commands to register
* @return map with results of the command register per command
*/
Map<Command, Boolean> registerAll(Command... commands);
/**
* deregister a command
*
* @param command the command to deregister
* @return whether the command could be deregistered, was registered
*/
boolean deregister(Command command);
/**
* deregister multiple commands
*
* @param commands commands to deregister
* @return map with results of the command deregistered per command
*/
Map<Command, Boolean> deregisterAll(Command... commands);
/**
* get a collection of all registered commands
*
* @return a collection of registered commands
*/
Collection<Command> getRegisteredCommands();
} | package org.telegram.telegrambots.api.commands;
import java.util.Map;
/**
*
*/
public interface ICommandRegistery {
/**
* register a command
*
* @param command the command to register
* @return whether the command could be registered, was not already registered
*/
boolean register(Command command);
/**
* register multiple commands
*
* @param commands commands to register
* @return map with results of the command register per command
*/
Map<Command, Boolean> registerAll(Command... commands);
/**
* deregister a command
*
* @param command the command to deregister
* @return whether the command could be deregistered, was registered
*/
boolean deregister(Command command);
/**
* deregister multiple commands
*
* @param commands commands to deregister
* @return map with results of the command deregistered per command
*/
Map<Command, Boolean> deregisterAll(Command... commands);
} |
Add required attribute to Category name input | # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# You should have received a copy of the GNU Affero General Public License
# along with e-Giełda. If not, see <http://www.gnu.org/licenses/>.
from django import forms
from django.utils.translation import ugettext_lazy as _
from categories.models import Category
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = '__all__'
labels = {
'name': _("Name")
}
widgets = {
'name': forms.TextInput(attrs={'required': 'required'}),
}
| # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# You should have received a copy of the GNU Affero General Public License
# along with e-Giełda. If not, see <http://www.gnu.org/licenses/>.
from django import forms
from django.utils.translation import ugettext_lazy as _
from categories.models import Category
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = '__all__'
labels = {
'name': _("Name")
}
|
Fix typo in for_guest function.
`**kwrags**` should be `**kwargs**` | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "danger")
return redirect(url_for("login"))
return decorated_function
def for_guests(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Invalid Action.", "danger")
return redirect(url_for("dashboard"))
return decorated_function | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "danger")
return redirect(url_for("login"))
return decorated_function
def for_guests(f):
@wraps(f)
def decorated_function(*args, **kwrags):
if not 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Invalid Action.", "danger")
return redirect(url_for("dashboard"))
return decorated_function |
Revise "set preference" notification to be clearer
Notification message originally read as though it were in the
imperative when it is meant to be in past tense. | # yvs.set_pref
# coding=utf-8
from __future__ import unicode_literals
import json
import sys
import yvs.shared as shared
# Parse pref set data from the given JSON string
def parse_pref_set_data(pref_set_data_str):
pref_set_data = json.loads(pref_set_data_str)
return pref_set_data['pref'], pref_set_data['value']
# Set the YouVersion Suggest preference with the given key
def set_pref(pref_id, value_id):
user_prefs = shared.get_user_prefs()
user_prefs[pref_id] = value_id
# If new language is set, ensure that preferred version is updated also
if pref_id == 'language':
bible = shared.get_bible_data(language=value_id)
user_prefs['version'] = bible['default_version']
shared.set_user_prefs(user_prefs)
def main(pref_set_data_str):
pref, value = parse_pref_set_data(pref_set_data_str)
set_pref(pref['id'], value['id'])
print('Preferred {} set to {}'.format(
pref['name'].lower(), value['name']).encode('utf-8'))
if __name__ == '__main__':
main(sys.argv[1].decode('utf-8'))
| # yvs.set_pref
# coding=utf-8
from __future__ import unicode_literals
import json
import sys
import yvs.shared as shared
# Parse pref set data from the given JSON string
def parse_pref_set_data(pref_set_data_str):
pref_set_data = json.loads(pref_set_data_str)
return pref_set_data['pref'], pref_set_data['value']
# Set the YouVersion Suggest preference with the given key
def set_pref(pref_id, value_id):
user_prefs = shared.get_user_prefs()
user_prefs[pref_id] = value_id
# If new language is set, ensure that preferred version is updated also
if pref_id == 'language':
bible = shared.get_bible_data(language=value_id)
user_prefs['version'] = bible['default_version']
shared.set_user_prefs(user_prefs)
def main(pref_set_data_str):
pref, value = parse_pref_set_data(pref_set_data_str)
set_pref(pref['id'], value['id'])
print('Set preferred {} to {}'.format(
pref['name'].lower(), value['name']).encode('utf-8'))
if __name__ == '__main__':
main(sys.argv[1].decode('utf-8'))
|
Add failing test for DistArrayProxy.__setitem__ | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
| import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Update to use croogo default cache config | <?php
CroogoCache::config('switcher_default', array_merge(
Configure::read('Cache.defaultConfig'),
array('duration' => '+10 minutes')
));
Croogo::hookBehavior('Node', 'Switcher.Switcher');
Croogo::hookComponent('*', 'Switcher.Switcher');
Croogo::hookHelper('*', 'Switcher.Switcher');
Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node');
Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node');
CroogoNav::add('extensions.children.switcher', array(
'title' => 'Switcher',
'url' => '#',
'children' => array(
'paths' => array(
'title' => 'Paths',
'url' => array(
'admin' => true,
'plugin' => 'switcher',
'controller' => 'switcher_paths',
'action' => 'index',
),
'weight' => 10,
),
'nodes' => array(
'title' => 'Nodes',
'url' => array(
'admin' => true,
'plugin' => 'nodes',
'controller' => 'nodes',
'action' => 'index',
),
'weight' => 20,
),
),
));
| <?php
$cacheConfig = array(
'duration' => '+10 minutes',
'path' => CACHE . 'queries',
'engine' => 'File',
);
Cache::config('switcher_default', $cacheConfig);
Croogo::hookBehavior('Node', 'Switcher.Switcher');
Croogo::hookComponent('*', 'Switcher.Switcher');
Croogo::hookHelper('*', 'Switcher.Switcher');
Croogo::hookAdminTab('Nodes/admin_edit', 'Switcher', 'switcher.admin_tab_node');
Croogo::hookAdminTab('Nodes/admin_add', 'Switcher', 'switcher.admin_tab_node');
CroogoNav::add('extensions.children.switcher', array(
'title' => 'Switcher',
'url' => '#',
'children' => array(
'paths' => array(
'title' => 'Paths',
'url' => array(
'admin' => true,
'plugin' => 'switcher',
'controller' => 'switcher_paths',
'action' => 'index',
),
'weight' => 10,
),
'nodes' => array(
'title' => 'Nodes',
'url' => array(
'admin' => true,
'plugin' => 'nodes',
'controller' => 'nodes',
'action' => 'index',
),
'weight' => 20,
),
),
));
|
Include binaries when importing (for Windows). | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration library for the Worldforge system."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/varconf.git",
"revision": "auto"
}
def imports(self):
self.copy("*.dll", "bin", "bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/varconf-1.0"]
def package(self):
pass
| from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration library for the Worldforge system."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/varconf.git",
"revision": "auto"
}
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/varconf-1.0"]
def package(self):
pass
|
Include instance load in instance creation | /**
*
*/
package jp.ac.nii.prl.mape.monitoring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jp.ac.nii.prl.mape.monitoring.model.Instance;
@Service("instanceService")
public class InstanceServiceImpl implements InstanceService {
private final CloudWatchService cwService;
@Autowired
public InstanceServiceImpl(CloudWatchService cwService) {
this.cwService = cwService;
}
/* (non-Javadoc)
* @see jp.ac.nii.prl.mape.monitoring.service.InstanceService#fromAWS(com.amazonaws.services.ec2.model.Instance)
*/
@Override
public Instance fromAWS(com.amazonaws.services.ec2.model.Instance aws) {
Instance instance = new Instance();
instance.setAmi(aws.getImageId());
instance.setInstID(aws.getInstanceId());
instance.setInstStatus(0);
instance.setInstType(aws.getInstanceType());
instance.setSecurityGroupRef(aws.getSecurityGroups().iterator().next().getGroupId());
instance.setState(aws.getState().getCode());
instance.setLoad(cwService.getLoad(instance.getInstID()));
return instance;
}
}
| /**
*
*/
package jp.ac.nii.prl.mape.monitoring.service;
import org.springframework.stereotype.Service;
import jp.ac.nii.prl.mape.monitoring.model.Instance;
@Service("instanceService")
public class InstanceServiceImpl implements InstanceService {
/* (non-Javadoc)
* @see jp.ac.nii.prl.mape.monitoring.service.InstanceService#fromAWS(com.amazonaws.services.ec2.model.Instance)
*/
@Override
public Instance fromAWS(com.amazonaws.services.ec2.model.Instance aws) {
Instance instance = new Instance();
instance.setAmi(aws.getImageId());
instance.setInstID(aws.getInstanceId());
instance.setInstStatus(0);
instance.setInstType(aws.getInstanceType());
instance.setSecurityGroupRef(aws.getSecurityGroups().iterator().next().getGroupId());
instance.setState(aws.getState().getCode());
return instance;
}
}
|
Comment grammar - c’mon Bryant… | <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Setup\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
/**
* Prevent '/admin' from redirecting to '/careers/administrative-jobs/'
*/
function redirect_exceptions($redirect_url, $requested_url) {
if($requested_url==='admin') {
$redirect_url = $requested_url;
}
return $redirect_url;
}
add_filter('redirect_canonical', __NAMESPACE__ . '\\redirect_exceptions'); | <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Setup\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
/**
* Prevent '/admin' to redirect to '/careers/administrative-jobs/'
*/
function redirect_exceptions($redirect_url, $requested_url) {
if($requested_url==='admin') {
$redirect_url = $requested_url;
}
return $redirect_url;
}
add_filter('redirect_canonical', __NAMESPACE__ . '\\redirect_exceptions'); |
Refactor get line order functionality into its own function. | $(function() {
$('#answerQuestion').click(function(e) {
$.ajax({
url: '/question/' + e.target.value,
type: 'POST',
data: {'answer': JSON.stringify(getLineOrder())},
success: function(response) {
$('#result').html(response);
},
});
});
$('#lines').sortable({containment: "parent"});
$('#lines').disableSelection();
});
function getLineOrder() {
var lineOrders = $('#lines').sortable('toArray', {attribute: 'lineNum'});
var res = [];
for (var i = 0; i < lineOrders.length; i++) {
if (lineOrders[i]) {
res.push(parseInt(lineOrders[i]));
}
}
return res;
}
| $(function() {
$('#answerQuestion').click(function(e) {
var lineOrders = $('#lines').sortable('toArray', {attribute: 'lineNum'});
var ans = [];
for (var i = 0; i < lineOrders.length; i++) {
if (lineOrders[i]) {
ans.push(parseInt(lineOrders[i]));
}
}
console.log();
$.ajax({
url: '/question/' + e.target.value,
type: 'POST',
data: {'answer': JSON.stringify(ans)},
success: function(response) {
$('#result').html(response);
},
});
});
$('#lines').sortable({containment: "parent"});
$('#lines').disableSelection();
});
|
Add unittests for BMKG EQ List Scrapper | # coding=utf-8
import logging
import unittest
from django import test
from timeout_decorator import timeout_decorator
from realtime.app_settings import LOGGER_NAME
from realtime.tasks import check_realtime_broker, \
retrieve_felt_earthquake_list
from realtime.tasks.realtime.celery_app import app as realtime_app
from realtime.utils import celery_worker_connected
__author__ = 'Rizky Maulana Nugraha <lana.pcfre@gmail.com>'
__date__ = '12/4/15'
LOGGER = logging.getLogger(LOGGER_NAME)
# minutes test timeout
LOCAL_TIMEOUT = 10 * 60
class CeleryTaskTest(test.SimpleTestCase):
@timeout_decorator.timeout(LOCAL_TIMEOUT)
@unittest.skipUnless(
celery_worker_connected(realtime_app, 'inasafe-realtime'),
'Realtime Worker needs to be run')
def test_indicator(self):
"""Test broker connection."""
result = check_realtime_broker.delay()
self.assertTrue(result.get())
@timeout_decorator.timeout(LOCAL_TIMEOUT)
@unittest.skipUnless(
celery_worker_connected(realtime_app, 'inasafe-django'),
'Realtime Worker needs to be run')
def test_indicator(self):
"""Test broker connection."""
result = retrieve_felt_earthquake_list.delay()
self.assertTrue(result.get())
| # coding=utf-8
import logging
import unittest
from django import test
from timeout_decorator import timeout_decorator
from realtime.app_settings import LOGGER_NAME
from realtime.tasks import check_realtime_broker
from realtime.tasks.realtime.celery_app import app as realtime_app
from realtime.utils import celery_worker_connected
__author__ = 'Rizky Maulana Nugraha <lana.pcfre@gmail.com>'
__date__ = '12/4/15'
LOGGER = logging.getLogger(LOGGER_NAME)
# minutes test timeout
LOCAL_TIMEOUT = 10 * 60
class CeleryTaskTest(test.SimpleTestCase):
@timeout_decorator.timeout(LOCAL_TIMEOUT)
@unittest.skipUnless(
celery_worker_connected(realtime_app, 'inasafe-realtime'),
'Realtime Worker needs to be run')
def test_indicator(self):
"""Test broker connection."""
result = check_realtime_broker.delay()
self.assertTrue(result.get())
|
Remove clean from hot-dev gulp sequence so tests can still run locally using build js | import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'webpack-build',
'cached-lintjs-watch'
], 'watch')
);
gulp.task('hot-dev', () =>
runSequence('set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], 'webpack-dev', 'watch')
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack-build', 'minify', cb)
);
| import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'webpack-build',
'cached-lintjs-watch'
], 'watch')
);
gulp.task('hot-dev', () =>
runSequence('clean', 'set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], 'webpack-dev', 'watch')
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack-build', 'minify', cb)
);
|
Allow cache time to be set from the command line. | var express = require('express');
//var config = require('./config');
var playsApp = require('radio-plays');
var logfmt = require("logfmt");
var app = express();
var plays = playsApp({
source: 'Spinitron',
spinitron: {
station: process.env.SPIN_STATION,
userid: process.env.SPIN_USERID,
secret: process.env.SPIN_SECRET
},
maxAge: Number(process.env.CACHE_TIME || 15000)
});
app.use(logfmt.requestLogger());
app.get('/nowplaying', function(req, res){
res.send(plays.recentPlays(1)[0]);
});
app.get('/recentplays/:num', function(req, res){
res.send(plays.recentPlays(Number(req.params.num)));
});
var port = Number(process.env.PORT || 3000);
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});
| var express = require('express');
//var config = require('./config');
var playsApp = require('radio-plays');
var logfmt = require("logfmt");
var app = express();
var plays = playsApp({
source: 'Spinitron',
spinitron: {
station: process.env.SPIN_STATION,
userid: process.env.SPIN_USERID,
secret: process.env.SPIN_SECRET
}
});
app.use(logfmt.requestLogger());
app.get('/nowplaying', function(req, res){
res.send(plays.recentPlays(1)[0]);
});
app.get('/recentplays/:num', function(req, res){
res.send(plays.recentPlays(Number(req.params.num)));
});
var port = Number(process.env.PORT || 3000);
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});
|
Remove noisy & pointless comment | var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var SIGNATURE = '__signature_' + require('hat')();
exports.parse = parse;
function parse (fn) {
if (typeof fn !== 'function') {
throw new TypeError("Not a function: " + fn);
}
if (!fn[SIGNATURE]) {
fn[SIGNATURE] = _parse(fn);
}
return fn[SIGNATURE];
}
exports.clobber = clobber;
function clobber (fn, names) {
fn[SIGNATURE] = names;
return fn;
}
exports.copy = copy;
function copy (fromFn, toFn) {
toFn[SIGNATURE] = fromFn[SIGNATURE] || _parse(fromFn);
return toFn;
}
/**
* This code is adapted from the AngularJS v1 dependency injector
*/
function _parse (fn) {
var fnText = fn.toString().replace(STRIP_COMMENTS, '');
var argDecl = fnText.match(FN_ARGS);
return argDecl[1].split(FN_ARG_SPLIT).map(function(arg){
return arg.replace(FN_ARG, function(all, underscore, name){
return name;
});
}).filter(Boolean);
}
| // source:
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var SIGNATURE = '__signature_' + require('hat')();
exports.parse = parse;
function parse (fn) {
if (typeof fn !== 'function') {
throw new TypeError("Not a function: " + fn);
}
if (!fn[SIGNATURE]) {
fn[SIGNATURE] = _parse(fn);
}
return fn[SIGNATURE];
}
exports.clobber = clobber;
function clobber (fn, names) {
fn[SIGNATURE] = names;
return fn;
}
exports.copy = copy;
function copy (fromFn, toFn) {
toFn[SIGNATURE] = fromFn[SIGNATURE] || _parse(fromFn);
return toFn;
}
/**
* This code is adapted from the AngularJS v1 dependency injector
*/
function _parse (fn) {
var fnText = fn.toString().replace(STRIP_COMMENTS, '');
var argDecl = fnText.match(FN_ARGS);
return argDecl[1].split(FN_ARG_SPLIT).map(function(arg){
return arg.replace(FN_ARG, function(all, underscore, name){
return name;
});
}).filter(Boolean);
}
|
Use proper Mongo collection name. | Categories = new Mongo.Collection("categories");
Category = Astro.Class({
name: 'Category',
collection: Categories,
fields: {
name: {
type: 'string',
validator: [
Validators.required(null, "Type in a name for your Category."),
Validators.unique(null, "A category with this name already exists."),
Validators.minLength(4, "Your category name has to be at least 4 letters."),
Validators.maxLength(100, "Your category name can't be bigger than 100 letters.")
]
},
slug: {
type: 'string',
validator: [
Validators.unique(null, "A category with this name already exists.")
]
},
createdAt: {
type: 'date',
validator: [
Validators.required(),
]
},
totalListings: {
type: 'number'
}
},
methods: {
updateListingCount() {
Meteor.call("Category.updateListingCount", this._id);
},
generateSlug: function() {
var self = this;
Meteor.call("Helpers.generateSlug", this.name, function(error, response) {
self.set('slug', response);
});
}
}
});
| Categories = new Mongo.Collection("communities");
Category = Astro.Class({
name: 'Category',
collection: Categories,
fields: {
name: {
type: 'string',
validator: [
Validators.required(null, "Type in a name for your Category."),
Validators.unique(null, "A category with this name already exists."),
Validators.minLength(4, "Your category name has to be at least 4 letters."),
Validators.maxLength(100, "Your category name can't be bigger than 100 letters.")
]
},
slug: {
type: 'string',
validator: [
Validators.unique(null, "A category with this name already exists.")
]
},
createdAt: {
type: 'date',
validator: [
Validators.required(),
]
},
totalListings: {
type: 'number'
}
},
methods: {
updateListingCount() {
Meteor.call("Category.updateListingCount", this._id);
},
generateSlug: function() {
var self = this;
Meteor.call("Helpers.generateSlug", this.name, function(error, response) {
self.set('slug', response);
});
}
}
});
|
Swap arguments to make encoding/decoding commands more natural | const logger = require('../logger')
const slackEncoder = require('../slack-encoder')
module.exports = (controller) => {
controller.hears([/base64 encode (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], x => Buffer.from(x).toString('base64'))
})
controller.hears([/base64 decode (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], (x) => Buffer.from(x, 'base64').toString('utf8'))
})
controller.hears([/url encode (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], encodeURIComponent)
})
controller.hears([/url decode (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], decodeURIComponent)
})
logger.info('Loaded slack-users skill')
}
const transform = (bot, message, match, transformer) => {
logger.info('transforming', match)
var result = transformer(slackEncoder.decode(match))
bot.reply(message, slackEncoder.encode(result))
}
| const logger = require('../logger')
const slackEncoder = require('../slack-encoder')
module.exports = (controller) => {
controller.hears([/encode base64 (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], x => Buffer.from(x).toString('base64'))
})
controller.hears([/decode base64 (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], (x) => Buffer.from(x, 'base64').toString('utf8'))
})
controller.hears([/encode url (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], encodeURIComponent)
})
controller.hears([/decode url (.*)$/i,], ['direct_message','direct_mention'], (bot, message) => {
transform(bot, message, message.match[1], decodeURIComponent)
})
logger.info('Loaded slack-users skill')
}
const transform = (bot, message, match, transformer) => {
logger.info('transforming', match)
var result = transformer(slackEncoder.decode(match))
bot.reply(message, slackEncoder.encode(result))
}
|
Fix jshint warnings in benchmark | /** @license MIT License (c) copyright 2010-2013 original author or authors */
/**
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Brian Cavalier
* @author: John Hann
*/
(function(define) { 'use strict';
define(function(require) {
var when, tests, run;
when = require('../when');
run = require('./run');
tests = [
{ name: 'map 100', fn: map(100), defer: true },
{ name: 'map 1k', fn: map(1e3), defer: true }
];
run(tests);
//
// Benchmark tests
//
function map(n) {
return function(deferred) {
var input = [];
for(var i = 0; i < n; i++) {
input.push(when(i));
}
when.map(input, addOne).then(function() {
deferred.resolve();
});
};
}
//
// Promise helpers
//
function addOne(x) {
return x + 1;
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
| /** @license MIT License (c) copyright 2010-2013 original author or authors */
/**
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Brian Cavalier
* @author: John Hann
*/
(function(define) { 'use strict';
define(function(require) {
var when, tests, run, input;
when = require('../when');
run = require('./run');
tests = [
{ name: 'map 100', fn: map(100), defer: true },
{ name: 'map 1k', fn: map(1e3), defer: true }
];
run(tests);
//
// Benchmark tests
//
function map(n) {
return function(deferred) {
var input = [];
for(var i = 0; i < n; i++) {
input.push(when(i));
}
when.map(input, addOne).then(function(r) {
deferred.resolve();
});
};
}
//
// Promise helpers
//
function addOne(x) {
return x + 1;
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
|
Remove use of eval in dev
This violates Codesandbox' CSP which does not permit unsafe-eval.
Instead, just use window to get the current global.
Fixes #6611 | if (__DEV__) {
if (typeof window !== "undefined") {
const global = window;
const key = "__react_router_build__";
const buildNames = { cjs: "CommonJS", esm: "ES modules", umd: "UMD" };
if (global[key] && global[key] !== process.env.BUILD_FORMAT) {
const initialBuildName = buildNames[global[key]];
const secondaryBuildName = buildNames[process.env.BUILD_FORMAT];
// TODO: Add link to article that explains in detail how to avoid
// loading 2 different builds.
throw new Error(
`You are loading the ${secondaryBuildName} build of React Router ` +
`on a page that is already running the ${initialBuildName} ` +
`build, so things won't work right.`
);
}
global[key] = process.env.BUILD_FORMAT;
}
}
export { default as MemoryRouter } from "./MemoryRouter";
export { default as Prompt } from "./Prompt";
export { default as Redirect } from "./Redirect";
export { default as Route } from "./Route";
export { default as Router } from "./Router";
export { default as StaticRouter } from "./StaticRouter";
export { default as Switch } from "./Switch";
export { default as generatePath } from "./generatePath";
export { default as matchPath } from "./matchPath";
export { default as withRouter } from "./withRouter";
export { default as __RouterContext } from "./RouterContext";
| if (__DEV__) {
const global = (1, eval)("this");
const key = "__react_router_build__";
const buildNames = { cjs: "CommonJS", esm: "ES modules", umd: "UMD" };
if (global[key] && global[key] !== process.env.BUILD_FORMAT) {
const initialBuildName = buildNames[global[key]];
const secondaryBuildName = buildNames[process.env.BUILD_FORMAT];
// TODO: Add link to article that explains in detail how to avoid
// loading 2 different builds.
throw new Error(
`You are loading the ${secondaryBuildName} build of React Router ` +
`on a page that is already running the ${initialBuildName} ` +
`build, so things won't work right.`
);
}
global[key] = process.env.BUILD_FORMAT;
}
export { default as MemoryRouter } from "./MemoryRouter";
export { default as Prompt } from "./Prompt";
export { default as Redirect } from "./Redirect";
export { default as Route } from "./Route";
export { default as Router } from "./Router";
export { default as StaticRouter } from "./StaticRouter";
export { default as Switch } from "./Switch";
export { default as generatePath } from "./generatePath";
export { default as matchPath } from "./matchPath";
export { default as withRouter } from "./withRouter";
export { default as __RouterContext } from "./RouterContext";
|
Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply | from bot.action.core.action import Action
from bot.action.standard.info.formatter.chat import ChatInfoFormatter
from bot.action.standard.info.formatter.user import UserInfoFormatter
class MeInfoAction(Action):
def process(self, event):
formatter = UserInfoFormatter(self.api, event.message.from_, event.chat)
formatter.format(member_info=True)
response = formatter.get_formatted()
self.api.send_message(response.build_message().to_chat_replying(event.message))
class UserInfoAction(Action):
def process(self, event):
message = event.message
replied_message = message.reply_to_message
if replied_message is None:
user = message.from_
else:
user = replied_message.from_
formatter = UserInfoFormatter(self.api, user, event.chat)
formatter.format(member_info=True)
response = formatter.get_formatted()
self.api.send_message(response.build_message().to_chat_replying(event.message))
class ChatInfoAction(Action):
def process(self, event):
formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_)
formatter.format(full_info=True)
response = formatter.get_formatted()
self.api.send_message(response.build_message().to_chat_replying(event.message))
| from bot.action.core.action import Action
from bot.action.standard.info.formatter.chat import ChatInfoFormatter
from bot.action.standard.info.formatter.user import UserInfoFormatter
class MeInfoAction(Action):
def process(self, event):
formatter = UserInfoFormatter(self.api, event.message.from_, event.chat)
formatter.format(member_info=True)
response = formatter.get_formatted()
self.api.send_message(response.build_message().to_chat_replying(event.message))
class ChatInfoAction(Action):
def process(self, event):
formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_)
formatter.format(full_info=True)
response = formatter.get_formatted()
self.api.send_message(response.build_message().to_chat_replying(event.message))
|
Add test to ensure files without goog.defineClass are skipped | const expect = require('chai').expect;
const fs = require('fs');
const path = require('path');
const pluginRunner = require('../lib/plugin_runner');
describe('goog.defineClass to ES6 class', () => {
const convert = function(fileName) {
const testFilePath = path.join(__dirname, fileName);
// Add new line at the end to match the expected file.
return pluginRunner.run(testFilePath);
};
const readFile = function(fileName) {
return fs.readFileSync(path.join(__dirname, fileName), 'utf8');
};
it('converts file to es6', () => {
expect(convert('with_statics_es5.js')).to.equal(
readFile('with_statics_es6.js'));
});
it('converts file with parent', () => {
expect(convert('inheritance_es5.js')).to.equal(
readFile('inheritance_es6.js'));
});
it('converts statics', function() {
expect(convert('static_functions_es5.js')).to.equal(
readFile('static_functions_es6.js'));
});
it('skips file without goog.defineClass', function() {
// A file without goog.defineClass will be skipped.
expect(convert('without_goog_define_class.js')).to.equal(
readFile('without_goog_define_class.js'));
});
});
| const expect = require('chai').expect;
const fs = require('fs');
const path = require('path');
const pluginRunner = require('../lib/plugin_runner');
describe('goog.defineClass to ES6 class', () => {
const convert = function(fileName) {
const testFilePath = path.join(__dirname, fileName);
// Add new line at the end to match the expected file.
return pluginRunner.run(testFilePath);
};
const readFile = function(fileName) {
return fs.readFileSync(path.join(__dirname, fileName), 'utf8');
};
it('converts file to es6', () => {
expect(convert('with_statics_es5.js')).to.equal(
readFile('with_statics_es6.js'));
});
it('converts file with parent', () => {
expect(convert('inheritance_es5.js')).to.equal(
readFile('inheritance_es6.js'));
});
it('converts statics', function() {
expect(convert('static_functions_es5.js')).to.equal(
readFile('static_functions_es6.js'));
});
});
|
Fix old production library names... 4a9833c | module.exports = {
options: {
baseUrl : "src/app",
mainConfigFile: "src/app/config.js",
name: "",
out : "build/tmp/app/main.js",
include: [ "main" ],
findNestedDependencies: true,
generateSourceMaps : false,
optimize : "none",
skipModuleInsertion: false,
wrap : false,
skipSemiColonInsertion : true,
useStrict : true,
preserveLicenseComments: true
},
dev: {
options: {
generateSourceMaps: true
}
},
release: {
options: {
paths: {
"Ember" : "../vendor/ember/ember.prod",
"EmberData": "../vendor/ember-data/ember-data.prod"
}
}
}
};
| module.exports = {
options: {
baseUrl : "src/app",
mainConfigFile: "src/app/config.js",
name: "",
out : "build/tmp/app/main.js",
include: [ "main" ],
findNestedDependencies: true,
generateSourceMaps : false,
optimize : "none",
skipModuleInsertion: false,
wrap : false,
skipSemiColonInsertion : true,
useStrict : true,
preserveLicenseComments: true
},
dev: {
options: {
generateSourceMaps: true
}
},
release: {
options: {
/*
* Do not use dev versions for release builds
*
* Defining two versions in the config file and mapping the names for a release build
* doesn't seem to work here. So we need to overwrite the paths in the grunt config :(
* https://gist.github.com/askesian/6e05daa443ca1955ea32
*/
paths: {
"ember" : "../vendor/ember/ember.prod",
"ember-data": "../vendor/ember-data/ember-data.prod"
}
}
}
};
|
Fix test 184 for python 3 | import sys
from numba import *
import numpy as np
@jit(object_(double[:, :]))
def func2(A):
L = []
n = A.shape[0]
for i in range(10):
for j in range(10):
temp = A[i-n : i+n+1, j-2 : j+n+1]
L.append(temp)
return L
A = np.empty(1000000, dtype=np.double).reshape(1000, 1000)
refcnt = sys.getrefcount(A)
func2(A)
new_refcnt = sys.getrefcount(A)
assert refcnt == new_refcnt
normal_result = list(map(sys.getrefcount, func2.py_func(A)))
numba_result = list(map(sys.getrefcount, func2(A)))
assert normal_result == numba_result
| import sys
from numba import *
import numpy as np
@jit(object_(double[:, :]))
def func2(A):
L = []
n = A.shape[0]
for i in range(10):
for j in range(10):
temp = A[i-n : i+n+1, j-2 : j+n+1]
L.append(temp)
return L
A = np.empty(1000000, dtype=np.double).reshape(1000, 1000)
refcnt = sys.getrefcount(A)
func2(A)
new_refcnt = sys.getrefcount(A)
assert refcnt == new_refcnt
normal_result = map(sys.getrefcount, func2.py_func(A))
numba_result = map(sys.getrefcount, func2(A))
assert normal_result == numba_result
|
Fix bug: pasting structure destructively adds to location | package me.jacobcrofts.simplestructureloader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public final class StructureAPI {
private StructureAPI() {}
public static void writeToFile(String filename, Selection selection) throws IOException {
File structures = new File("plugins/structures");
if (!(structures.exists())) {
structures.mkdirs();
}
FileWriter writer = new FileWriter("plugins/structures/" + filename + ".json");
writer.write(selection.toJSON().toJSONString());
writer.close();
}
public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException {
return (JSONArray) new JSONParser().parse(new FileReader(path));
}
@SuppressWarnings("deprecation")
public static void placeStructure(Selection selection, Location baseLocation) {
for (SavedBlock savedBlock : selection.getSavedBlocks()) {
Block realBlock = baseLocation.clone().add(savedBlock.getRelativeX(), savedBlock.getRelativeY(), savedBlock.getRelativeZ()).getBlock();
realBlock.setType(savedBlock.getType());
realBlock.setData(savedBlock.getData());
}
}
}
| package me.jacobcrofts.simplestructureloader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public final class StructureAPI {
private StructureAPI() {}
public static void writeToFile(String filename, Selection selection) throws IOException {
File structures = new File("plugins/structures");
if (!(structures.exists())) {
structures.mkdirs();
}
FileWriter writer = new FileWriter("plugins/structures/" + filename + ".json");
writer.write(selection.toJSON().toJSONString());
writer.close();
}
public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException {
return (JSONArray) new JSONParser().parse(new FileReader(path));
}
@SuppressWarnings("deprecation")
public static void placeStructure(Selection selection, Location baseLocation) {
for (SavedBlock block : selection.getSavedBlocks()) {
Block realBlock = baseLocation.add(block.getRelativeX(), block.getRelativeY(), block.getRelativeZ()).getBlock();
realBlock.setType(block.getType());
realBlock.setData(block.getData());
}
}
}
|
Update model to populate on save if record is returned from adapter | <?php
namespace Bolt;
use Bolt\Interfaces\Connection;
abstract class Model extends Base
{
protected $adapter;
public function __construct(Connection $connection = null, $data = null)
{
$this->adapter($connection);
if ($data !== null)
{
parent::__construct($data);
}
}
public function adapter(Connection $connection = null)
{
if ($connection !== null)
{
$className = $this->className(false);
$className = "App\\Adapters\\Models\\" . $className . "\\" . $connection->className(false);
$this->adapter = new $className($connection, $this);
return true;
}
return $this->adapter;
}
public function load()
{
$data = $this->adapter->load();
if ($data === false)
{
return false;
}
$this->populate($data);
return true;
}
public function save()
{
$data = $this->adapter->save();
if ($data === false)
{
return false;
}
if ($data !== true)
{
$this->populate($data);
}
return true;
}
}
?>
| <?php
namespace Bolt;
use Bolt\Interfaces\Connection;
abstract class Model extends Base
{
protected $adapter;
public function __construct(Connection $connection = null, $data = null)
{
$this->adapter($connection);
if ($data !== null)
{
parent::__construct($data);
}
}
public function adapter(Connection $connection = null)
{
if ($connection !== null)
{
$className = $this->className(false);
$className = "App\\Adapters\\Models\\" . $className . "\\" . $connection->className(false);
$this->adapter = new $className($connection, $this);
return true;
}
return $this->adapter;
}
public function load()
{
$data = $this->adapter->load();
if ($data === false)
{
return false;
}
$this->populate($data);
return true;
}
public function save()
{
return $this->adapter->save();
}
}
?>
|
Fix a breakage of the job details page.
This was an uncaught casualty of #1504. | import router from 'girder/router';
import events from 'girder/events';
import JobModel from './models/JobModel';
import JobDetailsWidget from './views/JobDetailsWidget';
import JobListWidget from './views/JobListWidget';
router.route('job/:id', 'jobView', function (id) {
var job = new JobModel({_id: id}).once('g:fetched', function () {
events.trigger('g:navigateTo', JobDetailsWidget, {
job: job,
renderImmediate: true
});
}, this).once('g:error', function () {
router.navigate('collections', {trigger: true});
}, this);
job.fetch();
});
router.route('jobs/user/:id', 'jobList', function (id) {
events.trigger('g:navigateTo', JobListWidget, {
filter: {userId: id}
});
});
| import router from 'girder/router';
import events from 'girder/events';
import JobModel from './models/JobModel';
import JobDetailsWidget from './views/JobDetailsWidget';
router.route('job/:id', 'jobView', function (id) {
var job = new JobModel({_id: id}).once('g:fetched', function () {
events.trigger('g:navigateTo', JobDetailsWidget, {
job: job,
renderImmediate: true
});
}, this).once('g:error', function () {
router.navigate('collections', {trigger: true});
}, this).fetch();
});
import JobListWidget from './views/JobListWidget';
router.route('jobs/user/:id', 'jobList', function (id) {
events.trigger('g:navigateTo', JobListWidget, {
filter: {userId: id}
});
});
|
Add test to consider message analysis | var expect = require('chai').expect;
var consider = require('./helpers/consider');
var elda = require('../lib/api.js');
describe('API', function() {
var instance;
beforeEach(function() {
instance = elda();
});
describe('respondTo', function() {
it('should be exposed as a function', function() {
expect(typeof instance.respondTo).to.equal('function');
});
it('should return a promise', function() {
var actual = instance.respondTo();
expect(typeof actual.then).to.equal('function');
});
it('should reject empty or null messages with an exception', function(done) {
instance.respondTo(null).then(function() {
done('Unexpected success');
}, function(ex) {
consider(function() {
expect(ex).to.equal('No message provided');
}, done);
});
});
it('should analyse and respond to a message', function(done) {
var expected = 'instruction';
instance.respondTo(expected).then(function(actual) {
consider(function() {
expect(actual).to.equal('Received message: ' + expected);
}, done);
}, function(ex) {
done(ex);
});
});
});
});
| var expect = require('chai').expect;
var consider = require('./helpers/consider');
var elda = require('../lib/api.js');
describe('API', function() {
var instance;
beforeEach(function() {
instance = elda();
});
describe('respondTo', function() {
it('should be exposed as a function', function(done) {
expect(typeof instance.respondTo).to.equal('function');
done();
});
it('should return a promise', function() {
var actual = instance.respondTo();
expect(typeof actual.then).to.equal('function');
});
it('should reject empty or null messages with an exception', function(done) {
instance.respondTo(null).then(function() {
done('Unexpected success');
}, function(ex) {
consider(function() {
expect(ex).to.equal('No message provided');
}, done);
});
});
it('should analyse and respond to a message', function(done) {
var expected = 'instruction';
instance.respondTo(expected).then(function(actual) {
consider(function() {
expect(actual).to.equal('Received message: ' + expected);
}, done);
}, function(ex) {
done(ex);
});
});
});
});
|
Rename list_flavors flavors in example
Change-Id: Idf699774484a29fa9e9bb1bf654ed00d6ca9907d | # 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.
"""
Example Connection Command
Make sure you can authenticate before running this command.
For example:
python -m examples.connection
"""
import sys
import os_client_config
from examples import common
from openstack import connection
def make_connection(opts):
occ = os_client_config.OpenStackConfig()
cloud = occ.get_one_cloud(opts.cloud, opts)
auth = cloud.config['auth']
conn = connection.Connection(preference=opts.user_preferences, **auth)
return conn
def run_connection(opts):
conn = make_connection(opts)
print("Connection: %s" % conn)
for flavor in conn.compute.flavors():
print(flavor.id + " " + flavor.name)
return
if __name__ == "__main__":
opts = common.setup()
sys.exit(common.main(opts, run_connection))
| # 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.
"""
Example Connection Command
Make sure you can authenticate before running this command.
For example:
python -m examples.connection
"""
import sys
import os_client_config
from examples import common
from openstack import connection
def make_connection(opts):
occ = os_client_config.OpenStackConfig()
cloud = occ.get_one_cloud(opts.cloud, opts)
auth = cloud.config['auth']
conn = connection.Connection(preference=opts.user_preferences, **auth)
return conn
def run_connection(opts):
conn = make_connection(opts)
print("Connection: %s" % conn)
for flavor in conn.compute.list_flavors():
print(flavor.id + " " + flavor.name)
return
if __name__ == "__main__":
opts = common.setup()
sys.exit(common.main(opts, run_connection))
|
Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru> | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
| #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
|
Use Django’s crypto code to generate random code.
Many thanks to Cédric Picard for his extensive
security report. | """ Generic helper functions """
import logging
from django.contrib.sites.models import Site
from django.utils.crypto import get_random_string
logger = logging.getLogger(__name__)
# Possible actions that user can perform
ACTIONS = ('subscribe', 'unsubscribe', 'update')
def make_activation_code():
""" Generate a unique activation code. """
# Use Django's crypto get_random_string() instead of rolling our own.
return get_random_string(length=40)
def get_default_sites():
""" Get a list of id's for all sites; the default for newsletters. """
return [site.id for site in Site.objects.all()]
class Singleton(type):
"""
Singleton metaclass.
Source:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(
*args, **kwargs
)
return cls._instances[cls]
| """ Generic helper functions """
import logging
import random
from datetime import datetime
from hashlib import sha1
from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes
logger = logging.getLogger(__name__)
# Possible actions that user can perform
ACTIONS = ('subscribe', 'unsubscribe', 'update')
def make_activation_code():
""" Generate a unique activation code. """
random_string = str(random.random())
random_digest = sha1(force_bytes(random_string)).hexdigest()[:5]
time_string = str(datetime.now().microsecond)
combined_string = random_digest + time_string
return sha1(force_bytes(combined_string)).hexdigest()
def get_default_sites():
""" Get a list of id's for all sites; the default for newsletters. """
return [site.id for site in Site.objects.all()]
class Singleton(type):
"""
Singleton metaclass.
Source:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(
*args, **kwargs
)
return cls._instances[cls]
|
Add cssmin to Grunt task ‘build’ | module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
},
src: 'src/progress-button.css',
dest: 'dist/progress-button.min.css'
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
| module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
|
Fix for non-DRMAA cluster run |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
|
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
|
Add scope_types for revoke event policies
This commit associates `system` to revoke event policies, since these
policies were developed to assist the system in offline token
validation.
From now on, a warning will be logged when a project-scoped token is
used to get revocation events. Operators can opt into requiring
system-scoped tokens for these policies by enabling oslo.policy's
`enforce_scope` configuration option, which will result in an
HTTP Forbidden exception when mismatching scope is used.
Change-Id: I1dddeb216b2523b8471e5f2d5370921bb7a45e7f | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN,
# NOTE(lbragstad): This API was originally introduced so that services
# could invalidate tokens based on revocation events. This is system
# specific so it make sense to associate `system` as the scope type
# required for this policy.
scope_types=['system'],
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}])
]
def list_rules():
return revoke_event_policies
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN,
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}])
]
def list_rules():
return revoke_event_policies
|
Disable banners on funding pages. | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from annoy.utils import banner_exempt
from . import views
urlpatterns = [
path('', banner_exempt(views.CurrentView.as_view()), name='funding_current'),
path('teraz/', banner_exempt(views.CurrentView.as_view())),
path('teraz/<slug:slug>/', banner_exempt(views.CurrentView.as_view()), name='funding_current'),
path('lektura/', banner_exempt(views.OfferListView.as_view()), name='funding'),
path('lektura/<slug:slug>/', banner_exempt(views.OfferDetailView.as_view()), name='funding_offer'),
path('pozostale/', banner_exempt(views.WLFundView.as_view()), name='funding_wlfund'),
path('dziekujemy/', banner_exempt(views.ThanksView.as_view()), name='funding_thanks'),
path('niepowodzenie/', banner_exempt(views.NoThanksView.as_view()), name='funding_nothanks'),
path('wylacz_email/', banner_exempt(views.DisableNotifications.as_view()), name='funding_disable_notifications'),
path('getpaid/', include('getpaid.urls')),
]
| # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.CurrentView.as_view(), name='funding_current'),
path('teraz/', views.CurrentView.as_view()),
path('teraz/<slug:slug>/', views.CurrentView.as_view(), name='funding_current'),
path('lektura/', views.OfferListView.as_view(), name='funding'),
path('lektura/<slug:slug>/', views.OfferDetailView.as_view(), name='funding_offer'),
path('pozostale/', views.WLFundView.as_view(), name='funding_wlfund'),
path('dziekujemy/', views.ThanksView.as_view(), name='funding_thanks'),
path('niepowodzenie/', views.NoThanksView.as_view(), name='funding_nothanks'),
path('wylacz_email/', views.DisableNotifications.as_view(), name='funding_disable_notifications'),
path('getpaid/', include('getpaid.urls')),
]
|
Add BirtException declaration on createView method. | /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.extensions;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.model.api.DesignElementHandle;
/**
* ReportItemViewAdapter
*/
public abstract class ReportItemViewAdapter implements IReportItemViewProvider
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.extensions.IReportItemViewProvider#createView(org.eclipse.birt.report.model.api.DesignElementHandle)
*/
public DesignElementHandle createView( DesignElementHandle host ) throws BirtException
{
return null;
}
}
| /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.extensions;
import org.eclipse.birt.report.model.api.DesignElementHandle;
/**
* ReportItemViewAdapter
*/
public abstract class ReportItemViewAdapter implements IReportItemViewProvider
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.extensions.IReportItemViewProvider#createView(org.eclipse.birt.report.model.api.DesignElementHandle)
*/
public DesignElementHandle createView( DesignElementHandle host )
{
return null;
}
}
|
[expo-updates] Change directory to project root before loading asset manifest
- Fixes https://github.com/expo/expo/issues/8374#issuecomment-666640157 | const { loadAsync } = require('@expo/metro-config');
const Server = require('metro/src/Server');
async function fetchAssetManifestAsync(platform, projectRoot) {
// Project-level babel config does not load unless we change to the
// projectRoot before instantiating the server
process.chdir(projectRoot)
const config = await loadAsync(projectRoot);
const server = new Server(config);
const requestOpts = {
entryFile: process.env.ENTRY_FILE || 'index.js',
dev: false,
minify: false,
platform,
};
let assetManifest;
let error;
try {
assetManifest = await server.getAssets({
...Server.DEFAULT_BUNDLE_OPTIONS,
...requestOpts,
});
} catch (e) {
error = e;
} finally {
server.end();
}
if (error) {
throw error;
}
return assetManifest;
}
module.exports = fetchAssetManifestAsync;
| const { loadAsync } = require('@expo/metro-config');
const Server = require('metro/src/Server');
async function fetchAssetManifestAsync(platform, projectRoot) {
const config = await loadAsync(projectRoot);
const server = new Server(config);
const requestOpts = {
entryFile: process.env.ENTRY_FILE || 'index.js',
dev: false,
minify: false,
platform,
};
let assetManifest;
let error;
try {
assetManifest = await server.getAssets({
...Server.DEFAULT_BUNDLE_OPTIONS,
...requestOpts,
});
} catch (e) {
error = e;
} finally {
server.end();
}
if (error) {
throw error;
}
return assetManifest;
}
module.exports = fetchAssetManifestAsync;
|
Clean up temporary files properly | var express = require('express');
var multiparty = require('multiparty');
var fs = require('fs');
var _ = require('underscore');
var app = express();
var steghide_embed = require('.').steghide_embed;
app.post('/embed', function(req, res) {
var form = new multiparty.Form({
uploadDir: '/tmp/stegosaurus',
});
form.parse(req, function(err, fields, files) {
if(err) {
res.status(401).send('401 Bad request');
return false;
}
var image_path = files.the_image[0].path;
var secret_path = files.the_secret[0].path;
var steghidden_path = steghide_embed(
image_path,
secret_path,
fields.the_password[0]
);
function cleanup(image_path, secret_path, steghidden_path) {
_([image_path, secret_path, steghidden_path]).each(function(path) { fs.unlink(path); });
}
res.download(steghidden_path, 'steghidden-' + files.the_image[0].originalFilename, function(err) {
cleanup(image_path, secret_path, steghidden_path);
});
});
});
app.use(express.static('public'));
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Stegosaurus service listening at http://%s:%s', host, port);
});
| var express = require('express');
var multiparty = require('multiparty');
var fs = require('fs');
var _ = require('underscore');
var app = express();
var steghide_embed = require('.').steghide_embed;
app.post('/embed', function(req, res) {
var form = new multiparty.Form({
uploadDir: '/tmp/stegosaurus',
});
form.parse(req, function(err, fields, files) {
if(err) {
res.status(401).send('401 Bad request');
return false;
}
var steghidden_path = steghide_embed(
files.the_image[0].path,
files.the_secret[0].path,
fields.the_password[0]
);
res.download(steghidden_path, 'steghidden-' + files.the_image[0].originalFilename);
_(files.the_image).each(function(file) { fs.unlink(file.path); });
_(files.the_secret).each(function(file) { fs.unlink(file.path); });
});
});
app.use(express.static('public'));
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Stegosaurus service listening at http://%s:%s', host, port);
});
|
Fix autogen code that was missed in refactor | package com.kickstarter.libs;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import org.joda.time.DateTime;
import auto.parcel.AutoParcel;
@AutoParcel
public abstract class RelativeDateTimeOptions implements Parcelable {
// Abbreviates string, e.g.: "in 1 hr"
public abstract boolean abbreviated();
// Don't output tense, e.g.: "1 hour" instead of "in 1 hour"
public abstract boolean absolute();
// Compare against this date instead of the current time
public abstract @Nullable DateTime relativeToDateTime();
// Number of seconds difference permitted before an attempt to describe the relative date is abandoned.
// For example, "738 days ago" is not helpful to users. The threshold defaults to 30 days.
public abstract int threshold();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder abbreviated(boolean __);
public abstract Builder absolute(boolean __);
public abstract Builder relativeToDateTime(DateTime __);
public abstract Builder threshold(int __);
public abstract RelativeDateTimeOptions build();
}
public static Builder builder() {
return new AutoParcel_RelativeDateTimeOptions.Builder()
.abbreviated(false)
.absolute(false)
.threshold(THIRTY_DAYS_IN_SECONDS);
}
public abstract Builder toBuilder();
private final static int THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;
}
| package com.kickstarter.libs;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import org.joda.time.DateTime;
import auto.parcel.AutoParcel;
@AutoParcel
public abstract class RelativeDateTimeOptions implements Parcelable {
// Abbreviates string, e.g.: "in 1 hr"
public abstract boolean abbreviated();
// Don't output tense, e.g.: "1 hour" instead of "in 1 hour"
public abstract boolean absolute();
// Compare against this date instead of the current time
public abstract @Nullable DateTime relativeToDateTime();
// Number of seconds difference permitted before an attempt to describe the relative date is abandoned.
// For example, "738 days ago" is not helpful to users. The threshold defaults to 30 days.
public abstract int threshold();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder abbreviated(boolean __);
public abstract Builder absolute(boolean __);
public abstract Builder relativeToDateTime(DateTime __);
public abstract Builder threshold(int __);
public abstract RelativeDateTimeOptions build();
}
public static Builder builder() {
return new AutoParcel_RelativeDateOptions.Builder()
.abbreviated(false)
.absolute(false)
.threshold(THIRTY_DAYS_IN_SECONDS);
}
public abstract Builder toBuilder();
private final static int THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;
}
|
Fix ops file for turbulence manifest
Signed-off-by: Rowan Jacobs <f6a1b0cdf5ee40839db77d8af28f9a0cbe9aba71@pivotal.io> | package turbulence
import "github.com/pivotal-cf-experimental/destiny/ops"
type ConfigV2 struct {
Name string
AZs []string
DirectorHost string
DirectorUsername string
DirectorPassword string
DirectorCACert string
}
func NewManifestV2(config ConfigV2) (string, error) {
return ops.ApplyOps(manifestV2, []ops.Op{
{"replace", "/name", config.Name},
{"replace", "/instance_groups/name=api/azs", config.AZs},
{"replace", "/instance_groups/name=api/properties/director/host", config.DirectorHost},
{"replace", "/instance_groups/name=api/properties/director/client", config.DirectorUsername},
{"replace", "/instance_groups/name=api/properties/director/client_secret", config.DirectorPassword},
{"replace", "/instance_groups/name=api/properties/director/cert/ca", config.DirectorCACert},
})
}
| package turbulence
import "github.com/pivotal-cf-experimental/destiny/ops"
type ConfigV2 struct {
Name string
AZs []string
DirectorHost string
DirectorUsername string
DirectorPassword string
DirectorCACert string
}
func NewManifestV2(config ConfigV2) (string, error) {
return ops.ApplyOps(manifestV2, []ops.Op{
{"replace", "/name", config.Name},
{"replace", "/instance_groups/name=api/azs", config.AZs},
{"replace", "/instance_groups/name=api/properties/director/host", config.DirectorHost},
{"replace", "/instance_groups/name=api/properties/director/client", config.DirectorUsername},
{"replace", "/instance_groups/name=api/properties/director/client_secret", config.DirectorPassword},
{"replace", "/instance_groups/name=api/properties/director/ca_cert", config.DirectorCACert},
})
}
|
Remove trailing comma, thanks @scothis | define({
plugins: [
{ module: 'wire/debug' },
{ module: 'wire/dojo/pubsub' }
],
// Create a logger object, in this case an AlertLogger
logger: {
create: 'test/test1/AlertLogger'
// if you want a less noisy test, wire in a ConsoleLogger instead!
// create: 'test/test1/ConsoleLogger'
},
// Create a publisher Thing that will publish a topic when its doSomething
// method is called
thing1: {
create: "test/pubsub1/Thing",
properties: {
name: "Thing 1",
logger: { $ref: 'logger' }
},
publish: {
"doSomething": "thing/did-something"
}
},
// Create a subscriber Thing whose doSomething method will be called
// when the topic is published
thing2: {
create: "test/pubsub1/Thing",
properties: {
name: "Thing 2",
logger: { $ref: 'logger' }
},
subscribe: {
"thing/did-something": "doSomething"
}
}
}); | define({
plugins: [
{ module: 'wire/debug' },
{ module: 'wire/dojo/pubsub' }
],
// Create a logger object, in this case an AlertLogger
logger: {
create: 'test/test1/AlertLogger'
// if you want a less noisy test, wire in a ConsoleLogger instead!
// create: 'test/test1/ConsoleLogger'
},
// Create a publisher Thing that will publish a topic when its doSomething
// method is called
thing1: {
create: "test/pubsub1/Thing",
properties: {
name: "Thing 1",
logger: { $ref: 'logger' }
},
publish: {
"doSomething": "thing/did-something"
}
},
// Create a subscriber Thing whose doSomething method will be called
// when the topic is published
thing2: {
create: "test/pubsub1/Thing",
properties: {
name: "Thing 2",
logger: { $ref: 'logger' }
},
subscribe: {
"thing/did-something": "doSomething"
},
}
}); |
Fix label render issue due to typo | import canvas from 'canvas';
import constants from '_constants';
import Game from 'lib/game';
import Prop from 'props/prop';
import Button from 'props/button';
export default class Screen extends Prop {
constructor(cta, label) {
const buttonHeight = 100;
super(0, 0, canvas.width, canvas.height);
this.label = label;
this.button = new Button(
(canvas.height / 2) - (buttonHeight / 2),
200,
buttonHeight,
cta || 'Play',
this.onClick.bind(this)
);
}
onClick() {
const game = new Game();
game.start();
}
renderLabel() {
const fontSize = 32;
const fontX = canvas.width / 2;
const fontY = 50;
canvas.context.font = `${fontSize}px Helvetica`;
canvas.context.textAlign = 'center';
canvas.context.fillStyle = constants.COLORS.PROPS;
canvas.context.textBaseline = 'middle';
canvas.context.fillText(this.label, fontX, fontY);
}
render() {
canvas.clear();
if (this.label) {
this.renderLabel();
}
this.button.render();
}
}
| import canvas from 'canvas';
import Game from 'lib/game';
import Prop from 'props/prop';
import Button from 'props/button';
export default class Screen extends Prop {
constructor(cta, label) {
const buttonHeight = 100;
super(0, 0, canvas.width, canvas.height);
this.label = label;
this.button = new Button(
(canvas.height / 2) - (buttonHeight / 2),
200,
buttonHeight,
cta || 'Play',
this.onClick.bind(this)
);
}
onClick() {
const game = new Game();
game.start();
}
renderLabel() {
const fontSize = 32;
const fontX = canvas.width / 2;
const fontY = 50;
canvas.context.font = `${fontSize}px Helvetica`;
canvas.context.textAlign = 'center';
canvas.context.fillStyle = 'constants.COLORS.PROPS';
canvas.context.textBaseline = 'middle';
canvas.context.fillText(this.label, fontX, fontY);
}
render() {
canvas.clear();
this.button.render();
// @TODO: Why cant this go above?
if (this.label) {
console.log('testing...');
this.renderLabel();
}
}
}
|
Add safety checks in test | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
| import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
|
Test .get(key) resolves to value | import test from 'ava';
import Keyv from '../';
test('Keyv is a function', t => {
t.is(typeof Keyv, 'function');
});
test('Keyv cannot be invoked without \'new\'', t => {
t.throws(() => Keyv()); // eslint-disable-line new-cap
t.notThrows(() => new Keyv());
});
test('Keyv is an instance of Keyv', t => {
t.true(new Keyv() instanceof Keyv);
});
test('.set(key, value) returns a Promise', t => {
const store = new Keyv();
t.true(store.set('foo', 'bar') instanceof Promise);
});
test('.set(key, value) resolves to value', async t => {
const store = new Keyv();
t.is(await store.set('foo', 'bar'), 'bar');
});
test('.get(key) returns a Promise', t => {
const store = new Keyv();
t.true(store.get('foo') instanceof Promise);
});
test('.get(key) resolves to value', async t => {
const store = new Keyv();
await store.set('foo', 'bar');
t.is(await store.get('foo'), 'bar');
});
| import test from 'ava';
import Keyv from '../';
test('Keyv is a function', t => {
t.is(typeof Keyv, 'function');
});
test('Keyv cannot be invoked without \'new\'', t => {
t.throws(() => Keyv()); // eslint-disable-line new-cap
t.notThrows(() => new Keyv());
});
test('Keyv is an instance of Keyv', t => {
t.true(new Keyv() instanceof Keyv);
});
test('.set(key, value) returns a Promise', t => {
const store = new Keyv();
t.true(store.set('foo', 'bar') instanceof Promise);
});
test('.set(key, value) resolves to value', async t => {
const store = new Keyv();
t.is(await store.set('foo', 'bar'), 'bar');
});
test('.get(key) returns a Promise', t => {
const store = new Keyv();
t.true(store.get('foo') instanceof Promise);
});
|
Make reporters' loader work on windows | var gutil = require('gulp-util'),
fs = require('fs');
/**
* Loads reporter by its name.
*
* The function works only with reporters that shipped with the plugin.
*
* @param {String} name Name of a reporter to load.
* @param {Object} options Custom options object that will be passed to
* a reporter.
* @returns {Function}
*/
module.exports = function(name, options) {
if (typeof name !== 'string') {
throw new gutil.PluginError('gulp-phpcs', 'Reporter name must be a string');
}
if (name === 'index') {
throw new gutil.PluginError('gulp-phpcs', 'Reporter cannot be named "index"');
}
var fileName = './' + name + '.js',
reporter = null;
try {
reporter = require(fileName)(options || {});
} catch(error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
throw new gutil.PluginError('gulp-phpcs', 'There is no reporter "' + name + '"');
}
return reporter;
};
| var gutil = require('gulp-util'),
fs = require('fs');
/**
* Loads reporter by its name.
*
* The function works only with reporters that shipped with the plugin.
*
* @param {String} name Name of a reporter to load.
* @param {Object} options Custom options object that will be passed to
* a reporter.
* @returns {Function}
*/
module.exports = function(name, options) {
if (typeof name !== 'string') {
throw new gutil.PluginError('gulp-phpcs', 'Reporter name must be a string');
}
if (name === 'index') {
throw new gutil.PluginError('gulp-phpcs', 'Reporter cannot be named "index"');
}
var fileName = __dirname + '/' + name + '.js',
reporter = null;
try {
reporter = require(fileName)(options || {});
} catch(error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
throw new gutil.PluginError('gulp-phpcs', 'There is no reporter "' + name + '"');
}
return reporter;
};
|
Change flag names to match API params | package main
import (
"flag"
"fmt"
)
const CompareAndSwapUsage = `usage: etcdctl [etcd flags] compareAndSwap <key> <value> [testAndSet flags]
either prevValue or prevIndex needs to be given
special flags: --ttl to set a key with ttl
--prevValue to set the previous value
--prevIndex to set the previous index`
var (
compareAndSwapFlag = flag.NewFlagSet("testAndSet", flag.ExitOnError)
compareAndSwapTtl = compareAndSwapFlag.Uint64("ttl", 0, "ttl of the key")
compareAndSwapPvalue = compareAndSwapFlag.String("prevValue", "", "previous value")
compareAndSwapPindex = compareAndSwapFlag.Uint64("prevIndex", 0, "previous index")
)
func init() {
// The minimum number of arguments is 3 because
// there needs to be either pvalue or pindex
registerCommand("compareAndSwap", CompareAndSwapUsage, 3, 6, compareAndSwap)
}
func compareAndSwap(args []string) error {
key := args[0]
value := args[1]
compareAndSwapFlag.Parse(args[2:])
resp, err := client.CompareAndSwap(key, value,
*compareAndSwapTtl, *compareAndSwapPvalue, *compareAndSwapPindex)
if debug {
fmt.Println(<-curlChan)
}
if err != nil {
return err
}
output(resp)
return nil
}
| package main
import (
"flag"
"fmt"
)
const CompareAndSwapUsage = `usage: etcdctl [etcd flags] compareAndSwap <key> <value> [testAndSet flags]
either prevValue or prevIndex needs to be given
special flags: --ttl to set a key with ttl
--pvalue to set the previous value
--pindex to set the previous index`
var (
compareAndSwapFlag = flag.NewFlagSet("testAndSet", flag.ExitOnError)
compareAndSwapTtl = compareAndSwapFlag.Uint64("ttl", 0, "ttl of the key")
compareAndSwapPvalue = compareAndSwapFlag.String("pvalue", "", "previous value")
compareAndSwapPindex = compareAndSwapFlag.Uint64("pindex", 0, "previous index")
)
func init() {
// The minimum number of arguments is 3 because
// there needs to be either pvalue or pindex
registerCommand("compareAndSwap", CompareAndSwapUsage, 3, 6, compareAndSwap)
}
func compareAndSwap(args []string) error {
key := args[0]
value := args[1]
compareAndSwapFlag.Parse(args[2:])
resp, err := client.CompareAndSwap(key, value,
*compareAndSwapTtl, *compareAndSwapPvalue, *compareAndSwapPindex)
if debug {
fmt.Println(<-curlChan)
}
if err != nil {
return err
}
output(resp)
return nil
}
|
Store rows as dictionaries of lists. | # -*- coding: utf-8 -*-
"""
lilkv.columnfamily
This module implements the client-facing aspect of the `lilkv` app. All
requests are handled through this interface.
"""
class ColumnFamily(object):
"""Column Family objects store information about all rows.
daily_purchases_cf = ColumnFamily("daily_purchases")
"""
def __init__(self, name, data_dir='data'):
self.name = name
# A row consists of:
# {'rowkey': [col1, col2, col3]}
self.ROWS = dict()
def insert(self, column):
return self._insert(column)
def delete(self, column):
column.tombstone = True
return self._insert(column)
def get(self, key):
# NOTE: Check for tombstones / TTL here
pass
def _insert(self, column):
try:
self.ROWS[column.row_key].append(column)
return True
except KeyError: # Key doesn't exist
self.ROWS[column.row_key] = [column]
except:
return False
def __repr__(self):
return '<%r>' % self.name
| # -*- coding: utf-8 -*-
"""
lilkv.columnfamily
This module implements the client-facing aspect of the `lilkv` app. All
requests are handled through this interface.
"""
class ColumnFamily(object):
"""Column Family objects store information about all rows.
daily_purchases_cf = ColumnFamily("daily_purchases")
"""
def __init__(self, name, data_dir='data'):
self.name = name
self.ROWS = set()
def insert(self, column):
return self._insert(column)
def delete(self, column):
column.tombstone = True
return self._insert(column)
def get(self, key):
# NOTE: Check for tombstones / TTL here
pass
def _insert(self, column):
try:
self.ROWS.add(column)
return True
except:
return False
def __repr__(self):
return '<%r>' % self.name
|
Make ace editor respect controllerMode | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'io.c9.ace',
name: 'Config',
imports: [
'controllerMode?'
],
properties: [
{
class: 'Int',
name: 'height',
value: 800
},
{
class: 'Int',
name: 'width',
value: 800
},
{
class: 'Enum',
of: 'io.c9.ace.Theme',
name: 'theme'
},
{
class: 'Enum',
of: 'io.c9.ace.Mode',
name: 'mode',
value: 'JAVA'
},
{
class: 'Enum',
of: 'io.c9.ace.KeyBinding',
name: 'keyBinding',
value: 'ACE'
},
{
class: 'Boolean',
name: 'isReadOnly',
expression: function(controllerMode) {
return controllerMode === foam.u2.ControllerMode.VIEW;
}
}
]
});
| /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'io.c9.ace',
name: 'Config',
properties: [
{
class: 'Int',
name: 'height',
value: 400
},
{
class: 'Int',
name: 'width',
value: 500
},
{
class: 'Enum',
of: 'io.c9.ace.Theme',
name: 'theme'
},
{
class: 'Enum',
of: 'io.c9.ace.Mode',
name: 'mode',
value: 'JAVA'
},
{
class: 'Enum',
of: 'io.c9.ace.KeyBinding',
name: 'keyBinding',
value: 'ACE'
},
{
class: 'Boolean',
name: 'isReadOnly'
}
]
});
|
Append canvas to body only when creating new | const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
if (document.body) {
document.body.appendChild(canvas)
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(canvas)
})
}
}
const gl = canvas.getContext('webgl')
return gl
}
module.exports = createGL
| const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
}
if (document.body) {
document.body.appendChild(canvas)
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(canvas)
})
}
const gl = canvas.getContext('webgl')
return gl
}
module.exports = createGL
|
Optimize GIF palette (too many colors right now), better GIF timing options. | from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = ImageDraw.Draw(im)
for idx, color in enumerate(colors):
color = tuple(map(int, color))
x0 = scale * idx
y0 = 0
x1 = scale * (idx + 1)
y1 = scale
d.rectangle((x0, y0, x1, y1), fill=color)
return im
def save_gif(out, image, *more_images):
delay_ms = 1000 * 0.035
image.save(out, save_all=True,
append_images=list(more_images),
duration=delay_ms, optimize=True)
| from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = ImageDraw.Draw(im)
for idx, color in enumerate(colors):
color = tuple(map(int, color))
x0 = scale * idx
y0 = 0
x1 = scale * (idx + 1)
y1 = scale
d.rectangle((x0, y0, x1, y1), fill=color)
return im
def save_gif(out, image, *more_images):
image.save(out, save_all=True,
append_images=list(more_images),
loop=1000,
duration=50)
|
Fix namespace in result test | <?php
namespace Saft\Sparql\Test\Result;
class ResultUnitTest extends \PHPUnit_Framework_TestCase
{
/**
* Contains an instance of the class to test.
*
* @var mixed
*/
protected $fixture;
/**
*
*/
public function setUp()
{
$this->fixture = $this->getMockBuilder('Saft\Sparql\Result\Result')->getMock();
}
/**
* Tests getResultObject
*/
public function testGetResultObject()
{
$this->assertEquals(
null,
$this->fixture->getResultObject()
);
}
}
| <?php
namespace Saft\Sparql\Test\Result;
class ResultUnitTest extends \PHPUnit_Framework_TestCase
{
/**
* Contains an instance of the class to test.
*
* @var mixed
*/
protected $fixture;
/**
*
*/
public function setUp()
{
$this->fixture = $this->getMockBuilder('Saft\Store\Result\Result')->getMock();
}
/**
* Tests getResultObject
*/
public function testGetResultObject()
{
$this->assertEquals(
null,
$this->fixture->getResultObject()
);
}
}
|
Write some real-ish usage information | package main
import (
"fmt"
"strings"
)
// HelpForHelp shows overall usage information for the BigV client, including a list of available commands.
func (cmds *CommandSet) HelpForHelp() {
fmt.Println("bigv command-line client (the new, cool one)")
fmt.Println()
fmt.Println("Usage")
fmt.Println()
fmt.Println(" go-bigv [flags] <command> [flags] [args]")
fmt.Println()
fmt.Println("Commands available")
fmt.Println()
fmt.Println(" help, config, create, debug, delete, list, show")
fmt.Println(" AND MAYBE MORE OR FEWER - THIS LIST IS NOT FINAL")
fmt.Println()
fmt.Println("See `go-bigv help <command>` for help specific to a command")
fmt.Println()
}
// Help implements the help command, which gives usage information specific to each command. Usage: bigv help [command]
func (cmds *CommandSet) Help(args []string) {
if len(args) == 0 {
cmds.HelpForHelp()
return
}
// please try and keep these in alphabetical order
switch strings.ToLower(args[0]) {
case "config":
cmds.HelpForConfig()
case "debug":
cmds.HelpForDebug()
case "delete":
cmds.HelpForDelete()
case "exit":
cmds.HelpForExitCodes()
case "exit-codes":
cmds.HelpForExitCodes()
case "show":
cmds.HelpForShow()
}
}
| package main
import (
"fmt"
"strings"
)
// HelpForHelp shows overall usage information for the BigV client, including a list of available commands.
func (cmds *CommandSet) HelpForHelp() {
// TODO(telyn): write real usage information
fmt.Println("bigv command-line client (the new, cool one)")
fmt.Println()
fmt.Println("There would be some usage output here if I had actually written any.")
fmt.Println()
}
// Help implements the help command, which gives usage information specific to each command. Usage: bigv help [command]
func (cmds *CommandSet) Help(args []string) {
if len(args) == 0 {
cmds.HelpForHelp()
return
}
// please try and keep these in alphabetical order
switch strings.ToLower(args[0]) {
case "config":
cmds.HelpForConfig()
case "debug":
cmds.HelpForDebug()
case "delete":
cmds.HelpForDelete()
case "exit":
cmds.HelpForExitCodes()
case "exit-codes":
cmds.HelpForExitCodes()
case "show":
cmds.HelpForShow()
}
}
|
Fix getting the default state. | import reducer from "./reducers";
import { getEqfData } from "./selectors";
describe("getEqfData", () => {
it("can extract EQF data from the current state", () => {
const state = reducer(undefined, { type: "@@INIT" });
//state = reducer(state, { type: "SET_BAND_VALUE", band: 60, value: 100 });
const actual = getEqfData(state);
const expected = {
presets: [
{
hz60: 32,
hz170: 32,
hz310: 32,
hz600: 32,
hz1000: 32,
hz3000: 32,
hz12000: 32,
hz14000: 32,
hz16000: 32,
hz6000: 32,
name: "Entry1",
preamp: 32
}
],
type: "Winamp EQ library file v1.1"
};
expect(actual).toEqual(expected);
});
});
| import reducer from "./reducers";
import { getEqfData } from "./selectors";
describe("getEqfData", () => {
it("can extract EQF data from the current state", () => {
const state = reducer();
//state = reducer(state, { type: "SET_BAND_VALUE", band: 60, value: 100 });
const actual = getEqfData(state);
const expected = {
presets: [
{
hz60: 32,
hz170: 32,
hz310: 32,
hz600: 32,
hz1000: 32,
hz3000: 32,
hz12000: 32,
hz14000: 32,
hz16000: 32,
hz6000: 32,
name: "Entry1",
preamp: 32
}
],
type: "Winamp EQ library file v1.1"
};
expect(actual).toEqual(expected);
});
});
|
Update view on each animation frame | ;(function(lander){
console.log('Moon Lander Visualisation');
var display = document.getElementById('display');
var horizon = new Array(display.width);
horizon[0] = 50;
for (var index = 1; index < display.width; index++){
horizon[index] = horizon[index - 1] + 2 * (Math.random() - 0.5);
}
var model = {
"lander": {
"x": 37, "y": 251,
"vx": 0, "vy": 0,
"orientation": Math.PI/4, "angular-velocity": 0,
"radius": 10,
"fuel": 1
},
"horizon": horizon
};
var view = new lander.View(model, display);
function tick(){
view.update();
requestAnimationFrame(tick);
};
tick();
})(lander);
| ;(function(lander){
console.log('Moon Lander Visualisation');
var display = document.getElementById('display');
var horizon = new Array(display.width);
horizon[0] = 50;
for (var index = 1; index < display.width; index++){
horizon[index] = horizon[index - 1] + 2 * (Math.random() - 0.5);
}
var model = {
"lander": {
"x": 37, "y": 251,
"vx": 0, "vy": 0,
"orientation": Math.PI/4, "angular-velocity": 0,
"radius": 10,
"fuel": 1
},
"horizon": horizon
};
new lander.View(model, display);
})(lander);
|
Modify setMentor. Remove unnessary test function | app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
console.log('SearchController running');
var self = this;
self.mentors = BioFactory.mentors;
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
gender: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
self.test = function() {
console.log(self.newSearch);
};
self.setMentor = function(mentor){
console.log(mentor);
BioFactory.setMentor(mentor);
}
self.getMentors = function() {
console.log("SEARCH controller new.Search:", self.newSearch)
BioFactory.getMentors(self.newSearch);
};
self.createMessage = function(ev) {
$mdDialog.show({
controller: 'MessageController as message',
templateUrl: '../../views/message-modal.html',
targetEvent: ev,
clickOutsideToClose: true
});
};
}]);
/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/
| app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
console.log('SearchController running');
var self = this;
self.mentors = BioFactory.mentors;
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
gender: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
self.test = function() {
console.log(self.newSearch);
};
self.getMentor = function(mentorId){
console.log(mentorId);
BioFactory.setMentorId(mentorId);
}
self.getMentors = function() {
console.log("SEARCH controller new.Search:", self.newSearch)
BioFactory.getMentors(self.newSearch);
};
self.createMessage = function(ev) {
$mdDialog.show({
controller: 'MessageController as message',
templateUrl: '../../views/message-modal.html',
targetEvent: ev,
clickOutsideToClose: true
});
};
}]);
/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/
|
Fix plural naming change for ProductTypesResource | 'use strict';
var _ = require('lodash');
/**@ngInject*/
var ProjectServicesController = function($scope, CartService, project, products, categories, currentUser) {
this.CartService = CartService;
this.project = project;
this.CurrentUser = currentUser;
/**
* @todo This mirrors the marketplace controller currently
* and very close to the admin/products page.
* Perhaps we could wrap it up into a service/factory better.
*/
this.categories = categories;
// Only display non deleted products.
this.products = _.filter(products, function(product) {
return product.deleted_at === null;
});
_.each(this.categories, _.bind(function(category) {
category.products = _.filter(this.products, function(product) {
return product.product_type_id == category.id;
});
}, this));
};
ProjectServicesController.resolve = {
/**@ngInject*/
categories: function(ProductTypesResource) {
return ProductTypesResource.query().$promise;
}
};
ProjectServicesController.prototype = {
addToCart: function(product) {
this.CartService.add(this.CurrentUser, this.project, product);
},
cartCount: function(projectId, productId) {
var cartItems = this.CartService.getItems();
var filtered = _.filter(cartItems, function(item) {
return (item.product.id == productId && item.project.id == projectId);
});
return filtered.length;
}
};
module.exports = ProjectServicesController;
| 'use strict';
var _ = require('lodash');
/**@ngInject*/
var ProjectServicesController = function($scope, CartService, project, products, categories, currentUser) {
this.CartService = CartService;
this.project = project;
this.CurrentUser = currentUser;
/**
* @todo This mirrors the marketplace controller currently
* and very close to the admin/products page.
* Perhaps we could wrap it up into a service/factory better.
*/
this.categories = categories;
// Only display non deleted products.
this.products = _.filter(products, function(product) {
return product.deleted_at === null;
});
_.each(this.categories, _.bind(function(category) {
category.products = _.filter(this.products, function(product) {
return product.product_type_id == category.id;
});
}, this));
};
ProjectServicesController.resolve = {
/**@ngInject*/
categories: function(ProductTypeResource) {
return ProductTypeResource.query().$promise;
}
};
ProjectServicesController.prototype = {
addToCart: function(product) {
this.CartService.add(this.CurrentUser, this.project, product);
},
cartCount: function(projectId, productId) {
var cartItems = this.CartService.getItems();
var filtered = _.filter(cartItems, function(item) {
return (item.product.id == productId && item.project.id == projectId);
});
return filtered.length;
}
};
module.exports = ProjectServicesController;
|
Fix attempting to highlight a unloaded document | import { SlidehubPlugin } from '../core/SlidehubPlugin';
import { config } from '../config';
import { listener } from '../util/passive-event-listener';
export { Highlighter };
/**
* Highlighter.
*
* Highlights documents/items on hover
*/
class Highlighter extends SlidehubPlugin {
constructor(slidehub) {
const description = 'Highlights documents/items on hover';
super(slidehub, 'Highlighter', description);
this.boundHandleHighlight = this.handleHighlight.bind(this);
}
enable() {
document.addEventListener('mousemove', this.boundHandleHighlight, listener.passive);
super.enable();
}
disable() {
this.slidehub.unhighlightDocument();
document.removeEventListener('mousemove', this.boundHandleHighlight);
super.disable();
}
/**
* @param {MouseEvent} event
*/
handleHighlight(event) {
if (event.target instanceof Element) {
const docNode = event.target.closest(config.selector.doc);
const doc = this.slidehub.documents.get(docNode.id);
if (doc.loaded) {
this.slidehub.highlightDocument(doc);
if (config.keepSelectedPageInFirstColumn) {
return;
}
const itemNode = event.target.closest(config.selector.item);
if (itemNode) {
doc.highlightItem(itemNode);
}
}
}
}
};
| import { SlidehubPlugin } from '../core/SlidehubPlugin';
import { config } from '../config';
import { listener } from '../util/passive-event-listener';
export { Highlighter };
/**
* Highlighter.
*
* Highlights documents/items on hover
*/
class Highlighter extends SlidehubPlugin {
constructor(slidehub) {
const description = 'Highlights documents/items on hover';
super(slidehub, 'Highlighter', description);
this.boundHandleHighlight = this.handleHighlight.bind(this);
}
enable() {
document.addEventListener('mousemove', this.boundHandleHighlight, listener.passive);
super.enable();
}
disable() {
this.slidehub.unhighlightDocument();
document.removeEventListener('mousemove', this.boundHandleHighlight);
super.disable();
}
/**
* @param {MouseEvent} event
*/
handleHighlight(event) {
if (event.target instanceof Element) {
const docNode = event.target.closest(config.selector.doc);
if (docNode) {
const doc = this.slidehub.documents.get(docNode.id);
this.slidehub.highlightDocument(doc);
if (config.keepSelectedPageInFirstColumn) {
return;
}
const itemNode = event.target.closest(config.selector.item);
if (itemNode) {
doc.highlightItem(itemNode);
}
}
}
}
};
|
TEST: Add weird SLP orientation to get_world_pedir | import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
('SLP', 'k-', 'Posterior-Anterior'),
('SLP', 'k', 'Anterior-Posterior'),
('SLP', 'j-', 'Left-Right'),
('SLP', 'j', 'Right-Left'),
('SLP', 'i', 'Inferior-Superior'),
('SLP', 'i-', 'Superior-Inferior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
| import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Superior-Inferior'),
('LAS', 'j', 'Posterior-Anterior'),
('LAS', 'i-', 'Left-Right'),
('LAS', 'k-', 'Superior-Inferior'),
('LPI', 'j', 'Anterior-Posterior'),
('LPI', 'i-', 'Left-Right'),
('LPI', 'k-', 'Inferior-Superior'),
])
def test_get_world_pedir(tmpdir, orientation, pe_dir, expected):
assert get_world_pedir(orientation, pe_dir) == expected
|
Add message for when command is not supplied any arguments. | from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
| from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
|
Add correct URL ; increment version | from distutils.core import setup
setup(
name='tspapi',
version='0.1.1',
url="https://github.com/boundary/pulse-api-python",
author='David Gwartney',
author_email='david_gwartney@bmc.com',
packages=['tspapi', ],
# entry_points={
# 'console_scripts': [
# 'actionhandler = boundary.webhook_handler:main',
# ],
# },
# scripts=[
# 'tsp-cli-env.sh',
# ],
# package_data={'boundary': ['templates/*']},
license='Apache 2',
description='Python Bindings for the TrueSight Pulse REST APIs',
long_description=open('README.txt').read(),
install_requires=[
"requests >= 2.3.0",
],
)
| from distutils.core import setup
setup(
name='tspapi',
version='0.1.0',
url="http://boundary.github.io/pulse-api-python/",
author='David Gwartney',
author_email='david_gwartney@bmc.com',
packages=['tspapi', ],
# entry_points={
# 'console_scripts': [
# 'actionhandler = boundary.webhook_handler:main',
# ],
# },
# scripts=[
# 'tsp-cli-env.sh',
# ],
# package_data={'boundary': ['templates/*']},
license='Apache 2',
description='Python Bindings for the TrueSight Pulse REST APIs',
long_description=open('README.txt').read(),
install_requires=[
"requests >= 2.3.0",
],
)
|
Fix shooter and pickup relay numbers | package com.saintsrobotics.frc;
import edu.wpi.first.wpilibj.Relay;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// Motors
public static final int LEFT_MOTOR_1 = 1;
public static final int LEFT_MOTOR_2 = 2;
public static final int RIGHT_MOTOR_1 = 3;
public static final int RIGHT_MOTOR_2 = 4;
// Relays
public static final int PICKUP_RELAY = 2;
public static final Relay.Direction PICKUP_RELAY_DIRECTION =
Relay.Direction.kBoth;
public static final int SHOOTER_RELAY = 1;
public static final Relay.Direction SHOOTER_RELAY_DIRECTION =
Relay.Direction.kForward;
public static final int GEAR_SHIFTER_RELAY = 3;
public static final Relay.Direction GEAR_SHIFTER_RELAY_DIRECTION =
Relay.Direction.kBoth;
}
| package com.saintsrobotics.frc;
import edu.wpi.first.wpilibj.Relay;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// Motors
public static final int LEFT_MOTOR_1 = 1;
public static final int LEFT_MOTOR_2 = 2;
public static final int RIGHT_MOTOR_1 = 3;
public static final int RIGHT_MOTOR_2 = 4;
// Relays
public static final int PICKUP_RELAY = 1;
public static final Relay.Direction PICKUP_RELAY_DIRECTION =
Relay.Direction.kBoth;
public static final int SHOOTER_RELAY = 2;
public static final Relay.Direction SHOOTER_RELAY_DIRECTION =
Relay.Direction.kForward;
public static final int GEAR_SHIFTER_RELAY = 3;
public static final Relay.Direction GEAR_SHIFTER_RELAY_DIRECTION =
Relay.Direction.kBoth;
}
|
Test add 2 Factor Token. (We should move this to a modal instead) | @extends('templates.master')
@section('content')
<form action="/login" method="POST">
<input type="text" name="username" placeholder="Username"><br />
<input type="password" name="password" placeholder="Password"><br />
<input type="text" name="2fa" placeholder="2 Factor Authen"><br />
{{ csrf_field() }}
<input type="submit" value="Login">
</form>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@stop
| @extends('templates.master')
@section('content')
<form action="/login" method="POST">
<input type="text" name="username" placeholder="Username"><br />
<input type="password" name="password" placeholder="Password"><br />
{{ csrf_field() }}
<input type="submit" value="Login">
</form>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@stop
|
Update Tile sandbox for op lib | from collections import OrderedDict
import numpy as np
import plaidml
import plaidml.tile as tile
import plaidml.keras
plaidml.keras.install_backend()
import keras.backend as K
class SandboxOp(tile.Operation):
def __init__(self, code, a, b, output_shape):
super(SandboxOp, self).__init__(code, [('A', a), ('B', b)], [('O', output_shape)])
def main(code, tensor_A, tensor_B, output_shape):
print(K.backend())
op = SandboxOp(code, tensor_A, tensor_B, tile.Shape(plaidml.DType.FLOAT32, output_shape))
print(op.sole_output().shape)
print(op.sole_output().eval())
if __name__ == '__main__':
plaidml._internal_set_vlog(1)
A = K.variable(np.arange(12).reshape(4, 3))
B = K.variable(np.arange(3).reshape(3))
code = """function (A[N, M], B[M]) -> (O) {
O[i, j: N, M] = =(A[i, j] + B[j]), i/2 + j/2 + 1/2 < 2;
}"""
out_shape = (2, 3)
main(code, A, B, out_shape)
| from collections import OrderedDict
import numpy as np
import plaidml
import plaidml.keras
plaidml.keras.install_backend()
import keras.backend as K
def main(code, tensor_A, tensor_B, output_shape):
print(K.backend())
op = K._Op('sandbox_op', A.dtype, output_shape, code,
OrderedDict([('A', tensor_A), ('B', tensor_B)]), ['O'])
print(op.eval())
if __name__ == '__main__':
plaidml._internal_set_vlog(3)
A = K.variable(np.array([[1., 2., 3.], [4., 5., 6.]]))
B = K.variable(np.array([-7., -1., 2.]))
# code = """function (A[N, M], B[M]) -> (O) {
# O[i, j: N, M] = =(A[i, j] + B[j]), i/2 + j/2 + 1/2 < 2;
# }"""
# out_shape = (2, 3)
code = """function (A[N, M], B[M]) -> (O) {
O[i: N] = +(A[i - j, 0] + B[0]), j < N;
}"""
out_shape = (3,)
main(code, A, B, out_shape)
|
Add sleep after nickserv identify | from motobot import hook
from time import sleep
@hook('PING')
def handle_ping(bot, context, message):
""" Handle the server's pings. """
bot.send('PONG :' + message.params[-1])
@hook('439')
def handle_wait(bot, context, message):
""" Handles too fast for server message and waits 1 second. """
bot.identified = False
sleep(1)
@hook('NOTICE')
def handle_identification(bot, context, message):
""" Use the notice message to identify and register to the server. """
if not bot.identified:
bot.send('USER MotoBot localhost localhost MotoBot')
bot.send('NICK ' + bot.nick)
bot.identified = True
@hook('002')
def handle_nickserv_identification(bot, context, message):
""" At server welcome message 004 identify to nickserv and join channels. """
if bot.nickserv_password is not None:
bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password)
sleep(1)
@hook('ERROR')
def handle_error(bot, context, message):
""" Handle an error message from the server. """
bot.connected = bot.identified = False
| from motobot import hook
from time import sleep
@hook('PING')
def handle_ping(bot, context, message):
""" Handle the server's pings. """
bot.send('PONG :' + message.params[-1])
@hook('439')
def handle_wait(bot, context, message):
""" Handles too fast for server message and waits 1 second. """
bot.identified = False
sleep(1)
@hook('NOTICE')
def handle_identification(bot, context, message):
""" Use the notice message to identify and register to the server. """
if not bot.identified:
bot.send('USER MotoBot localhost localhost MotoBot')
bot.send('NICK ' + bot.nick)
bot.identified = True
@hook('002')
def handle_nickserv_identification(bot, context, message):
""" At server welcome message 004 identify to nickserv and join channels. """
if bot.nickserv_password is not None:
bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password)
@hook('ERROR')
def handle_error(bot, context, message):
""" Handle an error message from the server. """
bot.connected = bot.identified = False
|
Set model vingtiles on initialization. | define([
'jquery',
'underscore',
'backbone',
'backendServiceM',
'helpers',
'json!vingtilesD'
],
function ($, _, Backbone, backendServiceM, helpers, vingtiles) {
'use strict';
var LocatingChartM = Backbone.Model.extend({
code: null,
defaults: {
data: null,
vingtiles: null,
},
initialize: function(options) {
this.code = options.code;
this.set('vingtiles', _.findWhere(vingtiles, {id: this.code}));
this.listenTo(backendServiceM, 'change:apiData', this.parseApiData);
},
parseApiData: function() {
this.set('data',
backendServiceM.get('simulationStatus') === 'done' ?
helpers.findDeep(backendServiceM.get('apiData').value, {code: this.code}) :
null
);
},
});
return LocatingChartM;
});
| define([
'jquery',
'underscore',
'backbone',
'backendServiceM',
'helpers',
'json!vingtilesD'
],
function ($, _, Backbone, backendServiceM, helpers, vingtiles) {
'use strict';
var LocatingChartM = Backbone.Model.extend({
code: null,
defaults: {
data: null,
vingtiles: null,
},
initialize: function(options) {
this.code = options.code;
this.listenTo(backendServiceM, 'change:apiData', this.parseApiData);
},
parseApiData: function() {
this.set({
data: helpers.findDeep(backendServiceM.get('apiData').value, {code: this.code}),
vingtiles: _.findWhere(vingtiles, {id: this.code}),
});
},
});
return LocatingChartM;
});
|
Add some checking that stuff is bound
Specifically we require that request is bound to the form. | # File: csrf.py
# Author: Bert JW Regeer <bertjw@regeer.org>
# Created: 2013-01-26
import colander
import deform
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get('request')
if request is None:
raise KeyError('Require bind: request')
csrf_token = request.session.get_csrf_token()
return csrf_token
@colander.deferred
def deferred_csrf_validator(node, kw):
request = kw.get('request')
if request is None:
raise KeyError('Require bind: request')
def validate_csrf(node, value):
csrf_token = request.session.get_csrf_token()
if value != csrf_token:
raise colander.Invalid(node, _('Invalid cross-site scripting token'))
return validate_csrf
class CSRFSchema(colander.Schema):
csrf_token = colander.SchemaNode(
colander.String(),
default=deferred_csrf_default,
validator=deferred_csrf_validator,
widget=deform.widget.HiddenWidget()
)
| # File: csrf.py
# Author: Bert JW Regeer <bertjw@regeer.org>
# Created: 2013-01-26
import colander
import deform
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get('request')
csrf_token = request.session.get_csrf_token()
return csrf_token
@colander.deferred
def deferred_csrf_validator(node, kw):
def validate_csrf(node, value):
request = kw.get('request')
csrf_token = request.session.get_csrf_token()
if value != csrf_token:
raise colander.Invalid(node, _('Invalid cross-site scripting token'))
return validate_csrf
class CSRFSchema(colander.Schema):
csrf_token = colander.SchemaNode(
colander.String(),
default=deferred_csrf_default,
validator=deferred_csrf_validator,
widget=deform.widget.HiddenWidget()
)
|
Add PORT environmental variable support. Favor optimist argv.
Useful for deployment and on PaaS services like Heroku.
For example, Heroku uses a different port for each deploy. Luckily, the port number is stored in an environmental variable called PORT.
https://devcenter.heroku.com/articles/nodejs | var matador = require('matador')
, env = process.env.NODE_ENV || 'development'
, argv = matador.argv
, config = require('./app/config/' + env)
, app = matador.createApp(__dirname, config, {})
, port = argv.port || process.env.PORT || 3000
app.configure(function () {
app.set('view engine', 'html')
app.register('.html', matador.engine)
app.use(matador.cookieParser())
app.use(matador.session({secret: 'boosh'}))
// TODO: Add JSON body parser middleware
app.use(app.requestDecorator())
app.use(app.preRouter())
})
app.configure('development', function () {
app.use(matador.errorHandler({ dumpExceptions: true, showStack: true }))
app.set('soy options', {
eraseTemporaryFiles: true
, allowDynamicRecompile: true
})
})
app.configure('production', function () {
app.use(matador.errorHandler())
})
app.configure(function () {
app.use(app.router({}))
})
app.prefetch()
app.mount()
app.listen(port)
console.log('matador running on port ' + port)
| var matador = require('matador')
, env = process.env.NODE_ENV || 'development'
, argv = matador.argv
, config = require('./app/config/' + env)
, app = matador.createApp(__dirname, config, {})
, port = argv.port || 3000
app.configure(function () {
app.set('view engine', 'html')
app.register('.html', matador.engine)
app.use(matador.cookieParser())
app.use(matador.session({secret: 'boosh'}))
// TODO: Add JSON body parser middleware
app.use(app.requestDecorator())
app.use(app.preRouter())
})
app.configure('development', function () {
app.use(matador.errorHandler({ dumpExceptions: true, showStack: true }))
app.set('soy options', {
eraseTemporaryFiles: true
, allowDynamicRecompile: true
})
})
app.configure('production', function () {
app.use(matador.errorHandler())
})
app.configure(function () {
app.use(app.router({}))
})
app.prefetch()
app.mount()
app.listen(port)
console.log('matador running on port ' + port)
|
Fix bug with dom-properties, support deprecated valueLink and checkedLink, support Caputre events | import DOMProperty from 'react-dom/lib/DOMProperty'
import EventPluginRegistry from 'react-dom/lib/EventPluginRegistry'
const reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true,
autoFocus: true,
defaultValue: true,
defaultChecked: true,
innerHTML: true,
suppressContentEditableWarning: true,
onFocusIn: true,
onFocusOut: true,
// deprecated
valueLink: true,
checkedLink: true,
}
const hasProp = Object.prototype.hasOwnProperty
export default (prop: string) => {
if (
hasProp.call(DOMProperty.properties, prop)
|| DOMProperty.isCustomAttribute(prop.toLowerCase())
) {
return true
}
if (hasProp.call(reactProps, prop) && reactProps[prop]) {
return true
}
if (
hasProp.call(EventPluginRegistry.registrationNameModules, prop)
|| hasProp.call(EventPluginRegistry.registrationNameModules, prop.split('Capture')[0])
) {
return true
}
return false
}
| import DOMProperty from 'react-dom/lib/DOMProperty'
import EventPluginRegistry from 'react-dom/lib/EventPluginRegistry'
const reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true,
autoFocus: true,
defaultValue: true,
defaultChecked: true,
innerHTML: true,
suppressContentEditableWarning: true,
onFocusIn: true,
onFocusOut: true,
}
export default (prop: string) => {
if (
Object.prototype.hasOwnProperty.call(DOMProperty, prop) ||
DOMProperty.isCustomAttribute(prop)
) {
return true
}
if (Object.prototype.hasOwnProperty.call(reactProps, prop) && reactProps[prop]) {
return true
}
if (Object.prototype.hasOwnProperty.call(EventPluginRegistry.registrationNameModules, prop)) {
return true
}
return false
}
|
Add the right use clause. | <?php
namespace Datenknoten\LigiBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\HttpFoundation\Request;
use Datenknoten\LigiBundle\Form\DataTransformer\ImageUploadTransformer;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Persistence\ManagerRegistry;
class ImageType extends AbstractType
{
private $managerRegistry;
private $request;
public function __construct(ManagerRegistry $managerRegistry, Request $request)
{
$this->managerRegistry = $managerRegistry;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new ImageUploadTransformer($this->managerRegistry);
$builder->addModelTransformer($transformer);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'invalid_message' => 'The selected issue does not exist',
'compound' => false,
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'ligi_image';
}
}
| <?php
namespace Datenknoten\LigiBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Datenknoten\LigiBundle\Form\DataTransformer\ImageUploadTransformer;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Persistence\ManagerRegistry;
class ImageType extends AbstractType
{
private $managerRegistry;
private $request;
public function __construct(ManagerRegistry $managerRegistry, Request $request)
{
$this->managerRegistry = $managerRegistry;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new ImageUploadTransformer($this->managerRegistry);
$builder->addModelTransformer($transformer);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'invalid_message' => 'The selected issue does not exist',
'compound' => false,
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'ligi_image';
}
}
|
Change command installation check process
To properly check even if the user is not root. | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import errno
import sys
import subprocrunner as spr
from ._common import find_bin_path
from ._const import Tc, TcSubCommand
from ._error import NetworkInterfaceNotFoundError
from ._logger import logger
def check_tc_command_installation():
if find_bin_path("tc"):
return
logger.error("command not found: tc")
sys.exit(errno.ENOENT)
def get_tc_base_command(tc_subcommand):
if tc_subcommand not in TcSubCommand:
raise ValueError("the argument must be a TcSubCommand value")
return "{:s} {:s}".format(find_bin_path("tc"), tc_subcommand.value)
def run_tc_show(subcommand, device):
from ._network import verify_network_interface
verify_network_interface(device)
runner = spr.SubprocessRunner(
"{:s} show dev {:s}".format(get_tc_base_command(subcommand), device))
if runner.run() != 0 and runner.stderr.find("Cannot find device") != -1:
# reach here if the device does not exist at the system and netiface
# not installed.
raise NetworkInterfaceNotFoundError(device=device)
return runner.stdout
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import errno
import sys
import subprocrunner as spr
from ._common import find_bin_path
from ._const import Tc, TcSubCommand
from ._error import NetworkInterfaceNotFoundError
from ._logger import logger
def check_tc_command_installation():
try:
spr.Which("tc").verify()
except spr.CommandNotFoundError as e:
logger.error("{:s}: {}".format(e.__class__.__name__, e))
sys.exit(errno.ENOENT)
def get_tc_base_command(tc_subcommand):
if tc_subcommand not in TcSubCommand:
raise ValueError("the argument must be a TcSubCommand value")
return "{:s} {:s}".format(find_bin_path("tc"), tc_subcommand.value)
def run_tc_show(subcommand, device):
from ._network import verify_network_interface
verify_network_interface(device)
runner = spr.SubprocessRunner(
"{:s} show dev {:s}".format(get_tc_base_command(subcommand), device))
if runner.run() != 0 and runner.stderr.find("Cannot find device") != -1:
# reach here if the device does not exist at the system and netiface
# not installed.
raise NetworkInterfaceNotFoundError(device=device)
return runner.stdout
|
Add method to find the coordinates of game | #!/usr/bin/env python
"""
This is the main file for a script that reads info off a game on kongregate.com and acts upon it.
"""
# import line/s for builtin modules
# import pyautogui
__author__ = "Alex Flores Escarcega"
__copyright__ = "Copyright 2007, Alex Flores Escarcega"
__credits__ = ["Alex Flores Escarcega"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Alex Flores Escarcega"
__email__ = "alex.floresescar@gmail.com"
__status__ = "Development"
# game located at http://www.kongregate.com/games/Volch/endless-expansion?haref=HP_TGTM_endless-expansion
def find_game_region():
"""
Finds the top left coordinates of the game by substracting (700 + 300) from the location of the game.
The 300 comes from the width of the top_right_corner.png file that is used to locate the top right corner.
Input: None.
Output: the top left coordinates. Two elements in a tuple.
coors = pyautogui.locateOnScreen("images/top_right_corner.png")
return (coors[0],coors[1])
def main():
"""
Just now runs main()
inputs: none
outputs: none
"""
print find_game_region()
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
This is the main file for a script that reads info off a game on kongregate.com and acts upon it.
"""
# import line/s for builtin modules
# import pyautogui
__author__ = "Alex Flores Escarcega"
__copyright__ = "Copyright 2007, Alex Flores Escarcega"
__credits__ = ["Alex Flores Escarcega"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Alex Flores Escarcega"
__email__ = "alex.floresescar@gmail.com"
__status__ = "Development"
# game located at http://www.kongregate.com/games/Volch/endless-expansion?haref=HP_TGTM_endless-expansion
def main():
"""
Just now runs main()
inputs: none
outputs: none
"""
pass
if __name__ == "__main__":
main()
|
Set container_id and ext_ip container serf tags. | #!/usr/bin/env python -B
from optparse import OptionParser
import inspect
import json
import os
container_id=None
def get_port_mappings(container):
global container_id
script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
container_id = os.popen('cat %s/../containers/%s/host.id' % (script_dir, container)).read().strip()
info = os.popen('docker inspect %s' % container_id).read().strip()
parsed = json.loads(info)[0]
return {k.split('/')[0]:v[0]['HostPort'] for k,v in parsed['NetworkSettings']['Ports'].items()}
def rpc_port(container):
return get_port_mappings(container)['7373']
if __name__ == '__main__':
from set_tag import set_tag, check_container_count
parser = OptionParser(usage="usage: %prog container")
(options, args) = parser.parse_args()
if len(args) != 1: parser.print_help(); exit(1)
container = args[0]
check_container_count(container)
for k, v in get_port_mappings(container).items():
set_tag(container, 'port:%s' % k, v)
set_tag(container, 'container_id', container_id)
host_member = os.popen('serf members --detailed --format json --name `hostname`')
addr = json.loads(host_member.read().strip())['members'][0]['addr'].split(':')[0]
set_tag(container, 'ext_ip', addr)
| #!/usr/bin/env python -B
from optparse import OptionParser
import inspect
import json
import os
def get_port_mappings(container):
script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
container_id = os.popen('cat %s/../containers/%s/host.id' % (script_dir, container)).read().strip()
info = os.popen('docker inspect %s' % container_id).read().strip()
parsed = json.loads(info)[0]
return {k.split('/')[0]:v[0]['HostPort'] for k,v in parsed['NetworkSettings']['Ports'].items()}
def rpc_port(container):
return get_port_mappings(container)['7373']
if __name__ == '__main__':
from set_tag import set_tag, check_container_count
parser = OptionParser(usage="usage: %prog container")
(options, args) = parser.parse_args()
if len(args) != 1: parser.print_help(); exit(1)
container = args[0]
check_container_count(container)
set_tag(container, "ports", json.dumps(get_port_mappings(container)))
|
Use github page as homepage | from distutils.core import setup
DESCRIPTION="""
"""
setup(
name="django-moneyfield",
description="Django Money Model Field",
long_description=DESCRIPTION,
version="0.2",
author="Carlos Palol",
author_email="carlos.palol@awarepixel.com",
url="https://github.com/carlospalol/django-moneyfield",
packages=[
'moneyfield'
],
requires=[
'django (>=1.5)',
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
| from distutils.core import setup
DESCRIPTION="""
"""
setup(
name="django-moneyfield",
description="Django Money Model Field",
long_description=DESCRIPTION,
version="0.2",
author="Carlos Palol",
author_email="carlos.palol@awarepixel.com",
url="http://www.awarepixel.com",
packages=[
'moneyfield'
],
requires=[
'django (>=1.5)',
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
Add proxyfix for X-Forwarded-For header | """pluss, a feed proxy for G+"""
import logging
from pluss.app import app
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stderr.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(asctime)s [%(process)d] [%(levelname)s] %(pathname)s:%(lineno)d %(message)s",
"%Y-%m-%d %H:%M:%S",
))
app.logger.addHandler(handler)
app.logger.setLevel(logging.WARNING)
if __name__ == '__main__':
app.run(host='pluss.aiiane.com', port=54321, debug=True)
# vim: set ts=4 sts=4 sw=4 et:
| """pluss, a feed proxy for G+"""
import logging
from pluss.app import app
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stderr.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(asctime)s [%(process)d] [%(levelname)s] %(pathname)s:%(lineno)d %(message)s",
"%Y-%m-%d %H:%M:%S",
))
app.logger.addHandler(handler)
app.logger.setLevel(logging.WARNING)
if __name__ == '__main__':
app.run(host='pluss.aiiane.com', port=54321, debug=True)
# vim: set ts=4 sts=4 sw=4 et:
|
Add the "teeny" wp editor option key | <?php
namespace jvwp\components;
use fieldwork\components\Textarea;
/**
* Fieldwork Field implementation of the wp_editor function
*/
class WpEditorField extends Textarea
{
private $editorOptions = [];
const OPTION_EDITOR_CLASS = 'editor_class';
const OPTION_DRAG_DROP_UPLOAD = 'drag_drop_upload';
const OPTION_WPAUTOP = 'wpautop';
const OPTION_TEENY = 'teeny';
public function getHTML ($showLabel = true)
{
// Capture the output of the WordPress API function using output buffering
ob_start();
wp_editor($this->value, $this->getName(), $this->getEditorOptions());
return ob_get_clean();
}
public function setOption ($option, $value)
{
$this->editorOptions[$option] = $value;
}
/**
* Gets an array of options passed to <pre>wp_editor</pre>
* @return array
*/
private function getEditorOptions ()
{
return array_merge([
self::OPTION_EDITOR_CLASS => implode(' ', $this->getClasses()),
self::OPTION_DRAG_DROP_UPLOAD => true
], $this->editorOptions);
}
} | <?php
namespace jvwp\components;
use fieldwork\components\Textarea;
/**
* Fieldwork Field implementation of the wp_editor function
*/
class WpEditorField extends Textarea
{
private $editorOptions = [];
const OPTION_EDITOR_CLASS = 'editor_class';
const OPTION_DRAG_DROP_UPLOAD = 'drag_drop_upload';
const OPTION_WPAUTOP = 'wpautop';
public function getHTML ($showLabel = true)
{
// Capture the output of the WordPress API function using output buffering
ob_start();
wp_editor($this->value, $this->getName(), $this->getEditorOptions());
return ob_get_clean();
}
public function setOption ($option, $value)
{
$this->editorOptions[$option] = $value;
}
/**
* Gets an array of options passed to <pre>wp_editor</pre>
* @return array
*/
private function getEditorOptions ()
{
return array_merge([
self::OPTION_EDITOR_CLASS => implode(' ', $this->getClasses()),
self::OPTION_DRAG_DROP_UPLOAD => true
], $this->editorOptions);
}
} |
Add test for non-member access | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationHomePermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationHomePermissionTest, self).setUp()
self.path = reverse('sentry-organization-home', args=[self.organization.slug])
def test_teamless_member_can_load(self):
self.assert_teamless_member_can_access(self.path)
def test_org_member_can_load(self):
self.assert_org_member_can_access(self.path)
def test_non_member_cannot_load(self):
self.assert_non_member_cannot_access(self.path)
class OrganizationHomeTest(TestCase):
def test_renders_with_context(self):
organization = self.create_organization(name='foo', owner=self.user)
team = self.create_team(organization=organization)
project = self.create_project(team=team)
path = reverse('sentry-organization-home', args=[organization.slug])
self.login_as(self.user)
resp = self.client.get(path)
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'sentry/organization-home.html')
assert resp.context['organization'] == organization
assert resp.context['team_list'] == [(team, [project])]
| from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationHomePermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationHomePermissionTest, self).setUp()
self.path = reverse('sentry-organization-home', args=[self.organization.slug])
def test_teamless_member_can_load(self):
self.assert_teamless_member_can_access(self.path)
def test_org_member_can_load(self):
self.assert_org_member_can_access(self.path)
class OrganizationHomeTest(TestCase):
def test_renders_with_context(self):
organization = self.create_organization(name='foo', owner=self.user)
team = self.create_team(organization=organization)
project = self.create_project(team=team)
path = reverse('sentry-organization-home', args=[organization.slug])
self.login_as(self.user)
resp = self.client.get(path)
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'sentry/organization-home.html')
assert resp.context['organization'] == organization
assert resp.context['team_list'] == [(team, [project])]
|
Use MONO_REPOSITORY to set the repo URL | import os
class MonoMasterPackage(Package):
def __init__(self):
Package.__init__(self, 'mono', os.getenv('MONO_VERSION'),
sources = [os.getenv('MONO_REPOSITORY') or 'git://github.com/mono/mono.git'],
revision = os.getenv('MONO_BUILD_REVISION'),
configure_flags = [
'--enable-nls=no',
'--prefix=' + Package.profile.prefix,
'--with-ikvm=yes',
'--with-moonlight=no'
]
)
if Package.profile.name == 'darwin':
if not Package.profile.m64:
self.configure_flags.extend([
# fix build on lion, it uses 64-bit host even with -m32
'--build=i386-apple-darwin11.2.0',
])
self.configure_flags.extend([
'--enable-loadedllvm'
])
self.sources.extend ([
# Fixes up pkg-config usage on the Mac
'patches/mcs-pkgconfig.patch'
])
self.configure = expand_macros ('CFLAGS="%{env.CFLAGS} -O2" ./autogen.sh', Package.profile)
def prep (self):
Package.prep (self)
if Package.profile.name == 'darwin':
for p in range (1, len (self.sources)):
self.sh ('patch -p1 < "%{sources[' + str (p) + ']}"')
MonoMasterPackage()
| import os
class MonoMasterPackage(Package):
def __init__(self):
Package.__init__(self, 'mono', os.getenv('MONO_VERSION'),
sources = ['git://github.com/mono/mono.git'],
revision = os.getenv('MONO_BUILD_REVISION'),
configure_flags = [
'--enable-nls=no',
'--prefix=' + Package.profile.prefix,
'--with-ikvm=yes',
'--with-moonlight=no'
]
)
if Package.profile.name == 'darwin':
if not Package.profile.m64:
self.configure_flags.extend([
# fix build on lion, it uses 64-bit host even with -m32
'--build=i386-apple-darwin11.2.0',
])
self.configure_flags.extend([
'--enable-loadedllvm'
])
self.sources.extend ([
# Fixes up pkg-config usage on the Mac
'patches/mcs-pkgconfig.patch'
])
self.configure = expand_macros ('CFLAGS="%{env.CFLAGS} -O2" ./autogen.sh', Package.profile)
def prep (self):
Package.prep (self)
if Package.profile.name == 'darwin':
for p in range (1, len (self.sources)):
self.sh ('patch -p1 < "%{sources[' + str (p) + ']}"')
MonoMasterPackage()
|
Fix rpc argument handling when constructing a Request | from .exceptions import MalformedRequestException
class Request(object):
def __init__(self, version, metadata, arguments):
self._version = version
self._metadata = metadata
self._arguments = arguments
@property
def version(self):
return self._version
@property
def arguments(self):
return self._arguments
@property
def metadata(self):
return self._metadata
@staticmethod
def loads(s, serializer):
try:
l = serializer.loads(s)
except(ValueError, TypeError):
raise MalformedRequestException(serializer.__name__, s)
try:
version, metadata, args = l[0:3]
except ValueError:
raise MalformedRequestException(serializer.__name__, s)
else:
return Request(version, metadata, args)
@staticmethod
def dumps(obj, serializer):
return serializer.dumps([obj.version, obj.metadata, obj.arguments])
| from .exceptions import MalformedRequestException
class Request(object):
def __init__(self, version, metadata, **kwargs):
self._version = version
self._metadata = metadata
self._arguments = kwargs
@property
def version(self):
return self._version
@property
def arguments(self):
return self._arguments
@property
def metadata(self):
return self._metadata
@staticmethod
def loads(s, serializer):
try:
l = serializer.loads(s)
except(ValueError, TypeError):
raise MalformedRequestException(serializer.__name__, s)
try:
version, metadata, args = l[0:3]
except ValueError:
raise MalformedRequestException(serializer.__name__, s)
else:
return Request(version, metadata, args)
@staticmethod
def dumps(obj, serializer):
return serializer.dumps([obj.version, obj.metadata, obj.arguments])
|
Fix cache.store does not exist when using in Lumen 5.1. | <?php
namespace Rymanalu\LaravelCircuitBreaker;
use Illuminate\Support\ServiceProvider;
class CircuitBreakerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(CircuitBreaker::class, function ($app) {
return new CircuitBreaker($app['cache']->store());
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [CircuitBreaker::class];
}
}
| <?php
namespace Rymanalu\LaravelCircuitBreaker;
use Illuminate\Support\ServiceProvider;
class CircuitBreakerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(CircuitBreaker::class, function ($app) {
return new CircuitBreaker($app['cache.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [CircuitBreaker::class];
}
}
|
Sort combination operators in alphabetical order | const combine = (combiner, ...observables) => next => {
let state = Array(observables.length)
observables.forEach((base, index) => base(value => {
state[index] = value
if(Object.keys(state).length === state.length)
next(combiner(state))
}))
}
const constant = (base, value) => map(base, () => value)
const filter = (base, predicate) => next =>
base(value => predicate(value) && next(value))
const from = values => next => values.forEach(next)
const just = value => next => next(value)
const map = (base, mapper) => next =>
base(value => next(mapper(value)))
const merge = (...observables) => next => observables.forEach(base => base(next))
const periodic = interval => next => setInverval(next, interval)
const scan = (base, reducer, initial) => next => {
let state = initial
base(value => {
state = reducer(state, value)
next(state)
})
}
export {
combine,
constant,
filter,
from,
just,
map,
merge,
periodic,
scan,
}
| const constant = (base, value) => map(base, () => value)
const filter = (base, predicate) => next =>
base(value => predicate(value) && next(value))
const from = values => next => values.forEach(next)
const just = value => next => next(value)
const map = (base, mapper) => next =>
base(value => next(mapper(value)))
const periodic = interval => next => setInverval(next, interval)
const scan = (base, reducer, initial) => next => {
let state = initial
base(value => {
state = reducer(state, value)
next(state)
})
}
const merge = (...observables) => next => observables.forEach(base => base(next))
const combine = (combiner, ...observables) => next => {
let state = Array(observables.length)
observables.forEach((base, index) => base(value => {
state[index] = value
if(Object.keys(state).length === state.length)
next(combiner(state))
}))
}
export {
constant,
filter,
from,
just,
map,
periodic,
scan,
merge,
combine
}
|
Add kml layer to map | var exampleLoc = new google.maps.LatLng(-25.363882,131.044922);
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 4,
center: exampleLoc,
disableDefaultUI: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello, world!'
});
var marker = new google.maps.Marker({
position: exampleLoc,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var circle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.1,
map: map,
center: exampleLoc,
radius: 400000
});
var exampleKml = new google.maps.KmlLayer({
url: 'data/example.kml',
clickable: false
});
exampleKml.setMap(map);
| var exampleLoc = new google.maps.LatLng(-25.363882,131.044922);
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 4,
center: exampleLoc,
disableDefaultUI: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello, world!'
});
var marker = new google.maps.Marker({
position: exampleLoc,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var circle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.1,
map: map,
center: exampleLoc,
radius: 400000
});
var exampleKml = new google.maps.KmlLayer({
url: 'data/example.kml',
clickable: false
});
|
Improve MD unit test diffs
Break MD expected and actual output into lines so that diffs are more helpful and precise for failing tests. | const {expect} = require('chai');
const fs = require('fs');
const th = require('../test_helper');
const {exportToMarkdown} = require('../../lib/markdown/export');
const {Namespace, DataElement, Identifier, Concept, CodeFromAncestorValue} = require('../../lib/models');
describe('#exportToMarkdownCommonCases()', th.commonTests(importFixture, exportNamespaces));
describe('#exportToMarkdownGrammarV3Cases()', () => {
it('should correctly export coded descendents', () => {
let ns = new Namespace('shr.test');
let de = new DataElement(new Identifier(ns.namespace, 'CodedDescendent'), true);
de.description = 'It is a coded element descending from foobar';
de.value = new CodeFromAncestorValue(new Concept('http://foo.org', 'bar', 'Foobar'));
ns.addDefinition(de);
let expectedMD = importFixture('CodedDescendent');
let markdown = exportNamespaces(ns);
expect(markdown).to.eql(expectedMD);
});
});
function exportNamespaces(...namespace) {
let markdowns = [];
const results = exportToMarkdown(namespace);
for (const ns of namespace) {
markdowns = markdowns.concat(splitLines(results.namespaces[ns.namespace].index), '');
}
return markdowns;
}
function importFixture(name, ext='.md') {
const fixture = fs.readFileSync(`${__dirname}/fixtures/${name}${ext}`, 'utf8');
return splitLines(fixture).concat('');
}
function splitLines(text) {
return text.split('\n').map(l => l.trim());
}
| const {expect} = require('chai');
const fs = require('fs');
const th = require('../test_helper');
const {exportToMarkdown} = require('../../lib/markdown/export');
const {Namespace, DataElement, Identifier, Concept, CodeFromAncestorValue} = require('../../lib/models');
describe('#exportToMarkdownCommonCases()', th.commonTests(importFixture, exportNamespaces));
describe('#exportToMarkdownGrammarV3Cases()', () => {
it('should correctly export coded descendents', () => {
let ns = new Namespace('shr.test');
let de = new DataElement(new Identifier(ns.namespace, 'CodedDescendent'), true);
de.description = 'It is a coded element descending from foobar';
de.value = new CodeFromAncestorValue(new Concept('http://foo.org', 'bar', 'Foobar'));
ns.addDefinition(de);
let expectedMD = importFixture('CodedDescendent');
let markdown = exportNamespaces(ns);
expect(markdown).to.have.length(1);
expect(markdown).to.eql(expectedMD);
});
});
function exportNamespaces(...namespace) {
let markdowns = [];
const results = exportToMarkdown(namespace);
for (const ns of namespace) {
markdowns = markdowns.concat(results.namespaces[ns.namespace].index);
}
return markdowns;
}
function importFixture(name, ext='.md') {
const fixture = fs.readFileSync(`${__dirname}/fixtures/${name}${ext}`, 'utf8');
const files = fixture.split('<!-- next file -->');
return files.map(f => f.trim());
}
|
Add libnexmo as a dependency | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
packages=['nexmo'],
include_package_data=True,
license='WTFPL',
description='A simple Django app to send text messages using the Nexmo api.',
long_description=README,
url='https://github.com/thibault/django-nexmo',
author='Thibault Jouannic',
author_email='thibault@miximum.fr',
setup_requires=('setuptools'),
install_requires=[
'libnexmo',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-nexmo',
version='1.0.1',
packages=['nexmo'],
include_package_data=True,
license='WTFPL',
description='A simple Django app to send text messages using the Nexmo api.',
long_description=README,
url='https://github.com/thibault/django-nexmo',
author='Thibault Jouannic',
author_email='thibault@miximum.fr',
setup_requires=('setuptools'),
requires=(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
fix(mount): Check first if the componentDidMount and componentWillUnmount are defined | /**
* Created by thram on 21/01/17.
*/
import forEach from "lodash/forEach";
import assign from "lodash/assign";
import isArray from "lodash/isArray";
import {observe, state, removeObserver} from "thrux";
export const connect = (stateKey, ReactComponent) => {
class ThruxComponent extends ReactComponent {
observers = {};
constructor(props) {
super(props);
this.state = assign(this.state || {}, state([].concat(stateKey)));
}
addObserver = (key) => {
this.observers[key] = (state) => {
let newState = {};
newState[key] = state;
this.setState(newState);
};
observe(key, this.observers[key]);
};
componentDidMount(...args) {
isArray(stateKey) ? forEach(stateKey, this.addObserver) : this.addObserver(stateKey);
super.componentDidMount && super.componentDidMount.apply(this, args);
}
componentWillUnmount(...args) {
super.componentWillUnmount && super.componentWillUnmount.apply(this, args);
forEach(this.observers, (observer, key) => removeObserver(key, observer));
}
}
return ThruxComponent;
}; | /**
* Created by thram on 21/01/17.
*/
import forEach from "lodash/forEach";
import assign from "lodash/assign";
import isArray from "lodash/isArray";
import {observe, state, removeObserver} from "thrux";
export const connect = (stateKey, ReactComponent) => {
class ThruxComponent extends ReactComponent {
observers = {};
constructor(props) {
super(props);
this.state = assign(this.state || {}, state([].concat(stateKey)));
}
addObserver = (key) => {
this.observers[key] = (state) => {
let newState = {};
newState[key] = state;
this.setState(newState);
};
observe(key, this.observers[key]);
};
componentDidMount(...args) {
isArray(stateKey) ? forEach(stateKey, this.addObserver) : this.addObserver(stateKey);
super.componentDidMount.apply(this, args);
}
componentWillUnmount(...args) {
super.componentWillUnmount.apply(this, args);
forEach(this.observers, (observer, key) => removeObserver(key, observer));
}
}
return ThruxComponent;
}; |
Add check for content directory.
Nothing will run if it doesn't exist. | <?php
require_once __DIR__.'/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
if(!is_dir($app['config']['content_location'])) {
$app->abort(500, "There was an issue loading the content. Is your content location correct?");
}
$app->mount(
'/'.$app['config']['admin_path'],
new Chula\ControllerProvider\Admin()
);
$app->mount(
'/{page}',
new Chula\ControllerProvider\Loader()
);
$app->mount(
'/'.$app['config']['admin_path'].'/new',
new Chula\ControllerProvider\NewPage()
);
$app->mount(
'/'.$app['config']['admin_path'].'/delete',
new Chula\ControllerProvider\DeletePage()
);
$app->mount(
'/'.$app['config']['admin_path'].'/edit',
new Chula\ControllerProvider\EditPage()
);
$app->get('/', function() use ($app)
{
return 'HELLOOOOO';
});
$app->get('/login', function(Request $request) use ($app) {
return $app['twig']->render('login.twig', array(
'error' => $app['security.last_error']($request),
'last_username' => $app['session']->get('_security.last_username'),
));
});
$app->run();
| <?php
require_once __DIR__.'/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
$app->mount(
'/'.$app['config']['admin_path'],
new Chula\ControllerProvider\Admin()
);
$app->mount(
'/{page}',
new Chula\ControllerProvider\Loader()
);
$app->mount(
'/'.$app['config']['admin_path'].'/new',
new Chula\ControllerProvider\NewPage()
);
$app->mount(
'/'.$app['config']['admin_path'].'/delete',
new Chula\ControllerProvider\DeletePage()
);
$app->mount(
'/'.$app['config']['admin_path'].'/edit',
new Chula\ControllerProvider\EditPage()
);
$app->get('/', function() use ($app)
{
return 'HELLOOOOO';
});
$app->get('/login', function(Request $request) use ($app) {
return $app['twig']->render('login.twig', array(
'error' => $app['security.last_error']($request),
'last_username' => $app['session']->get('_security.last_username'),
));
});
$app->run();
|
Make default page after signin the bolt page | angular.module('bolt.auth', [])
.controller('AuthController', function ($scope, $window, $location, Auth) {
$scope.user = {};
$scope.signin = function () {
Auth.signin($scope.user)
.then(function (token) {
$window.localStorage.setItem('com.bolt', token);
$location.path('/');
})
.catch(function (error) {
console.error(error);
});
};
$scope.signup = function () {
Auth.signup($scope.user)
.then(function (token) {
$window.localStorage.setItem('com.bolt', token);
$location.path('/');
})
.catch(function (error) {
console.error(error);
});
};
});
| angular.module('bolt.auth', [])
.controller('AuthController', function ($scope, $window, $location, Auth) {
$scope.user = {};
$scope.signin = function () {
Auth.signin($scope.user)
.then(function (token) {
$window.localStorage.setItem('com.bolt', token);
$location.path('/links');
})
.catch(function (error) {
console.error(error);
});
};
$scope.signup = function () {
Auth.signup($scope.user)
.then(function (token) {
$window.localStorage.setItem('com.bolt', token);
$location.path('/');
})
.catch(function (error) {
console.error(error);
});
};
});
|
Remove tests from __all__ which are no longere here.
git-svn-id: fc68d25ef6d4ed42045cee93f23b6b1994a11c36@1122 5646265b-94b7-0310-9681-9501d24b2df7 | #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = [
'database', 'pool', 'commands',
'time_since',
'rfc822', 'rfc1521',
'http', 'querystring', 'cookie', 'virtualhost',
'webresource', 'webcollections', 'webentwiner',
'webserver', 'webclient', 'web',
'semaphore', 'logfile',
]
| #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = [
'reactor', 'database', 'pool', 'commands',
'time_since',
'rfc822', 'rfc1521',
'http', 'querystring', 'cookie', 'virtualhost', 'accept',
'webresource', 'webcollections', 'webentwiner',
'webserver', 'webclient', 'web',
'semaphore', 'logfile',
]
|
Upgrade tangled from 0.1a5 to 0.1a7 | from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a3.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.sqlalchemy',
],
install_requires=[
'tangled>=0.1a7',
'SQLAlchemy',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a7',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a3.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.sqlalchemy',
],
install_requires=[
'tangled>=0.1a5',
'SQLAlchemy',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a5',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Use tag name translations in new pledge form | import { connect } from 'react-redux'
import merge from 'lodash/merge'
import I18n from 'i18n-js'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'
const mapStateToProps = function(state, ownProps) {
return {
availableTags: assembleTags(ownProps.tags),
currentUser: state.currentUser,
}
}
function assembleTags(tags) {
return tags.map(function(tag) {
return {
value: tag.id,
label: I18n.t(`tags.names.${tag.name}`),
}
})
}
const mapDispatchToProps = dispatch => ({
onLinkClick: function(event) {
event.preventDefault()
dispatch(toggleSessionPopup())
window.scrollTo(0, 0)
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(PledgeForm)
| import { connect } from 'react-redux'
import merge from 'lodash/merge'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'
const mapStateToProps = function(state, ownProps) {
return {
availableTags: assembleTags(ownProps.tags),
currentUser: state.currentUser,
}
}
function assembleTags(tags) {
return tags.map(function(tag) {
return {
value: tag.id,
label: tag.name,
}
})
}
const mapDispatchToProps = dispatch => ({
onLinkClick: function(event) {
event.preventDefault()
dispatch(toggleSessionPopup())
window.scrollTo(0, 0)
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(PledgeForm)
|
Use extraPaths configuration for browserify | module.exports = function(gulp, settings) {
var appBundlerFn = require("./util-bundlers.js")(gulp, settings).appBundlerFn;
/**
* Run all test build tasks.
**/
gulp.task('build-tests', ['copy-test-lib', 'bundle-test-lib', 'ui-test'], function () {
// Lastly, bundle the test code (app/code/test/...).
return appBundlerFn({
entries: './app/code/test/testIndex.js',
paths: settings.extraPaths,
isDebug: settings.isDebug,
vendorLibraries: settings.libraryModules,
destinationName: 'test.bundle.js',
destinationDir: settings.testOutputPath
});
});
};
| module.exports = function(gulp, settings) {
var appBundlerFn = require("./util-bundlers.js")(gulp, settings).appBundlerFn;
/**
* Run all test build tasks.
**/
gulp.task('build-tests', ['copy-test-lib', 'bundle-test-lib', 'ui-test'], function () {
// Lastly, bundle the test code (app/code/test/...).
return appBundlerFn({
entries: './app/code/test/testIndex.js',
paths: 'app/code/util/',
isDebug: settings.isDebug,
vendorLibraries: settings.libraryModules,
destinationName: 'test.bundle.js',
destinationDir: settings.testOutputPath
});
});
};
|
Use .min files when available. | var url = require('url'),
grunt = require('grunt');
module.exports = {
manifestUrl: function(manifest) {
return function(path) {
if(process.env.GLAZIER_ENV !== "prod") { return path; }
var parsed = url.parse(path, true);
var pathname = parsed.pathname;
var minifiedPathname = pathname.replace(/\.(js|css)$/, '.min.$1');
var path = manifest[minifiedPathname] || manifest[pathname];
if (!path) {
throw "No file found in manifest for path " + pathname;
} else {
console.log("Found entry for path " + pathname);
}
var assetHost = grunt.config.process('<%= pkg.assetHost %>');
var parts = {
pathname: assetHost + path,
hash: parsed.hash,
query: grunt.util._.extend({}, parsed.query, {"cors-fix": "1"})
};
console.log(path + " -> " + url.format(parts));
return url.format(parts);
};
}
};
| var url = require('url'),
grunt = require('grunt');
module.exports = {
manifestUrl: function(manifest) {
return function(path) {
if(process.env.GLAZIER_ENV !== "prod") { return path; }
var parsed = url.parse(path, true);
if (!manifest[parsed.pathname]) {
throw "No file found in manifest for path " + parsed.pathname;
} else {
console.log("Found entry for path " + parsed.pathname);
}
var assetHost = grunt.config.process('<%= pkg.assetHost %>');
var parts = {
pathname: assetHost + manifest[parsed.pathname],
hash: parsed.hash,
query: grunt.util._.extend({}, parsed.query, {"cors-fix": "1"})
};
console.log(path + " -> " + url.format(parts));
return url.format(parts);
};
}
};
|
Include filename in reading/parsing errors.
Fixes issue #2. | // Copyright (c) 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd.
// golint lints the Go source files named on its command line.
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"github.com/golang/lint"
)
var minConfidence = flag.Float64("min_confidence", 0.8, "minimum confidence of a problem to print it")
func main() {
flag.Parse()
// TODO(dsymonds): Support linting of stdin.
for _, filename := range flag.Args() {
lintFile(filename)
}
}
func lintFile(filename string) {
src, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("Failed reading %v: %v", filename, err)
return
}
l := new(lint.Linter)
ps, err := l.Lint(filename, src)
if err != nil {
log.Printf("Failed parsing %v: %v", filename, err)
return
}
for _, p := range ps {
if p.Confidence >= *minConfidence {
fmt.Printf("%s:%v: %s\n", filename, p.Position, p.Text)
}
}
}
| // Copyright (c) 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd.
// golint lints the Go source files named on its command line.
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"github.com/golang/lint"
)
var minConfidence = flag.Float64("min_confidence", 0.8, "minimum confidence of a problem to print it")
func main() {
flag.Parse()
// TODO(dsymonds): Support linting of stdin.
for _, filename := range flag.Args() {
lintFile(filename)
}
}
func lintFile(filename string) {
src, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("Failed reading file: %v", err)
return
}
l := new(lint.Linter)
ps, err := l.Lint(filename, src)
if err != nil {
log.Printf("Failed parsing file: %v", err)
return
}
for _, p := range ps {
if p.Confidence >= *minConfidence {
fmt.Printf("%s:%v: %s\n", filename, p.Position, p.Text)
}
}
}
|
Fix: Remove invalid `sourcemaps` option passed to gulp-sourcemaps | 'use strict';
var through2 = require('through2');
var sourcemaps = require('gulp-sourcemaps');
var duplexify = require('duplexify');
var sink = require('../sink');
var prepareWrite = require('../prepareWrite');
var writeContents = require('./writeContents');
function dest(outFolder, opt) {
if (!opt) {
opt = {};
}
function saveFile(file, enc, cb) {
prepareWrite(outFolder, file, opt, function(err, writePath) {
if (err) {
return cb(err);
}
writeContents(writePath, file, cb);
});
}
var saveStream = through2.obj(opt, saveFile);
if (!opt.sourcemaps) {
// Sink the save stream to start flowing
// Do this on nextTick, it will flow at slowest speed of piped streams
process.nextTick(sink(saveStream));
return saveStream;
}
var sourcemapOpt = opt.sourcemaps;
if (typeof sourcemapOpt === 'boolean') {
sourcemapOpt = {};
}
var mapStream = sourcemaps.write(sourcemapOpt.path, sourcemapOpt);
var outputStream = duplexify.obj(mapStream, saveStream);
mapStream.pipe(saveStream);
// Sink the output stream to start flowing
// Do this on nextTick, it will flow at slowest speed of piped streams
process.nextTick(sink(outputStream));
return outputStream;
}
module.exports = dest;
| 'use strict';
var through2 = require('through2');
var sourcemaps = require('gulp-sourcemaps');
var duplexify = require('duplexify');
var sink = require('../sink');
var prepareWrite = require('../prepareWrite');
var writeContents = require('./writeContents');
function dest(outFolder, opt) {
if (!opt) {
opt = {};
}
function saveFile(file, enc, cb) {
prepareWrite(outFolder, file, opt, function(err, writePath) {
if (err) {
return cb(err);
}
writeContents(writePath, file, cb);
});
}
var saveStream = through2.obj(opt, saveFile);
if (!opt.sourcemaps) {
// Sink the save stream to start flowing
// Do this on nextTick, it will flow at slowest speed of piped streams
process.nextTick(sink(saveStream));
return saveStream;
}
var sourcemapOpt = opt.sourcemaps;
if (typeof sourcemapOpt === 'boolean') {
sourcemapOpt = { sourcemaps: sourcemapOpt };
}
var mapStream = sourcemaps.write(sourcemapOpt.path, sourcemapOpt);
var outputStream = duplexify.obj(mapStream, saveStream);
mapStream.pipe(saveStream);
// Sink the output stream to start flowing
// Do this on nextTick, it will flow at slowest speed of piped streams
process.nextTick(sink(outputStream));
return outputStream;
}
module.exports = dest;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.