text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use `reducer` to replace `prepare`
|
__all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self.root, self.name)
imgl = ss.get_slides(None, gray=True, resize=True)
self.feats(imgl, prefix="s")
def get_frame_feats(self):
rr = Reducer(self.root, self.name)
vv = Video(self.root, self.name)
imgl = vv.get_frames(rr.frame_ids(), gray=True)
self.feats(imgl, prefix="f")
def get_feats_pair(self, sid, fid):
"""
Get features by given `slide`, `frame` pairs
"""
sk = self.load("s_{:03d}_kps".format(sid))
sd = self.load("s_{:03d}_des".format(sid))
fk = self.load("f_{:03d}_kps".format(fid))
fd = self.load("f_{:03d}_des".format(fid))
return dict(sk=sk, sd=sd, fk=fk, fd=fd)
|
__all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.prepare import Prepare
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self.root, self.name)
imgl = ss.get_slides(None, gray=True, resize=True)
self.feats(imgl, prefix="s")
def get_frame_feats(self):
pp = Prepare(self.root, self.name)
vv = Video(self.root, self.name)
imgl = vv.get_frames(pp.frame_ids(), gray=True)
self.feats(imgl, prefix="f")
def get_feats_pair(self, sid, fid):
"""
Get features by given `slide`, `frame` pairs
"""
sk = self.load("s_{:03d}_kps".format(sid))
sd = self.load("s_{:03d}_des".format(sid))
fk = self.load("f_{:03d}_kps".format(fid))
fd = self.load("f_{:03d}_des".format(fid))
return dict(sk=sk, sd=sd, fk=fk, fd=fd)
|
Add old method for setting val to pin named set_val_old
|
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
# Application name:
name="blynkapi",
# Version number (initial):
version="0.1.7",
description="This is a simple blynk HTTP/HTTPS API wrapper.",
long_description=long_description,
#URL
url='https://github.com/xandr2/blynkapi',
download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.7.tar.gz',
# Application author details:
author="Alexandr Borysov",
author_email="xandr2@gmail.com",
# License
license='MIT',
keywords=['python', 'blynk', 'HTTP/HTTPS', 'API', 'wrapper'],
# Packages
packages=["blynkapi"],
# Include additional files into the package
#include_package_data=True,
#
# license="LICENSE.txt",
# long_description=open("README.txt").read(),
# Dependent packages (distributions)
#install_requires=[
# "urllib2",
#],
classifiers = [],
)
|
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
# Application name:
name="blynkapi",
# Version number (initial):
version="0.1.6",
description="This is a simple blynk HTTP/HTTPS API wrapper.",
long_description=long_description,
#URL
url='https://github.com/xandr2/blynkapi',
download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.6.tar.gz',
# Application author details:
author="Alexandr Borysov",
author_email="xandr2@gmail.com",
# License
license='MIT',
keywords=['python', 'blynk', 'HTTP/HTTPS', 'API', 'wrapper'],
# Packages
packages=["blynkapi"],
# Include additional files into the package
#include_package_data=True,
#
# license="LICENSE.txt",
# long_description=open("README.txt").read(),
# Dependent packages (distributions)
#install_requires=[
# "urllib2",
#],
classifiers = [],
)
|
Check for config via NOT
Until yesterday, this was `if (config == null)`, which checks for a certain
falseyness of `config`. This was changed yesterday to `if (config === null)` which
checks if `config` is, in fact, `null`. The problem is that when calling a function
without a parameter, then the paramter is `undefined`. So maybe we should check
for `if (config === undefined)` but I figure its easier and clearer to check
`if (!config)`
|
/**
* Run a new test with the given +title+ and function body, which will
* be executed within the proper test declarations for the UIAutomation
* framework. The given function will be handed a +UIATarget+ and
* a +UIApplication+ object which it can use to exercise and validate your
* application.
*
* The +options+ parameter is an optional object/hash thingie that
* supports the following:
* logTree -- a boolean to log the element tree when the test fails (default 'true')
*
* Example:
* test("Sign-In", function(target, application) {
* // exercise and validate your application.
* });
*
*/
function test(title, f, options) {
if (!options) {
options = {
logTree: true
};
}
target = UIATarget.localTarget();
application = target.frontMostApp();
UIALogger.logStart(title);
try {
f(target, application);
UIALogger.logPass(title);
}
catch (e) {
UIALogger.logError(e.toString());
if (options.logTree) target.logElementTree();
UIALogger.logFail(title);
}
}
|
/**
* Run a new test with the given +title+ and function body, which will
* be executed within the proper test declarations for the UIAutomation
* framework. The given function will be handed a +UIATarget+ and
* a +UIApplication+ object which it can use to exercise and validate your
* application.
*
* The +options+ parameter is an optional object/hash thingie that
* supports the following:
* logTree -- a boolean to log the element tree when the test fails (default 'true')
*
* Example:
* test("Sign-In", function(target, application) {
* // exercise and validate your application.
* });
*
*/
function test(title, f, options) {
if (options === null) {
options = {
logTree: true
};
}
target = UIATarget.localTarget();
application = target.frontMostApp();
UIALogger.logStart(title);
try {
f(target, application);
UIALogger.logPass(title);
}
catch (e) {
UIALogger.logError(e.toString());
if (options.logTree) target.logElementTree();
UIALogger.logFail(title);
}
}
|
feat(redux-module-activities): Update to use Records for initialState
|
import {Record} from 'immutable';
import {
STORE_ACTIVITIES,
UPDATE_ACTIVITY
} from './actions';
const Activity = Record({
id: null,
actor: null,
type: '',
object: {},
status: {}
});
const InitialState = Record({
byId: {}
});
export const initialState = new InitialState();
export default function reducer(state = initialState, action) {
switch (action.type) {
case STORE_ACTIVITIES: {
const activities = {};
action.payload.activities.forEach((a) => {
activities[a.id] = new Activity(a);
});
return state.mergeIn(['byId'], activities);
}
case UPDATE_ACTIVITY: {
const {activity} = action.payload;
return state.mergeDeepIn(['byId', activity.id], activity);
}
default:
return state;
}
}
|
import {fromJS, Record} from 'immutable';
import {
STORE_ACTIVITIES,
UPDATE_ACTIVITY
} from './actions';
const Activity = Record({
id: null,
actor: null,
type: '',
object: {},
status: {}
});
export const initialState = fromJS({
byId: {}
});
export default function reducer(state = initialState, action) {
switch (action.type) {
case STORE_ACTIVITIES: {
const activities = {};
action.payload.activities.forEach((a) => {
activities[a.id] = new Activity(a);
});
return state.mergeIn(['byId'], activities);
}
case UPDATE_ACTIVITY: {
const {activity} = action.payload;
return state.mergeDeepIn(['byId', activity.id], activity);
}
default:
return state;
}
}
|
Add named 'login' route for auth middleware.
|
<?php
/**
* Here is where you can register web routes for your application. These
* routes are loaded by the RouteServiceProvider within a group which
* contains the "web" middleware group. Now create something great!
*
* @var \Illuminate\Routing\Router $router
* @see \Aurora\Providers\RouteServiceProvider
*/
// Homepage
$router->get('/', 'HomeController@home')->name('login');
// Authentication
$router->get('auth/login', 'Auth\AuthController@getLogin');
$router->get('auth/logout', 'Auth\AuthController@getLogout');
// Users
$router->resource('users', 'UsersController', ['except' => ['create', 'store']]);
$router->get('search', ['as' => 'user.search', 'uses' => 'UsersController@search']);
// Superusers
$router->resource('superusers', 'SuperusersController', ['only' => ['index']]);
// Clients
$router->resource('clients', 'ClientController');
|
<?php
/**
* Here is where you can register web routes for your application. These
* routes are loaded by the RouteServiceProvider within a group which
* contains the "web" middleware group. Now create something great!
*
* @var \Illuminate\Routing\Router $router
* @see \Aurora\Providers\RouteServiceProvider
*/
// Homepage
$router->get('/', 'HomeController@home');
// Authentication
$router->get('auth/login', 'Auth\AuthController@getLogin');
$router->get('auth/logout', 'Auth\AuthController@getLogout');
// Users
$router->resource('users', 'UsersController', ['except' => ['create', 'store']]);
$router->get('search', ['as' => 'user.search', 'uses' => 'UsersController@search']);
// Superusers
$router->resource('superusers', 'SuperusersController', ['only' => ['index']]);
// Clients
$router->resource('clients', 'ClientController');
|
Fix issue where book names weren't being lowercased
The book name must be lowercased in order to be compared with the query
string.
|
import m from 'mithril';
// The core back-end model consisting of shared functions and data
class Core {
// Fetch any arbitrary JSON data via the given data file path
static getJSON(dataFilePath) {
return m.request({url: dataFilePath});
}
// Retrieve the Bible data for the current language (English for now)
static getBibleData() {
return this.getJSON('data/bible/language-eng.json');
}
// Retrieve an object of YouVersion book IDs mapped to the number of chapters
// in each
static getChapterData() {
return this.getJSON('data/bible/chapters.json');
}
// Change the query string to be in a consistent format
static normalizeQueryStr(queryStr) {
queryStr = queryStr.toLowerCase();
// Remove all non-alphanumeric characters
queryStr = queryStr.replace(/[\W_]/gi, ' ', queryStr);
// Remove extra whitespace
queryStr = queryStr.trim();
queryStr = queryStr.replace(/\s+/g, ' ', queryStr);
// Parse shorthand reference notation
queryStr = queryStr.replace(/(\d)(?=[a-z])/, '$1 ', queryStr);
return queryStr;
}
}
export default Core;
|
import m from 'mithril';
// The core back-end model consisting of shared functions and data
class Core {
// Fetch any arbitrary JSON data via the given data file path
static getJSON(dataFilePath) {
return m.request({url: dataFilePath});
}
// Retrieve the Bible data for the current language (English for now)
static getBibleData() {
return this.getJSON('data/bible/language-eng.json');
}
// Retrieve an object of YouVersion book IDs mapped to the number of chapters
// in each
static getChapterData() {
return this.getJSON('data/bible/chapters.json');
}
// Change the query string to be in a consistent format
static normalizeQueryStr(queryStr) {
queryStr - queryStr.toLowerCase();
// Remove all non-alphanumeric characters
queryStr = queryStr.replace(/[\W_]/gi, ' ', queryStr);
// Remove extra whitespace
queryStr = queryStr.trim();
queryStr = queryStr.replace(/\s+/g, ' ', queryStr);
// Parse shorthand reference notation
queryStr = queryStr.replace(/(\d)(?=[a-z])/, '$1 ', queryStr);
return queryStr;
}
}
export default Core;
|
Set the allowed methods to all required ones.
The Spring boot default ones do not allow for `PUT` and `DELETE`.
|
package org.zalando.pazuzu.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfiguration {
@Value("${pazuzu.registry.cors.allowedOrigins:}")
private String allowedOrigins;
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/api/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "PUT", "POST", "DELETE");
}
};
}
}
|
package org.zalando.pazuzu.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfiguration {
@Value("${pazuzu.registry.cors.allowedOrigins:}")
private String allowedOrigins;
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins(allowedOrigins);
}
};
}
}
|
Update overrides iterator to use Array.forEach
|
var log = require('../lib/logger');
var config = {
coinbaseApiKey: process.env.COINBASE_API_KEY,
coinbaseApiSec: process.env.COINBASE_API_SECRET,
coinbaseApiUri: process.env.COINBASE_API_URI,
coinbaseApiWallet: process.env.COINBASE_API_WALLET,
dbUrl: process.env.DATABASE_URL,
redisUrl: process.env.REDIS_URL,
secret: process.env.SECRET,
mailerUser: process.env.MG_USER,
mailerPass: process.env.MG_PASS,
authSecret: process.env.AUTH_SECRET
};
try {
var overrides = require('./configOverrides.js');
Object.keys(overrides).forEach(function(key) {
log.debug("found override for " + key);
config[key] = overrides[key];
});
} catch (e) {
// if no override file is found
log.debug("no overrides found, reverting to env vars");
}
module.exports = config;
|
var log = require('../lib/logger');
var allTheSettings = {
coinbaseApiKey: process.env.COINBASE_API_KEY,
coinbaseApiSec: process.env.COINBASE_API_SECRET,
coinbaseApiUri: process.env.COINBASE_API_URI,
coinbaseApiWallet: process.env.COINBASE_API_WALLET,
dbUrl: process.env.DATABASE_URL,
redisUrl: process.env.REDIS_URL,
secret: process.env.SECRET,
mailerUser: process.env.MG_USER,
mailerPass: process.env.MG_PASS,
authSecret: process.env.AUTH_SECRET
};
try {
var overrides = require('./configOverrides.js');
log.debug("Found overrides for", Object.keys(overrides));
for (var prop in overrides) {
if (overrides.hasOwnProperty(prop)) {
if (allTheSettings[prop]) {
allTheSettings[prop] = overrides[prop];
}
}
}
} catch (e) {
// if no override file is found
log.debug("no overrides found, reverting to env vars");
}
module.exports = allTheSettings;
|
Remove name, url and email from comment form
|
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_comments.models import Comment
from news.models import Blob, BlobInstance
from .models import ThreadedComment
def single_comment(request, id):
comment = get_object_or_404(ThreadedComment, id=id)
variables = RequestContext(request, {'comment': comment})
return render_to_response('comments/single.html', variables)
def comment_posted( request ):
if request.GET['c']:
comment_id, blob_id = request.GET['c'].split( ':' )
blob = Blob.objects.get( pk=blob_id )
if post:
return HttpResponseRedirect( blob.get_absolute_url() )
return HttpResponseRedirect( "/" )
|
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_comments.models import Comment
from .models import ThreadedComment
def single_comment(request, id):
comment = get_object_or_404(ThreadedComment, id=id)
variables = RequestContext(request, {'comment': comment})
return render_to_response('comments/single.html', variables)
def comment_posted( request ):
if request.GET['c']:
comment_id, feeditem_id = request.GET['c'].split( ':' )
feeditem = FeedItem.objects.get( pk=feeditem_id )
if post:
return HttpResponseRedirect( feeditem.get_absolute_url() )
return HttpResponseRedirect( "/" )
|
Make only left-button, unmasked clicks operate conflict buttons
|
/*
* Copyright (C) 2013 Aaron Madlon-Kay <aaron@madlon-kay.com>
*
* 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.
*/
package org.madlonkay.supertmxmerge.gui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractButton;
/**
*
* @author Aaron Madlon-Kay <aaron@madlon-kay.com>
*/
public class ClickForwarder extends MouseAdapter {
private AbstractButton target;
public ClickForwarder(AbstractButton target) {
this.target = target;
}
@Override
public void mouseClicked(MouseEvent me) {
if (me.getButton() == MouseEvent.BUTTON1 && me.getModifiersEx() == 0) {
target.doClick();
}
}
}
|
/*
* Copyright (C) 2013 Aaron Madlon-Kay <aaron@madlon-kay.com>
*
* 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.
*/
package org.madlonkay.supertmxmerge.gui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractButton;
/**
*
* @author Aaron Madlon-Kay <aaron@madlon-kay.com>
*/
public class ClickForwarder extends MouseAdapter {
private AbstractButton target;
public ClickForwarder(AbstractButton target) {
this.target = target;
}
@Override
public void mouseClicked(MouseEvent me) {
target.doClick();
}
}
|
Test for .wfbundle filename, not .scufl2
git-svn-id: d93a27e49e8366f092fe01955016b9f01f5c8622@14416 bf327186-88b3-11dd-a302-d386e5130c1c
|
package uk.org.taverna.scufl2.usecases;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
public class TestConvertT2flowScufl2 {
@Test
public void testname() throws Exception {
File tmp = File.createTempFile("scufl2-ebi-interproscan", ".t2flow");
tmp.deleteOnExit();
InputStream ebi = getClass().getResourceAsStream("/workflows/t2flow/ebi_interproscan_for_taverna_2_317472.t2flow");
FileOutputStream output = new FileOutputStream(tmp);
IOUtils.copy(ebi, output);
output.close();
ConvertT2flowScufl2.main(new String[]{tmp.getAbsolutePath()});
File scufl2File = new File(tmp.getAbsolutePath().replace(".t2flow", ".wfbundle"));
assertTrue(scufl2File.isFile());
assertNotNull(new ZipFile(scufl2File).getEntry("workflowBundle.rdf"));
scufl2File.deleteOnExit();
// System.out.println(scufl2File);
}
}
|
package uk.org.taverna.scufl2.usecases;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
public class TestConvertT2flowScufl2 {
@Test
public void testname() throws Exception {
File tmp = File.createTempFile("scufl2-ebi-interproscan", ".t2flow");
tmp.deleteOnExit();
InputStream ebi = getClass().getResourceAsStream("/workflows/t2flow/ebi_interproscan_for_taverna_2_317472.t2flow");
FileOutputStream output = new FileOutputStream(tmp);
IOUtils.copy(ebi, output);
output.close();
ConvertT2flowScufl2.main(new String[]{tmp.getAbsolutePath()});
File scufl2File = new File(tmp.getAbsolutePath().replace(".t2flow", ".scufl2"));
assertTrue(scufl2File.isFile());
assertNotNull(new ZipFile(scufl2File).getEntry("workflowBundle.rdf"));
scufl2File.deleteOnExit();
// System.out.println(scufl2File);
}
}
|
Check for composer wherever it is signaled to be, even after override
|
<?php
namespace Probuild\Shell;
use Probuild\Shell;
class Composer extends Shell
{
protected $composer = 'composer';
/**
* @param string $targetDir
* @return Composer
* @author Cristian Quiroz <cris@qcas.co>
*/
public function run($targetDir)
{
if (!`which {$this->composer}`) {
$this->write(sprintf('<error>\'%s\' is not installed.</error>', $this->composer));
return $this;
}
$this->exec("{$this->composer} update -d {$targetDir}");
return $this;
}
/**
* @param string $composer
* @author Cristian Quiroz <cris@qcas.co>
* @return Composer
*/
public function setComposerCommand($composer)
{
$this->composer = $composer;
return $this;
}
}
|
<?php
namespace Probuild\Shell;
use Probuild\Shell;
class Composer extends Shell
{
protected $composer = 'composer';
/**
* @param string $targetDir
* @return Composer
* @author Cristian Quiroz <cris@qcas.co>
*/
public function run($targetDir)
{
if (!`which composer`) {
$this->write('<error>\'composer\' is not installed.</error>');
return $this;
}
$this->exec("{$this->composer} update -d {$targetDir}");
return $this;
}
/**
* @param string $composer
* @author Cristian Quiroz <cris@qcas.co>
* @return Composer
*/
public function setComposerCommand($composer)
{
$this->composer = $composer;
return $this;
}
}
|
Fix merge (phpdoc => typehint)
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
/**
* This is a wrapper around the actual firewall configuration which allows us
* to lazy load the context for one specific firewall only when we need it.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class FirewallContext
{
private $listeners;
private $exceptionListener;
private $config;
public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
{
$this->listeners = $listeners;
$this->exceptionListener = $exceptionListener;
$this->config = $config;
}
public function getConfig()
{
return $this->config;
}
public function getListeners(): iterable
{
return $this->listeners;
}
public function getExceptionListener()
{
return $this->exceptionListener;
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
/**
* This is a wrapper around the actual firewall configuration which allows us
* to lazy load the context for one specific firewall only when we need it.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class FirewallContext
{
private $listeners;
private $exceptionListener;
private $config;
/**
* @param \Traversable|array $listeners
* @param ExceptionListener|null $exceptionListener
* @param FirewallConfig|null $firewallConfig
*/
public function __construct($listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
{
$this->listeners = $listeners;
$this->exceptionListener = $exceptionListener;
$this->config = $config;
}
public function getConfig()
{
return $this->config;
}
/**
* @return \Traversable|array
*/
public function getListeners()
{
return $this->listeners;
}
public function getExceptionListener()
{
return $this->exceptionListener;
}
}
|
Update class names for more consistency
|
import Remarkable from 'remarkable';
const markdown = (text) => {
var md = new Remarkable();
return {
__html: md.render(text)
};
};
const Event = ({ title, start_time, end_time, content, eventClickHandler, index, active }) => {
const classes = (index === active) ? 'cal-event-content-active' : '';
return (
<a href={`#event-${index}`} onClick={ () => { eventClickHandler(index); } } className="cal-event" id={`event-${index}`}>
<div className="cal-event-indicator"></div>
<div className="cal-event-header">
<p className="cal-event-date">{start_time.toTimeString().substr(0, 5)}</p>
<h3 className="cal-event-title">{title}</h3>
</div>
<p className={`cal-event-content ${ classes }`} dangerouslySetInnerHTML={markdown(content)}/>
<p className={`cal-event-content ${ classes } cal-event-endtime`}>Antatt sluttidspunkt: {end_time.toTimeString().substr(0, 5)}</p>
</a>
);
};
export default Event;
|
import Remarkable from 'remarkable';
const markdown = (text) => {
var md = new Remarkable();
return {
__html: md.render(text)
};
};
const Event = ({ title, start_time, end_time, content, eventClickHandler, index, active }) => {
const classes = (index === active) ? 'cal-event-content-active' : '';
return (
<a href={`#event-${index}`} onClick={ () => { eventClickHandler(index); } } className="cal-event" id={`event-${index}`}>
<div className="cal-event-indicator"></div>
<div className="cal-event-header">
<p className="cal-event-dateString">{start_time.toTimeString().substr(0, 5)}</p>
<h3 className="cal-title">{title}</h3>
</div>
<p className={`cal-event-content ${ classes }`} dangerouslySetInnerHTML={markdown(content)}/>
<p className={`cal-event-content ${ classes } cal-event-endtime`}>Antatt sluttidspunkt: {end_time.toTimeString().substr(0, 5)}</p>
</a>
);
};
export default Event;
|
Return null when a response is not succesful.
|
<?php
namespace Sdmx\api\client\http;
use Requests;
class RequestHttpClient implements HttpClient
{
/**
* @var array $predefinedHeaders
*/
private $predefinedHeaders = [];
/**
* @param string $url
* @param array $headers
* @param array $options
* @return string
*/
public function get($url, $headers = array('Accept' => 'application/xml', 'Accept-Encoding' => 'gzip'), $options = array())
{
$headersToSend = array_merge($this->predefinedHeaders, $headers);
$response = Requests::get($url, $headersToSend, $options);
return $response->success ? $response->body : null;
}
/**
* @param array $headers
*/
public function setPredefinedHeaders(array $headers)
{
$this->predefinedHeaders = $headers;
}
}
|
<?php
namespace Sdmx\api\client\http;
use Requests;
class RequestHttpClient implements HttpClient
{
/**
* @var array $predefinedHeaders
*/
private $predefinedHeaders = [];
/**
* @param string $url
* @param array $headers
* @param array $options
* @return string
*/
public function get($url, $headers = array('Accept' => 'application/xml', 'Accept-Encoding' => 'gzip'), $options = array())
{
$headersToSend = array_merge($this->predefinedHeaders, $headers);
$response = Requests::get($url, $headersToSend, $options);
return $response->body;
}
/**
* @param array $headers
*/
public function setPredefinedHeaders(array $headers)
{
$this->predefinedHeaders = $headers;
}
}
|
Fix teacher ids not being mapped
|
package li.l1t.tingo.service;
import li.l1t.tingo.exception.TeacherNotFoundException;
import li.l1t.tingo.model.Teacher;
import li.l1t.tingo.model.dto.TeacherDto;
import li.l1t.tingo.model.repo.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service handling teachers, providing a bridge between the controller and the model.
*
* @author <a href="http://xxyy.github.io/">xxyy</a>
* @since 2016-02-14
*/
@Service
public class TeacherService {
@Autowired
private TeacherRepository teacherRepository;
public Iterable<Teacher> getAllTeachers() {
return teacherRepository.findAll();
}
public Teacher getById(int id) {
Teacher teacher = teacherRepository.findOne(id);
if(teacher == null) {
throw new TeacherNotFoundException(id);
}
return teacher;
}
public TeacherDto toDto(Teacher entity) {
TeacherDto dto = new TeacherDto();
dto.setId(entity.getId());
dto.setAbbreviation(entity.getAbbreviation());
dto.setName(entity.getName());
return dto;
}
}
|
package li.l1t.tingo.service;
import li.l1t.tingo.exception.TeacherNotFoundException;
import li.l1t.tingo.model.Teacher;
import li.l1t.tingo.model.dto.TeacherDto;
import li.l1t.tingo.model.repo.TeacherRepository;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service handling teachers, providing a bridge between the controller and the model.
*
* @author <a href="http://xxyy.github.io/">xxyy</a>
* @since 2016-02-14
*/
@Service
public class TeacherService {
private final DozerBeanMapper dozerBeanMapper;
private final TeacherRepository teacherRepository;
@Autowired
public TeacherService(DozerBeanMapper dozerBeanMapper, TeacherRepository teacherRepository) {
this.dozerBeanMapper = dozerBeanMapper;
this.teacherRepository = teacherRepository;
}
public Iterable<Teacher> getAllTeachers() {
return teacherRepository.findAll();
}
public Teacher getById(int id) {
Teacher teacher = teacherRepository.findOne(id);
if(teacher == null) {
throw new TeacherNotFoundException(id);
}
return teacher;
}
public TeacherDto toDto(Teacher entity) {
return dozerBeanMapper.map(entity, TeacherDto.class);
}
}
|
Add support for Redux Devtools extension
|
import moment from 'moment';
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer as HotAppContainer } from 'react-hot-loader';
import { applyMiddleware, createStore, compose } from 'redux';
import IO from 'socket.io-client';
import createSocketIoMiddleware from 'redux-socket.io';
import logger from 'redux-logger';
import 'normalize.css';
import Raven from 'raven-js';
import votingApp from './reducers';
import Routes from './routes';
moment.locale('nb');
Raven
.config(process.env.SDF_SENTRY_DSN_FRONTEND, {
tags: {
app: 'frontend',
},
})
.install();
const socket = IO.connect();
const socketIoMiddleware = createSocketIoMiddleware(socket, 'server/');
// eslint-disable-next-line no-underscore-dangle
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
votingApp,
composeEnhancers(applyMiddleware(socketIoMiddleware, logger)),
);
const render = (RootRoute) => {
ReactDOM.render(
<HotAppContainer>
<RootRoute store={store} />
</HotAppContainer>,
document.getElementById('app'),
);
};
render(Routes);
if (module.hot) {
module.hot.accept('./routes', () => {
render(Routes);
});
}
|
import moment from 'moment';
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer as HotAppContainer } from 'react-hot-loader';
import { applyMiddleware, createStore } from 'redux';
import IO from 'socket.io-client';
import createSocketIoMiddleware from 'redux-socket.io';
import logger from 'redux-logger';
import 'normalize.css';
import Raven from 'raven-js';
import votingApp from './reducers';
import Routes from './routes';
moment.locale('nb');
Raven
.config(process.env.SDF_SENTRY_DSN_FRONTEND, {
tags: {
app: 'frontend',
},
})
.install();
const socket = IO.connect();
const socketIoMiddleware = createSocketIoMiddleware(socket, 'server/');
const store = applyMiddleware(socketIoMiddleware, logger)(createStore)(votingApp);
const render = (RootRoute) => {
ReactDOM.render(
<HotAppContainer>
<RootRoute store={store} />
</HotAppContainer>,
document.getElementById('app'),
);
};
render(Routes);
if (module.hot) {
module.hot.accept('./routes', () => {
render(Routes);
});
}
|
internal-test-helpers: Convert `ContainersAssert` to ES6 class
|
import { Container } from '@ember/-internals/container';
const { _leakTracking: containerLeakTracking } = Container;
export default class ContainersAssert {
constructor(env) {
this.env = env;
}
reset() {}
inject() {}
assert() {
if (containerLeakTracking === undefined) return;
let { config } = QUnit;
let {
testName,
testId,
module: { name: moduleName },
finish: originalFinish,
} = config.current;
config.current.finish = function() {
originalFinish.call(this);
originalFinish = undefined;
config.queue.unshift(function() {
if (containerLeakTracking.hasContainers()) {
containerLeakTracking.reset();
// eslint-disable-next-line no-console
console.assert(
false,
`Leaked container after test ${moduleName}: ${testName} testId=${testId}`
);
}
});
};
}
restore() {}
}
|
import { Container } from '@ember/-internals/container';
function ContainersAssert(env) {
this.env = env;
}
const { _leakTracking: containerLeakTracking } = Container;
ContainersAssert.prototype = {
reset: function() {},
inject: function() {},
assert: function() {
if (containerLeakTracking === undefined) return;
let { config } = QUnit;
let {
testName,
testId,
module: { name: moduleName },
finish: originalFinish,
} = config.current;
config.current.finish = function() {
originalFinish.call(this);
originalFinish = undefined;
config.queue.unshift(function() {
if (containerLeakTracking.hasContainers()) {
containerLeakTracking.reset();
// eslint-disable-next-line no-console
console.assert(
false,
`Leaked container after test ${moduleName}: ${testName} testId=${testId}`
);
}
});
};
},
restore: function() {},
};
export default ContainersAssert;
|
Comment long_description read, because it cause exception
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 424
|
import os
from setuptools import setup, find_packages
VERSION = (0, 1, 7)
__version__ = '.'.join(map(str, VERSION))
# readme_rst = os.path.join(os.path.dirname(__file__), 'README.rst')
# if os.path.exists(readme_rst):
# long_description = open(readme_rst).read()
# else:
long_description = "This module provides a few map widgets for Django applications."
# 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-map-widgets',
version=__version__,
description="Map widgets for Django PostGIS fields",
long_description=long_description,
author="Erdem Ozkol",
author_email="erdemozkol@gmail.com",
url="https://github.com/erdem/django-map-widgets",
license="MIT",
platforms=["any"],
packages=find_packages(exclude=("example", "static", "env")),
include_package_data=True,
classifiers=[
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Framework :: Django",
"Programming Language :: Python",
],
)
|
import os
from setuptools import setup, find_packages
VERSION = (0, 1, 7)
__version__ = '.'.join(map(str, VERSION))
readme_rst = os.path.join(os.path.dirname(__file__), 'README.rst')
if os.path.exists(readme_rst):
long_description = open(readme_rst).read()
else:
long_description = "This module provides a few map widgets for Django applications."
# 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-map-widgets',
version=__version__,
description="Map widgets for Django PostGIS fields",
long_description=long_description,
author="Erdem Ozkol",
author_email="erdemozkol@gmail.com",
url="https://github.com/erdem/django-map-widgets",
license="MIT",
platforms=["any"],
packages=find_packages(exclude=("example", "static", "env")),
include_package_data=True,
classifiers=[
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Framework :: Django",
"Programming Language :: Python",
],
)
|
Remove `setState`, For hide modal, it is enough to call `onHidePromoteModal`.
|
import React, { Component } from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
// NOTE: For emit `onTouchTap` event.
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class PromoteModal extends Component {
constructor(props) {
super(props);
this.state = { open: false };
}
closeModal() {
this.props.onHidePromoteModal();
}
render() {
const actions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />,
<FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} />
];
return (
<div>
<Dialog title="" actions={actions} modal={true} open={this.props.open} />
</div>
);
}
}
|
import React, { Component } from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
// NOTE: For emit `onTouchTap` event.
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class PromoteModal extends Component {
constructor(props) {
super(props);
this.state = { open: false };
}
closeModal() {
this.props.onHidePromoteModal();
this.setState({ open: this.props.open });
}
render() {
const actions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />,
<FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} />
];
return (
<div>
<Dialog title="" actions={actions} modal={true} open={this.props.open} />
</div>
);
}
}
|
core: Add missing serial version id
Change-Id: I1467bfda3a1f349087266bedb0fafac7170baeb2
Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>
|
package org.ovirt.engine.core.common.queries;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
public class GetFilteredAttachableDisksParameters extends GetAllAttachableDisksForVmQueryParameters {
private static final long serialVersionUID = 4092810692277463140L;
private int os;
private Version vdsGroupCompatibilityVersion;
public GetFilteredAttachableDisksParameters() {
super();
}
public GetFilteredAttachableDisksParameters(Guid storagePoolId) {
super(storagePoolId);
}
public int getOs() {
return os;
}
public void setOs(int os) {
this.os = os;
}
public Version getVdsGroupCompatibilityVersion() {
return vdsGroupCompatibilityVersion;
}
public void setVdsGroupCompatibilityVersion(Version vdsGroupCompatibilityVersion) {
this.vdsGroupCompatibilityVersion = vdsGroupCompatibilityVersion;
}
}
|
package org.ovirt.engine.core.common.queries;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
public class GetFilteredAttachableDisksParameters extends GetAllAttachableDisksForVmQueryParameters {
private int os;
private Version vdsGroupCompatibilityVersion;
public GetFilteredAttachableDisksParameters() {
super();
}
public GetFilteredAttachableDisksParameters(Guid storagePoolId) {
super(storagePoolId);
}
public int getOs() {
return os;
}
public void setOs(int os) {
this.os = os;
}
public Version getVdsGroupCompatibilityVersion() {
return vdsGroupCompatibilityVersion;
}
public void setVdsGroupCompatibilityVersion(Version vdsGroupCompatibilityVersion) {
this.vdsGroupCompatibilityVersion = vdsGroupCompatibilityVersion;
}
}
|
Implement getTitle and getDescription for search
|
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
getTitle: function() {
return i18n.t("Search") + ' - ' + getSetting('title', "Telescope");
},
getDescription: function() {
return getSetting('description');
},
onBeforeAction: function() {
var query = this.params.query;
if ('q' in query) {
Session.set('searchQuery', query.q);
if (query.q) {
Meteor.call('logSearch', query.q)
}
}
this.next();
}
});
Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']});
// Search
Router.route('/search/:limit?', {
name: 'search',
controller: PostsSearchController
});
// Search Logs
Router.route('/logs/:limit?', {
name: 'searchLogs',
waitOn: function () {
var limit = this.params.limit || 100;
if(Meteor.isClient) {
Session.set('logsLimit', limit);
}
return Meteor.subscribe('searches', limit);
},
data: function () {
return Searches.find({}, {sort: {timestamp: -1}});
},
fastRender: true
});
});
|
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
onBeforeAction: function() {
var query = this.params.query;
if ('q' in query) {
Session.set('searchQuery', query.q);
if (query.q) {
Meteor.call('logSearch', query.q)
}
}
this.next();
}
});
Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']});
// Search
Router.route('/search/:limit?', {
name: 'search',
controller: PostsSearchController
});
// Search Logs
Router.route('/logs/:limit?', {
name: 'searchLogs',
waitOn: function () {
var limit = this.params.limit || 100;
if(Meteor.isClient) {
Session.set('logsLimit', limit);
}
return Meteor.subscribe('searches', limit);
},
data: function () {
return Searches.find({}, {sort: {timestamp: -1}});
},
fastRender: true
});
});
|
Use the config for token
And yes, I did regenerate that token, don't bother.
|
const Discord = require('discord.js');
const client = new Discord.Client();
const _ = require('lodash');
const winston = require('winston');
require('dotenv').config();
const channel_handler = require('./channel_handler');
const presence_handler = require('./presence_handler');
winston.configure({
transports: [
new (winston.transports.Console)({
timestamp: true,
}),
new (winston.transports.File)({
filename: 'sgs_bot.log',
}),
],
});
client.on('ready', () => {
winston.log('info', 'Logged into Discord as %s', client.user.tag);
// set creepy presence
client.user.setPresence({
status: 'online',
afk: false,
game: {
name: 'Big Brother',
url: '',
},
});
});
client.on('presenceUpdate', presence_handler.handlePresenceUpdate);
client.on('voiceStateUpdate', channel_handler.handleVoiceStateUpdate);
client.login(process.env.DISCORD_KEY);
|
const Discord = require('discord.js');
const client = new Discord.Client();
const _ = require('lodash');
const winston = require('winston');
require('dotenv').config();
const channel_handler = require('./channel_handler');
const presence_handler = require('./presence_handler');
winston.configure({
transports: [
new (winston.transports.Console)({
timestamp: true,
}),
new (winston.transports.File)({
filename: 'sgs_bot.log',
}),
],
});
client.on('ready', () => {
winston.log('info', 'Logged into Discord as %s', client.user.tag);
// set creepy presence
client.user.setPresence({
status: 'online',
afk: false,
game: {
name: 'Big Brother',
url: '',
},
});
});
client.on('presenceUpdate', presence_handler.handlePresenceUpdate);
client.on('voiceStateUpdate', channel_handler.handleVoiceStateUpdate);
client.login('MzMwMDgzODQ2NzQzNjU0NDAx.DDb8_A.Aq9f9KnUQq4Hu_oqVxxULnS5BUY');
|
Add spec for endpoints function
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint-env node, mocha */
import test from 'ava';
import endpoint from '../src/endpoint';
test('endpoint returns correctly partially applied function', (t) => {
const endpointConfig = {
uri: 'http://example.com',
};
const init = () => {};
const Request = (uriOpt, initOpt) => {
t.true(uriOpt === endpointConfig.uri);
t.true(initOpt.toString() === init.toString());
};
endpoint(Request, init)(endpointConfig);
});
test.skip('returns a request object with the correct url', (t) => {
const testUrl = 'http://api.example.com/v1/';
const Request = (url) => {
t.true(url === testUrl);
};
endpoint(Request);
});
test.skip('should append a trailing slash if one is missing in the given url', (t) => {
const testUrl = 'http://api.example.com/v1';
const Request = (url) => {
t.true(url === `${testUrl}/`);
};
endpoint(Request);
});
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint-env node, mocha */
import test from 'ava';
import endpoint from '../src/endpoint';
test('happy ponies', () => {
const fetch = () => null;
api(null, null, {
baseUri: 'http://api.example.com/v1',
endpoints: [
{
endpoint: '/happy/ponies/{id}',
method: 'GET',
requiredParams: ['id'],
optionalParams: ['lastSeenId'],
}
]
});
});
test.skip('returns a request object with the correct url', (t) => {
const testUrl = 'http://api.example.com/v1/';
const Request = (url) => {
t.true(url === testUrl);
};
endpoint(Request);
});
test.skip('should append a trailing slash if one is missing in the given url', (t) => {
const testUrl = 'http://api.example.com/v1';
const Request = (url) => {
t.true(url === `${testUrl}/`);
};
endpoint(Request);
});
|
Switch to API version 009 for generation.
|
<?php
// Map 'src' and 'lib' folders to the Wsdl2PhpGenerator namespace in your
// favorite PSR-0 compatible classloader or require the files manually.
require __DIR__ . '/../vendor/autoload.php';
use Wsdl2PhpGenerator\Config;
$generator = new \Wsdl2PhpGenerator\Generator();
$generator->generate(new Config(array(
'inputFile' => __DIR__ . '/../YellowCubeService_009/YellowCubeService_extern.wsdl',
'outputDir' => 'gen/YellowCube',
'verbose' => false,
'namespaceName' => 'YellowCube',
'sharedTypes' => true,
'constructorParamsDefaultToNull' => true,
'soapClientClass' => '\\YellowCube\Util\SoapClient'
)));
|
<?php
// Map 'src' and 'lib' folders to the Wsdl2PhpGenerator namespace in your
// favorite PSR-0 compatible classloader or require the files manually.
require __DIR__ . '/../vendor/autoload.php';
use Wsdl2PhpGenerator\Config;
$generator = new \Wsdl2PhpGenerator\Generator();
$generator->generate(new Config(array(
'inputFile' => './YellowCubeService_005/YellowCubeService.wsdl',
'outputDir' => 'gen/YellowCube',
'verbose' => false,
'namespaceName' => 'YellowCube',
'sharedTypes' => true,
'constructorParamsDefaultToNull' => true,
'soapClientClass' => '\\YellowCube\Util\SoapClient'
)));
|
fix: Use watch instead of watchFile
|
#!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(500).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
const watcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change') {
delete require.cache[filePath];
watcher.close();
}
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
|
#!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(500).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
fs.watchFile(filePath, () => {
delete require.cache[filePath];
fs.unwatchFile(filePath);
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
|
Add post date on search results
|
<header class="entry-header">
<?php
if ( is_sticky() && ! is_single() ) :
printf( '<p class="sticky-title-sm">%s</p>', __( 'Must read', 'keitaro' ) );
endif;
if ( is_singular() ) :
the_title( '<h1 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h1>' );
elseif ( is_front_page() && is_home() ) :
the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' );
elseif ( is_sticky() ) :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
else :
the_title( '<h2 class="entry-title h3"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) :
echo '<div class="entry-meta">';
if ( is_singular() || is_archive() || is_home() || is_search() ) :
keitaro_posted_on();
endif;
echo '</div><!-- .entry-meta -->';
endif;
?>
</header>
|
<header class="entry-header">
<?php
if ( is_sticky() && ! is_single() ) :
printf( '<p class="sticky-title-sm">%s</p>', __( 'Must read', 'keitaro' ) );
endif;
if ( is_singular() ) :
the_title( '<h1 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h1>' );
elseif ( is_front_page() && is_home() ) :
the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' );
elseif ( is_sticky() ) :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
else :
the_title( '<h2 class="entry-title h3"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) :
echo '<div class="entry-meta">';
if ( is_single() || is_archive() || is_home() ) :
keitaro_posted_on();
endif;
echo '</div><!-- .entry-meta -->';
endif;
?>
</header>
|
Switch back to using innerText
I thought innerHTML might preserve spaces better, but the encoding is
actually working fine without innerText
|
document.addEventListener('DOMContentLoaded', function() {
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerText = quotedPrintable.decode(source);
});
});
}
|
document.addEventListener('DOMContentLoaded', function() {
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerHTML = quotedPrintable.decode(source);
});
});
}
|
Make abstract method final to avoid unwanted overloading
|
<?php
namespace Trappar\AliceGenerator\Metadata\Resolver\Faker;
use Trappar\AliceGenerator\DataStorage\ValueContext;
use Trappar\AliceGenerator\Faker\FakerGenerator;
use Trappar\AliceGenerator\Metadata\Resolver\AbstractMetadataResolver;
abstract class AbstractFakerResolver extends AbstractMetadataResolver implements FakerResolverInterface
{
final public function resolve(ValueContext $valueContext)
{
$this->validate($valueContext);
$result = $this->handle($valueContext);
if (!$result instanceof ValueContext) {
if (is_array($result)) {
$result = FakerGenerator::generate($valueContext->getMetadata()->fakerName, $result);
}
$valueContext->setValue($result);
}
}
/**
* @inheritDoc
*/
public function validate(ValueContext $valueContext)
{
}
}
|
<?php
namespace Trappar\AliceGenerator\Metadata\Resolver\Faker;
use Trappar\AliceGenerator\DataStorage\ValueContext;
use Trappar\AliceGenerator\Faker\FakerGenerator;
use Trappar\AliceGenerator\Metadata\Resolver\AbstractMetadataResolver;
abstract class AbstractFakerResolver extends AbstractMetadataResolver implements FakerResolverInterface
{
public function resolve(ValueContext $valueContext)
{
$this->validate($valueContext);
$result = $this->handle($valueContext);
if (!$result instanceof ValueContext) {
if (is_array($result)) {
$result = FakerGenerator::generate($valueContext->getMetadata()->fakerName, $result);
}
$valueContext->setValue($result);
}
}
/**
* @inheritDoc
*/
public function validate(ValueContext $valueContext)
{
}
}
|
Add both domains to hostsfile.
|
"""
Dynamic host file management.
"""
import docker
from subprocess import call
import re
def refresh():
"""
Ensure that all running containers have a valid entry in /etc/hosts.
"""
containers = docker.containers()
hosts = '\n'.join(['%s %s.%s.dork %s' % (c.address, c.project, c.instance, c.domain) for c in [d for d in containers if d.running]])
hosts = '# DORK START\n%s\n# DORK END' % hosts
expr = re.compile('# DORK START\n(.*\n)*# DORK END')
with open('/etc/hosts', 'r') as f:
content = f.read()
if len(expr.findall(content)) > 0:
content = expr.sub(hosts, content)
else:
content += hosts + '\n'
with open('/etc/hosts', 'w') as f:
f.write(content)
call(['sudo', 'service', 'dnsmasq', 'restart'])
|
"""
Dynamic host file management.
"""
import docker
from subprocess import call
import re
def refresh():
"""
Ensure that all running containers have a valid entry in /etc/hosts.
"""
containers = docker.containers()
hosts = '\n'.join(['%s %s' % (c.address, c.domain) for c in [d for d in containers if d.running]])
hosts = '# DORK START\n%s\n# DORK END' % hosts
expr = re.compile('# DORK START\n(.*\n)*# DORK END')
with open('/etc/hosts', 'r') as f:
content = f.read()
if len(expr.findall(content)) > 0:
content = expr.sub(hosts, content)
else:
content += hosts + '\n'
with open('/etc/hosts', 'w') as f:
f.write(content)
call(['sudo', 'service', 'dnsmasq', 'restart'])
|
Hide PyLint warning with undefined WindowsError exception
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import atexit
from os import remove
from tempfile import mkstemp
MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192
def _remove_tmpfile(path):
try:
remove(path)
except WindowsError: # pylint: disable=E0602
pass
def _huge_sources_hook(sources):
if len(str(sources)) < MAX_SOURCES_LENGTH:
return sources
_, tmp_file = mkstemp()
with open(tmp_file, "w") as f:
f.write(str(sources).replace("\\", "/"))
atexit.register(_remove_tmpfile, tmp_file)
return "@%s" % tmp_file
def exists(_):
return True
def generate(env):
env.Replace(
_huge_sources_hook=_huge_sources_hook,
ARCOM=env.get("ARCOM", "").replace(
"$SOURCES", "${_huge_sources_hook(SOURCES)}"))
return env
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
import atexit
from os import remove
from tempfile import mkstemp
MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192
def _remove_tmpfile(path):
try:
remove(path)
except WindowsError:
pass
def _huge_sources_hook(sources):
if len(str(sources)) < MAX_SOURCES_LENGTH:
return sources
_, tmp_file = mkstemp()
with open(tmp_file, "w") as f:
f.write(str(sources).replace("\\", "/"))
atexit.register(_remove_tmpfile, tmp_file)
return "@%s" % tmp_file
def exists(_):
return True
def generate(env):
env.Replace(
_huge_sources_hook=_huge_sources_hook,
ARCOM=env.get("ARCOM", "").replace(
"$SOURCES", "${_huge_sources_hook(SOURCES)}"))
return env
|
Add in `value` count, leaving non-interactive as the final parameter
|
// Extension to track errors using google analytics as a data store.
(function() {
"use strict";
var trackJavaScriptError = function (e) {
var errorSource = e.filename + ': ' + e.lineno;
_gaq.push([
'_trackEvent',
'JavaScript Error',
e.message,
errorSource,
1, // Set our value to 1, though we could look to tally session errors here
true // nonInteractive so bounce rate isn't affected
]);
};
if (window.addEventListener) {
window.addEventListener('error', trackJavaScriptError, false);
} else if (window.attachEvent) {
window.attachEvent('onerror', trackJavaScriptError);
} else {
window.onerror = trackJavaScriptError;
}
}());
|
// Extension to track errors using google analytics as a data store.
(function() {
"use strict";
var trackJavaScriptError = function (e) {
var errorSource = e.filename + ': ' + e.lineno;
_gaq.push([
'_trackEvent',
'JavaScript Error',
e.message,
errorSource,
true //nonInteractive so bounce rate isn't affected
]);
};
if (window.addEventListener) {
window.addEventListener('error', trackJavaScriptError, false);
} else if (window.attachEvent) {
window.attachEvent('onerror', trackJavaScriptError);
} else {
window.onerror = trackJavaScriptError;
}
}());
|
Upgrade the version to force reinstall by wheels
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-remote-forms',
version='0.0.2',
description='A platform independent form serializer for Django.',
author='WiserTogether Tech Team',
author_email='tech@wisertogether.com',
url='http://github.com/wisertoghether/django-remote-forms/',
long_description=open('README.md', 'r').read(),
packages=[
'django_remote_forms',
],
package_data={
},
zip_safe=False,
requires=[
],
install_requires=[
],
classifiers=[
'Development Status :: Pre Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: MIT',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-remote-forms',
version='0.0.1',
description='A platform independent form serializer for Django.',
author='WiserTogether Tech Team',
author_email='tech@wisertogether.com',
url='http://github.com/wisertoghether/django-remote-forms/',
long_description=open('README.md', 'r').read(),
packages=[
'django_remote_forms',
],
package_data={
},
zip_safe=False,
requires=[
],
install_requires=[
],
classifiers=[
'Development Status :: Pre Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: MIT',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
build(rollup): Fix path to compiled file
|
import nodeResolve from 'rollup-plugin-node-resolve';
import { globalsRegex, GLOBAL } from 'rollup-globals-regex';
export default {
input: 'dist/ng-dynamic-component.js',
output: {
file: 'dist/bundles/ng-dynamic-component.es2015.js',
format: 'es',
},
name: 'dynamicComponent',
plugins: [
nodeResolve({ jsnext: true, browser: true })
],
globals: globalsRegex({
'tslib': 'tslib',
[GLOBAL.NG2]: GLOBAL.NG2.TPL,
[GLOBAL.RX]: GLOBAL.RX.TPL,
[GLOBAL.RX_OPERATOR]: GLOBAL.RX_OPERATOR.TPL,
}),
external: (moduleId) => {
if (/^(\@angular|rxjs|tslib)\/?/.test(moduleId)) {
return true;
}
return false;
}
};
|
import nodeResolve from 'rollup-plugin-node-resolve';
import { globalsRegex, GLOBAL } from 'rollup-globals-regex';
export default {
input: 'dist/src/ng-dynamic-component.js',
output: {
file: 'dist/bundles/ng-dynamic-component.es2015.js',
format: 'es',
},
name: 'dynamicComponent',
plugins: [
nodeResolve({ jsnext: true, browser: true })
],
globals: globalsRegex({
'tslib': 'tslib',
[GLOBAL.NG2]: GLOBAL.NG2.TPL,
[GLOBAL.RX]: GLOBAL.RX.TPL,
[GLOBAL.RX_OPERATOR]: GLOBAL.RX_OPERATOR.TPL,
}),
external: (moduleId) => {
if (/^(\@angular|rxjs|tslib)\/?/.test(moduleId)) {
return true;
}
return false;
}
};
|
Make file listing more robust
|
from slacksocket import SlackSocket
import subprocess
import config
import os
def handle_cmd(cmd):
if cmd in ('ls','list'):
s.send_msg(list_files(), channel_name=config.slack_channel)
else:
playsound(cmd)
def playsound(sound):
subprocess.call([config.play_cmd,"{0}.mp3".format(sound)])
def list_files():
all_files = os.listdir('.')
mp3s = [parts[0] for file in all_files for parts in [file.split('.')] if parts[-1]=='mp3']
mp3s.sort()
return ' '.join(mp3s)
s = SlackSocket(config.api_key,translate=True)
for event in s.events():
if event.event.get('channel')==config.slack_channel and event.event.get('type')=='message':
print(event.json)
handle_cmd(event.event.get('text'))
|
from slacksocket import SlackSocket
import subprocess
import config
import os
def handle_cmd(cmd):
if cmd in ('ls','list'):
s.send_msg(list_files(), channel_name=config.slack_channel)
else:
playsound(cmd)
def playsound(sound):
subprocess.call([config.play_cmd,"{0}.mp3".format(sound)])
def list_files():
all_files = os.listdir('.')
mp3s = [parts[0] for file in all_files for parts in [file.split('.')] if parts[1]=='mp3']
mp3s.sort()
return ' '.join(mp3s)
s = SlackSocket(config.api_key,translate=True)
for event in s.events():
if event.event.get('channel')==config.slack_channel and event.event.get('type')=='message':
print(event.json)
handle_cmd(event.event.get('text'))
|
Change flow stat reply to include multiple stats
|
package nom
import (
"encoding/gob"
"time"
)
// NodeQuery queries the information of a node.
type NodeQuery struct {
Node UID
}
// NodeQueryResult is the result for NodeQuery.
type NodeQueryResult struct {
Err error
Node Node
}
// PortQuery queries the information of a port.
type PortQuery struct {
Port UID
}
// PortQueryResult is the result for a PortQuery.
type PortQueryResult struct {
Err error
Port Port
}
// FlowStatsQuery queries the flows that would match the query. If Exact is
// false, it removes all flow entries that are subsumed by the given match.
type FlowStatsQuery struct {
Node UID
Match Match
Exact bool
}
// FlowStatsQueryResult is the result for a FlowStatQuery
type FlowStatsQueryResult struct {
Node UID
Stats []FlowStats
}
// FlowStats is the statistics of flow
type FlowStats struct {
Match Match
Duration time.Duration
Packets uint64
Bytes uint64
}
func init() {
gob.Register(FlowStatsQuery{})
gob.Register(FlowStatsQueryResult{})
gob.Register(NodeQuery{})
gob.Register(NodeQueryResult{})
gob.Register(PortQuery{})
gob.Register(PortQueryResult{})
}
|
package nom
import (
"encoding/gob"
"time"
)
// NodeQuery queries the information of a node.
type NodeQuery struct {
Node UID
}
// NodeQueryResult is the result for NodeQuery.
type NodeQueryResult struct {
Err error
Node Node
}
// PortQuery queries the information of a port.
type PortQuery struct {
Port UID
}
// PortQueryResult is the result for a PortQuery.
type PortQueryResult struct {
Err error
Port Port
}
// FlowStatQuery queries the flows that would match the query. If Exact is
// false, it removes all flow entries that are subsumed by the given match.
type FlowStatQuery struct {
Match Match
Exact bool
}
// FlowStatQueryResult is the result for a FlowStatQuery
type FlowStatQueryResult struct {
Flow FlowEntry
Duration time.Duration
PktCount uint64
Bytes uint64
}
func init() {
gob.Register(FlowStatQuery{})
gob.Register(FlowStatQueryResult{})
gob.Register(NodeQuery{})
gob.Register(NodeQueryResult{})
gob.Register(PortQuery{})
gob.Register(PortQueryResult{})
}
|
Disable Darcula special welcome screen
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.laf.darcula;
import com.intellij.openapi.wm.WelcomeScreen;
import com.intellij.openapi.wm.WelcomeScreenProvider;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaWelcomeScreenProvider implements WelcomeScreenProvider {
@Nullable
@Override
public WelcomeScreen createWelcomeScreen(JRootPane rootPane) {
return new DarculaIntelliJWelcomeScreen();
}
@Override
public boolean isAvailable() {
return false; // UIUtil.isUnderDarcula() && PlatformUtils.isIntelliJ();
}
}
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.laf.darcula;
import com.intellij.openapi.wm.WelcomeScreen;
import com.intellij.openapi.wm.WelcomeScreenProvider;
import com.intellij.util.PlatformUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaWelcomeScreenProvider implements WelcomeScreenProvider {
@Nullable
@Override
public WelcomeScreen createWelcomeScreen(JRootPane rootPane) {
return new DarculaIntelliJWelcomeScreen();
}
@Override
public boolean isAvailable() {
return UIUtil.isUnderDarcula() && PlatformUtils.isIntelliJ();
}
}
|
Use the right UiThreadTest annotation.
|
package com.jakewharton.rxbinding.view;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
@Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
private final Context context = InstrumentationRegistry.getTargetContext();
private final LinearLayout parent = new LinearLayout(context);
private final View child = new View(context);
@Test @UiThreadTest public void childViewEvents() {
RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
o.assertNoMoreEvents(); // No initial value.
parent.addView(child);
assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));
parent.removeView(child);
assertThat(o.takeNext()).isEqualTo(
ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));
subscription.unsubscribe();
parent.addView(child);
o.assertNoMoreEvents();
}
}
|
package com.jakewharton.rxbinding.view;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.UiThreadTest;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
@Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
private final Context context = InstrumentationRegistry.getTargetContext();
private final LinearLayout parent = new LinearLayout(context);
private final View child = new View(context);
@Test @UiThreadTest public void childViewEvents() {
RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
o.assertNoMoreEvents(); // No initial value.
parent.addView(child);
assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));
parent.removeView(child);
assertThat(o.takeNext()).isEqualTo(
ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));
subscription.unsubscribe();
parent.addView(child);
o.assertNoMoreEvents();
}
}
|
Correct javadoc to point to proper annotation.
|
package retrofit;
/** Intercept every request before it is executed in order to add additional data. */
public interface RequestInterceptor {
/** Called for every request. Add data using methods on the supplied {@link RequestFacade}. */
void intercept(RequestFacade request);
interface RequestFacade {
/** Add a header to the request. This will not replace any existing headers. */
void addHeader(String name, String value);
/**
* Add a path parameter replacement. This works exactly like a {@link retrofit.http.Path
* @Path}-annotated method argument.
*/
void addPathParam(String name, String value);
/** Add an additional query parameter. This will not replace any existing query parameters. */
void addQueryParam(String name, String value);
}
/** A {@link RequestInterceptor} which does no modification of requests. */
RequestInterceptor NONE = new RequestInterceptor() {
@Override public void intercept(RequestFacade request) {
// Do nothing.
}
};
}
|
package retrofit;
/** Intercept every request before it is executed in order to add additional data. */
public interface RequestInterceptor {
/** Called for every request. Add data using methods on the supplied {@link RequestFacade}. */
void intercept(RequestFacade request);
interface RequestFacade {
/** Add a header to the request. This will not replace any existing headers. */
void addHeader(String name, String value);
/**
* Add a path parameter replacement. This works exactly like a {@link retrofit.http.Part
* @Part}-annotated method argument.
*/
void addPathParam(String name, String value);
/** Add an additional query parameter. This will not replace any existing query parameters. */
void addQueryParam(String name, String value);
}
/** A {@link RequestInterceptor} which does no modification of requests. */
RequestInterceptor NONE = new RequestInterceptor() {
@Override public void intercept(RequestFacade request) {
// Do nothing.
}
};
}
|
Disable distribution of rank-expression files.
|
package com.yahoo.searchdefinition;
import com.yahoo.vespa.model.AbstractService;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class RankExpressionFiles {
private final Map<String, RankExpressionFile> expressions = new HashMap<>();
public void add(RankExpressionFile expression) {
expression.validate();
String name = expression.getName();
if (expressions.containsKey(name))
throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
expressions.put(name, expression);
}
/** Returns the ranking constant with the given name, or null if not present */
public RankExpressionFile get(String name) {
return expressions.get(name);
}
/** Returns a read-only map of the ranking constants in this indexed by name */
public Map<String, RankExpressionFile> asMap() {
return Collections.unmodifiableMap(expressions);
}
/** Initiate sending of these constants to some services over file distribution */
public void sendTo(Collection<? extends AbstractService> services) {
// TODO Disabled until issues resolved
// expressions.values().forEach(constant -> constant.sendTo(services));
}
}
|
package com.yahoo.searchdefinition;
import com.yahoo.vespa.model.AbstractService;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class RankExpressionFiles {
private final Map<String, RankExpressionFile> expressions = new HashMap<>();
public void add(RankExpressionFile expression) {
expression.validate();
String name = expression.getName();
if (expressions.containsKey(name))
throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
expressions.put(name, expression);
}
/** Returns the ranking constant with the given name, or null if not present */
public RankExpressionFile get(String name) {
return expressions.get(name);
}
/** Returns a read-only map of the ranking constants in this indexed by name */
public Map<String, RankExpressionFile> asMap() {
return Collections.unmodifiableMap(expressions);
}
/** Initiate sending of these constants to some services over file distribution */
public void sendTo(Collection<? extends AbstractService> services) {
expressions.values().forEach(constant -> constant.sendTo(services));
}
}
|
Remove pause from e2e tests
|
var db = require( '../../db' )
var chai = require( 'chai' )
chai.use( require( 'chai-as-promised' ) )
var expect = chai.expect
describe( 'making a post', function() {
it( 'creates an account and creates a new post', function() {
browser.get( 'http://localhost:3001' )
element( by.css( 'nav .register' ) ).click()
// fill out and submit login form
element( by.model( 'username' ) ).sendKeys( 'drift' )
element( by.model( 'password' ) ).sendKeys( 'pass' )
element( by.css( 'form .btn' ) ).click()
element( by.css( 'nav .posts' ) ).click()
// submit a new post on the posts page
var post = 'my test post' + Math.random()
element( by.model( 'postBody' ) ).sendKeys( post )
element( by.css( 'form .btn' ) ).click()
// check that new post appears on the page
expect( element.all( by.css( 'ul.posts li' ) ).first().getText() )
.to.eventually.contain( post )
})
afterEach( function() {
db.connection.db.dropDatabase()
})
})
|
var db = require( '../../db' )
var chai = require( 'chai' )
chai.use( require( 'chai-as-promised' ) )
var expect = chai.expect
describe( 'making a post', function() {
it( 'creates an account and creates a new post', function() {
browser.get( 'http://localhost:3001' )
element( by.css( 'nav .register' ) ).click()
// fill out and submit login form
element( by.model( 'username' ) ).sendKeys( 'drift' )
element( by.model( 'password' ) ).sendKeys( 'pass' )
element( by.css( 'form .btn' ) ).click()
element( by.css( 'nav .posts' ) ).click()
// submit a new post on the posts page
var post = 'my test post' + Math.random()
element( by.model( 'postBody' ) ).sendKeys( post )
element( by.css( 'form .btn' ) ).click()
browser.pause()
// check that new post appears on the page
expect( element.all( by.css( 'ul.posts li' ) ).first().getText() )
.to.eventually.contain( post )
})
afterEach( function() {
db.connection.db.dropDatabase()
})
})
|
Fix Notification is already in use error
|
<?php
namespace LaravelDoctrine\ORM\Notifications;
use Doctrine\Common\Persistence\ManagerRegistry;
use Illuminate\Notifications\Notification as LaravelNotification;
use LaravelDoctrine\ORM\Exceptions\NoEntityManagerFound;
class DoctrineChannel
{
/**
* @var ManagerRegistry
*/
private $registry;
/**
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
/**
* Send the given notification.
*
* @param mixed $notifiable
* @param LaravelNotification $notification
*/
public function send($notifiable, LaravelNotification $notification)
{
$entity = $notification->toEntity($notifiable);
if ($channel = $notifiable->routeNotificationFor('doctrine')) {
$em = $this->registry->getManager($channel);
} else {
$em = $this->registry->getManagerForClass(get_class($entity));
}
if (is_null($em)) {
throw new NoEntityManagerFound;
}
$em->persist($entity);
$em->flush();
}
}
|
<?php
namespace LaravelDoctrine\ORM\Notifications;
use Doctrine\Common\Persistence\ManagerRegistry;
use Illuminate\Notifications\Notification;
use LaravelDoctrine\ORM\Exceptions\NoEntityManagerFound;
class DoctrineChannel
{
/**
* @var ManagerRegistry
*/
private $registry;
/**
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
/**
* Send the given notification.
*
* @param mixed $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
$entity = $notification->toEntity($notifiable);
if ($channel = $notifiable->routeNotificationFor('doctrine')) {
$em = $this->registry->getManager($channel);
} else {
$em = $this->registry->getManagerForClass(get_class($entity));
}
if (is_null($em)) {
throw new NoEntityManagerFound;
}
$em->persist($entity);
$em->flush();
}
}
|
Fix the deprecated "base_path" in Grunt
|
module.exports = function (grunt) {
grunt.initConfig({
typescript: {
base: {
src: ['src/**/*.ts'],
dest: 'bin',
options: {
module: 'commonjs', //or commonjs
target: 'es5', //or es3
basePath: 'src',
sourcemap: false,
fullSourceMapPath: false,
declaration: false
}
}
},
copy: {
main: {
files: [
{
expand: true,
cwd: 'src/plugins',
src: ['**', '!**/*.ts'],
dest: 'bin/plugins/'
}
]
}
}
});
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-contrib-copy');
// Default task(s).
grunt.registerTask('default', ['typescript','copy']);
};
|
module.exports = function (grunt) {
grunt.initConfig({
typescript: {
base: {
src: ['src/**/*.ts'],
dest: 'bin',
options: {
module: 'commonjs', //or commonjs
target: 'es5', //or es3
base_path: 'src',
sourcemap: false,
fullSourceMapPath: false,
declaration: false
}
}
},
copy: {
main: {
files: [
{
expand: true,
cwd: 'src/plugins',
src: ['**', '!**/*.ts'],
dest: 'bin/plugins/'
}
]
}
}
});
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-contrib-copy');
// Default task(s).
grunt.registerTask('default', ['typescript','copy']);
};
|
Add String Constant for Recipe key in Bundle
|
package com.example.profbola.bakingtime.ui;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.profbola.bakingtime.R;
public class MainActivity extends AppCompatActivity {
public static final String RECIPE = "recipe";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
|
package com.example.profbola.bakingtime.ui;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.profbola.bakingtime.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
|
Update taxonomyUrl to machine readable XML endpoint
|
package no.geonorge.nedlasting.data;
import org.apache.cayenne.Cayenne;
import org.apache.cayenne.ObjectContext;
import no.geonorge.nedlasting.data.auto._Projection;
public class Projection extends _Projection {
public no.geonorge.nedlasting.data.client.Projection forClient() {
no.geonorge.nedlasting.data.client.Projection p = new no.geonorge.nedlasting.data.client.Projection();
p.setCode(getSrid().toString());
p.setCodespace(getCodespace());
p.setName(getName());
return p;
}
public String getAuthorityAndCode() {
return "EPSG:" + getSrid();
}
public String getScheme() {
return "https://register.geonorge.no/api/epsg-koder.xml";
}
public static Projection getForSrid(ObjectContext ctxt, int srid) {
return Cayenne.objectForPK(ctxt, Projection.class, srid);
}
}
|
package no.geonorge.nedlasting.data;
import org.apache.cayenne.Cayenne;
import org.apache.cayenne.ObjectContext;
import no.geonorge.nedlasting.data.auto._Projection;
public class Projection extends _Projection {
public no.geonorge.nedlasting.data.client.Projection forClient() {
no.geonorge.nedlasting.data.client.Projection p = new no.geonorge.nedlasting.data.client.Projection();
p.setCode(getSrid().toString());
p.setCodespace(getCodespace());
p.setName(getName());
return p;
}
public String getAuthorityAndCode() {
return "EPSG:" + getSrid();
}
public String getScheme() {
return "http://www.opengis.net/def/crs/";
}
public static Projection getForSrid(ObjectContext ctxt, int srid) {
return Cayenne.objectForPK(ctxt, Projection.class, srid);
}
}
|
Fix reverse since we deprecated post_object_list
|
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *args, **kwargs):
return {'title': _('Posts')}
def get_view_modifier(self, request, *args, **kwargs):
return DefaultViewModifier(request, *args, **kwargs)
def get_paginate_by(self, *args, **kwargs):
return 12
def get_queryset(self, *args, **kwargs):
return Post.permitted.all()
object_list = ObjectList()
class ObjectDetail(GenericObjectDetail):
def get_queryset(self, *args, **kwargs):
return Post.permitted.all()
def get_extra_context(self, *args, **kwargs):
return {'title': 'Posts'}
def get_view_modifier(self, request, *args, **kwargs):
return DefaultViewModifier(
request,
base_url=reverse("object_list", args=['post', 'post']),
ignore_defaults=True,
*args,
**kwargs
)
object_detail = ObjectDetail()
|
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *args, **kwargs):
return {'title': _('Posts')}
def get_view_modifier(self, request, *args, **kwargs):
return DefaultViewModifier(request, *args, **kwargs)
def get_paginate_by(self, *args, **kwargs):
return 12
def get_queryset(self, *args, **kwargs):
return Post.permitted.all()
object_list = ObjectList()
class ObjectDetail(GenericObjectDetail):
def get_queryset(self, *args, **kwargs):
return Post.permitted.all()
def get_extra_context(self, *args, **kwargs):
return {'title': 'Posts'}
def get_view_modifier(self, request, *args, **kwargs):
return DefaultViewModifier(
request,
base_url=reverse("post_object_list"),
ignore_defaults=True,
*args,
**kwargs
)
object_detail = ObjectDetail()
|
Update asset paths in production
|
var webpack = require("webpack");
/**
* This is the Webpack configuration file for production.
*/
module.exports = {
entry: "./src/main",
output: {
path: __dirname + "/build/",
filename: "app.js"
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader" },
{ test: /\.png$/, loader: "file-loader" },
{ test: /\.less$/, loader: "style!css!less" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
]
},
resolve: {
extensions: ["", ".js", ".jsx"]
}
}
|
var webpack = require("webpack");
/**
* This is the Webpack configuration file for production.
*/
module.exports = {
entry: "./src/main",
output: {
path: __dirname + "/build/",
publicPath: __dirname + "/build/",
filename: "app.js"
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader" },
{ test: /\.png$/, loader: "file-loader" },
{ test: /\.less$/, loader: "style!css!less" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
]
},
resolve: {
extensions: ["", ".js", ".jsx"]
}
}
|
Change the tagline for PyPI
|
from distutils.core import setup
setup(
name='jute',
packages=['jute'],
package_dir={'jute': 'python3/jute'},
version='0.1.0',
description='An interface module that verifies both providers and callers',
author='Jonathan Patrick Giddy',
author_email='jongiddy@gmail.com',
url='https://github.com/jongiddy/jute',
download_url='https://github.com/jongiddy/jute/tarball/v0.1.0',
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Natural Language :: English",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
from distutils.core import setup
setup(
name='jute',
packages=['jute'],
package_dir={'jute': 'python3/jute'},
version='0.1',
description='Yet another interface module for Python',
author='Jonathan Patrick Giddy',
author_email='jongiddy@gmail.com',
url='https://github.com/jongiddy/jute',
download_url='https://github.com/jongiddy/jute/tarball/0.1',
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Natural Language :: English",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Add more tests to the in() utility
|
package adeptus
import (
"testing"
)
func Test_in(t *testing.T) {
cases := []struct {
in string
slice []string
out bool
}{
{
in: "a",
slice: []string{},
out: false,
},
{
in: "a",
slice: []string{"b", "c"},
out: false,
},
{
in: "a",
slice: []string{"a", "b", "c"},
out: true,
},
{
in: "b",
slice: []string{"a", "b", "c"},
out: true,
},
{
in: "c",
slice: []string{"a", "b", "c"},
out: true,
},
{
in: "d",
slice: []string{"a", "b", "c"},
out: false,
},
}
for i, c := range cases {
out := in(c.in, c.slice)
if out != c.out {
t.Logf("Unexpected output on case %d:", i+1)
t.Logf("Expected %t", c.out)
t.Logf("Having %t", out)
t.Fail()
}
}
}
|
package adeptus
import (
"testing"
)
func Test_in(t *testing.T) {
cases := []struct {
in string
slice []string
out bool
}{
{
in: "",
slice: []string{},
out: false,
},
{
in: "a",
slice: []string{"b", "c"},
out: false,
},
{
in: "a",
slice: []string{"a", "b", "c"},
out: true,
},
}
for i, c := range cases {
out := in(c.in, c.slice)
if out != c.out {
t.Logf("Unexpected output on case %d:", i+1)
t.Logf("Expected %t", c.out)
t.Logf("Having %t", out)
t.Fail()
}
}
}
|
Add timestamp and client IP
|
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class ApiController {
/**
* @Route("/api/submit")
*/
public function submitAction(Request $request) {
$dataRaw = $request->request->get('data');
$clientIP = $request->getClientIp();
$currentDate = new \DateTime();
if ($dataRaw === NULL) {
exit("Error");
}
$storedData = json_decode($dataRaw, true);
$storedData['timestamp'] = $currentDate->format('d/m-Y H:i:s');
$storedData['clientIp'] = $clientIP;
$client = new \Elasticsearch\Client();
$params = array();
$params['body'] = $storedData;
$params['index'] = 'weather_station';
$params['type'] = 'weatherStationLog';
$client->index($params);
return new JsonResponse(array('status' => 'OK'));
}
/**
* @param int $limit
*/
public function readAction($limit = 100) {
$client = new \Elasticsearch\Client();
$searchParams['body']['query']['match']['testField'] = 'abc';
}
}
|
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class ApiController {
/**
* @Route("/api/submit")
*/
public function submitAction(Request $request) {
$dataRaw = $request->request->get('data');
if ($dataRaw === NULL) {
exit("Error");
}
$client = new \Elasticsearch\Client();
$params = array();
$params['body'] = json_decode($dataRaw);
$params['index'] = 'weather_station';
$params['type'] = 'weatherStationLog';
$ret = $client->index($params);
return new JsonResponse(array('status' => 'OK'));
}
/**
* @param int $limit
*/
public function readAction($limit = 100) {
$client = new \Elasticsearch\Client();
$searchParams['body']['query']['match']['testField'] = 'abc';
}
}
|
Fix bug: use type to construct log string
|
var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG: ';
}
this.util.log(type + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
|
var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG: ';
}
this.util.log(DEBUG + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
|
Fix require MySQL server on Ubuntu 12.04 LTS
|
"""
Idempotent API for managing MySQL users and databases
"""
from __future__ import with_statement
from fabtools.mysql import *
from fabtools.deb import is_installed, preseed_package
from fabtools.require.deb import package
from fabtools.require.service import started
def server(version=None, password=None):
"""
Require a MySQL server
"""
if version:
pkg_name = 'mysql-server-%s' % version
else:
pkg_name = 'mysql-server'
if not is_installed(pkg_name):
if password is None:
password = prompt_password()
with settings(hide('running')):
preseed_package('mysql-server', {
'mysql-server/root_password': ('password', password),
'mysql-server/root_password_again': ('password', password),
})
package(pkg_name)
started('mysql')
def user(name, password, **kwargs):
"""
Require a MySQL user
"""
if not user_exists(name, **kwargs):
create_user(name, password, **kwargs)
def database(name, **kwargs):
"""
Require a MySQL database
"""
if not database_exists(name, **kwargs):
create_database(name, **kwargs)
|
"""
Idempotent API for managing MySQL users and databases
"""
from __future__ import with_statement
from fabtools.mysql import *
from fabtools.deb import is_installed, preseed_package
from fabtools.require.deb import package
from fabtools.require.service import started
def server(version='5.1', password=None):
"""
Require a MySQL server
"""
if not is_installed("mysql-server-%s" % version):
if password is None:
password = prompt_password()
with settings(hide('running')):
preseed_package('mysql-server', {
'mysql-server/root_password': ('password', password),
'mysql-server/root_password_again': ('password', password),
})
package('mysql-server-%s' % version)
started('mysql')
def user(name, password, **kwargs):
"""
Require a MySQL user
"""
if not user_exists(name, **kwargs):
create_user(name, password, **kwargs)
def database(name, **kwargs):
"""
Require a MySQL database
"""
if not database_exists(name, **kwargs):
create_database(name, **kwargs)
|
Remove props param to get current mobilization selector
|
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
// Global module dependencies
import { SettingsPageLayout } from '../../../components/Layout'
// Parent module dependencies
import * as MobilizationSelectors from '../../mobilizations/selectors'
// Current module dependencies
import * as WidgetSelectors from '../selectors'
export const SettingsContainer = ({ children, ...rest }) => (
<SettingsPageLayout>
{children && React.cloneElement(children, {...rest})}
</SettingsPageLayout>
)
SettingsContainer.propTypes = {
children: PropTypes.object,
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
widgets: PropTypes.array.isRequired
}
const mapStateToProps = (state, props) => ({
mobilization: MobilizationSelectors.getCurrent(state),
widget: WidgetSelectors.getWidget(state, props),
widgets: WidgetSelectors.getList(state)
})
export default connect(mapStateToProps)(SettingsContainer)
|
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
// Global module dependencies
import { SettingsPageLayout } from '../../../components/Layout'
// Parent module dependencies
import * as MobilizationSelectors from '../../mobilizations/selectors'
// Current module dependencies
import * as WidgetSelectors from '../selectors'
export const SettingsContainer = ({ children, ...rest }) => (
<SettingsPageLayout>
{children && React.cloneElement(children, {...rest})}
</SettingsPageLayout>
)
SettingsContainer.propTypes = {
children: PropTypes.object,
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
widgets: PropTypes.array.isRequired
}
const mapStateToProps = (state, props) => ({
mobilization: MobilizationSelectors.getCurrent(state, props),
widget: WidgetSelectors.getWidget(state, props),
widgets: WidgetSelectors.getList(state)
})
export default connect(mapStateToProps)(SettingsContainer)
|
Set instances variables in auth before init
|
"""Base formgrade authenticator."""
from traitlets.config.configurable import LoggingConfigurable
class BaseAuth(LoggingConfigurable):
"""Base formgrade authenticator."""
def __init__(self, ip, port, base_directory, **kwargs):
self._ip = ip
self._port = port
self._base_url = ''
self._base_directory = base_directory
super(BaseAuth, self).__init__(**kwargs)
@property
def base_url(self):
return self._base_url
@property
def login_url(self):
return ''
def get_user(self, handler):
return 'nbgrader'
def authenticate(self, user):
"""Authenticate a user."""
return user
def notebook_server_exists(self):
"""Checks for a notebook server."""
return False
def get_notebook_server_cookie(self):
"""Gets a cookie that is needed to access the notebook server."""
return None
def get_notebook_url(self, relative_path):
"""Gets the notebook's url."""
raise NotImplementedError
def transform_handler(self, handler):
return handler
def stop(self):
"""Stops the notebook server."""
pass
|
"""Base formgrade authenticator."""
from traitlets.config.configurable import LoggingConfigurable
class BaseAuth(LoggingConfigurable):
"""Base formgrade authenticator."""
def __init__(self, ip, port, base_directory, **kwargs):
super(BaseAuth, self).__init__(**kwargs)
self._ip = ip
self._port = port
self._base_url = ''
self._base_directory = base_directory
@property
def base_url(self):
return self._base_url
@property
def login_url(self):
return ''
def get_user(self, handler):
return 'nbgrader'
def authenticate(self, user):
"""Authenticate a user."""
return user
def notebook_server_exists(self):
"""Checks for a notebook server."""
return False
def get_notebook_server_cookie(self):
"""Gets a cookie that is needed to access the notebook server."""
return None
def get_notebook_url(self, relative_path):
"""Gets the notebook's url."""
raise NotImplementedError
def transform_handler(self, handler):
return handler
def stop(self):
"""Stops the notebook server."""
pass
|
Remove python decorators from list
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
Use filterEvent for filtering events
|
define([
'jquery',
'DoughBaseComponent',
'InsertManager',
'eventsWithPromises',
'filter-event'
], function (
$,
DoughBaseComponent,
InsertManager,
eventsWithPromises,
filterEvent
) {
'use strict';
var LinkManagerProto,
defaultConfig = {
selectors: {
}
};
function LinkManager($el, config, customConfig) {
LinkManager.baseConstructor.call(this, $el, config, customConfig || defaultConfig);
this.open = false;
this.itemValues = {
'page': null,
'file': null,
'external': null
};
}
DoughBaseComponent.extend(LinkManager, InsertManager);
LinkManagerProto = LinkManager.prototype;
LinkManagerProto.init = function(initialised) {
LinkManager.superclass.init.call(this);
this._initialisedSuccess(initialised);
};
LinkManagerProto._setupAppEvents = function() {
eventsWithPromises.subscribe('cmseditor:insert-published', filterEvent($.proxy(this._handleShown, this), this.context));
LinkManager.superclass._setupAppEvents.call(this);
};
return LinkManager;
});
|
define([
'jquery',
'DoughBaseComponent',
'InsertManager',
'eventsWithPromises'
], function (
$,
DoughBaseComponent,
InsertManager,
eventsWithPromises
) {
'use strict';
var LinkManagerProto,
defaultConfig = {
selectors: {
}
};
function LinkManager($el, config, customConfig) {
LinkManager.baseConstructor.call(this, $el, config, customConfig || defaultConfig);
this.open = false;
this.itemValues = {
'page': null,
'file': null,
'external': null
};
}
DoughBaseComponent.extend(LinkManager, InsertManager);
LinkManagerProto = LinkManager.prototype;
LinkManagerProto.init = function(initialised) {
LinkManager.superclass.init.call(this);
this._initialisedSuccess(initialised);
};
LinkManagerProto._setupAppEvents = function() {
eventsWithPromises.subscribe('cmseditor:insert-published', $.proxy(this._handleShown, this));
LinkManager.superclass._setupAppEvents.call(this);
}
return LinkManager;
});
|
Resolve commit about local time
|
/**
* Parse task and return task info if
* the task is valid, otherwise throw
* error.
* @param {string} query Enetered task
* @return {object} Task info containing
* task text, start time
* and dealine
*/
function parse(query) {
/**
* Day, week or month coefficient
* @type {Object}
*/
const dwm = {
d: 1,
'': 1,
w: 7,
m: 30,
};
const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/;
const regexResult = regex.exec(query);
const text = query.slice(0, regexResult.index);
let start = Date.now() - ((Date.now() % 86400000) - (new Date().getTimezoneOffset() * 60000));
if (regexResult[3]) {
start += 86400000 * regexResult[4] * dwm[regexResult[5]];
}
const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]);
const importance = regexResult[6].length + 1;
const status = 0;
return {
text: text.trim(),
start,
end,
importance,
status,
};
}
module.exports = parse;
|
/**
* Parse task and return task info if
* the task is valid, otherwise throw
* error.
* @param {string} query Enetered task
* @return {object} Task info containing
* task text, start time
* and dealine
*/
function parse(query) {
/**
* Day, week or month coefficient
* @type {Object}
*/
const dwm = {
d: 1,
'': 1,
w: 7,
m: 30,
};
const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/;
const regexResult = regex.exec(query);
const text = query.slice(0, regexResult.index);
let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000));
if (regexResult[3]) {
start += 86400000 * regexResult[4] * dwm[regexResult[5]];
}
const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]);
const importance = regexResult[6].length + 1;
const status = 0;
return {
text: text.trim(),
start,
end,
importance,
status,
};
}
module.exports = parse;
|
Check Foo.class.isInstance instead of Object.class.isInstance.
See
https://github.com/jspecify/jspecify/issues/164#issuecomment-775868055
I'm going to remove this sample entirely, but I'm first improving it in
this commit: If someone wants to keep a local copy, we might as well
make it as useful as we can.
|
/*
* Copyright 2020 The JSpecify Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;
@DefaultNonNull
class InstanceOfMethodCheck {
Object x0(Object o) {
if (Foo.class.isInstance(o)) {
return o;
} else {
return o;
}
}
Object x1(@NullnessUnspecified Object o) {
if (Foo.class.isInstance(o)) {
return o;
} else {
// jspecify_nullness_not_enough_information
return o;
}
}
Object x2(@Nullable Object o) {
if (Foo.class.isInstance(o)) {
return o;
} else {
// jspecify_nullness_mismatch
return o;
}
}
class Foo {}
}
|
/*
* Copyright 2020 The JSpecify Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;
@DefaultNonNull
class InstanceOfMethodCheck {
Object x0(Object o) {
if (Object.class.isInstance(o)) {
return o;
} else {
return o;
}
}
Object x1(@NullnessUnspecified Object o) {
if (Object.class.isInstance(o)) {
return o;
} else {
// jspecify_nullness_not_enough_information
return o;
}
}
Object x2(@Nullable Object o) {
if (Object.class.isInstance(o)) {
return o;
} else {
// jspecify_nullness_mismatch
return o;
}
}
}
|
Make that public so it is actually useable.
|
/*
* LapisCommons
* Copyright (c) 2014, LapisDev <https://github.com/LapisDev>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package blue.lapis.common.permission;
public interface Permission {
String getPermissionPath();
PermissionLevel getTrustLevel();
// todo: or String[] ?
String getSourcePlugin();
String getDescription();
}
|
/*
* LapisCommons
* Copyright (c) 2014, LapisDev <https://github.com/LapisDev>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package blue.lapis.common.permission;
interface Permission {
String getPermissionPath();
PermissionLevel getTrustLevel();
// todo: or String[] ?
String getSourcePlugin();
String getDescription();
}
|
:lipstick: Set proper config for inherited repo
|
<?php
namespace Harp\Core\Test\Repo;
use Harp\Core\Test\Model;
use Harp\Core\Test\Rel;
/**
* @author Ivan Kerin
* @copyright (c) 2014 Clippings Ltd.
* @license http://www.opensource.org/licenses/isc-license.txt
*/
class BlogPost extends Post {
public static function newInstance()
{
return new BlogPost('Harp\Core\Test\Model\BlogPost', 'Post.json');
}
public function initialize()
{
parent::initialize();
$this
->setRootRepo(Post::get())
->addRels([
new Rel\One('address', $this, Address::get()),
]);
}
}
|
<?php
namespace Harp\Core\Test\Repo;
use Harp\Core\Test\Model;
use Harp\Core\Test\Rel;
/**
* @author Ivan Kerin
* @copyright (c) 2014 Clippings Ltd.
* @license http://www.opensource.org/licenses/isc-license.txt
*/
class BlogPost extends Post {
public static function newInstance()
{
return new BlogPost('Harp\Core\Test\Model\BlogPost', 'Post.json');
}
public function initialize()
{
parent::initialize();
$this
->addRels([
new Rel\One('address', $this, Address::get()),
]);
}
}
|
Remove list of project names from slack announcement for cycle launch.
|
import Promise from 'bluebird'
import {Cycle, Phase, Project} from 'src/server/services/dataService'
export default async function sendCycleLaunchAnnouncements(cycleId) {
const [cycle, phases] = await Promise.all([
await Cycle.get(cycleId),
await Phase.filter({hasVoting: true}),
])
await Promise.each(phases, phase => _sendAnnouncementToPhase(cycle, phase))
}
async function _sendAnnouncementToPhase(cycle, phase) {
const chatService = require('src/server/services/chatService')
const numOfProjects = await Project.filter({cycleId: cycle.id, phaseId: phase.id}).count()
try {
await chatService.sendChannelMessage(phase.channelName, _buildAnnouncement(cycle, numOfProjects))
} catch (err) {
console.warn(`Failed to send cycle launch announcement to Phase ${phase.number} for cycle ${cycle.cycleNumber}: ${err}`)
}
}
function _buildAnnouncement(cycle, numOfProjects) {
let announcement = `🚀 *Cycle ${cycle.cycleNumber} has been launched!*\n`
if (numOfProjects > 0) {
announcement += `>${numOfProjects} projects were created.\n`
} else {
announcement += '>No projects created'
}
return announcement
}
|
import Promise from 'bluebird'
import {Cycle, Phase, Project} from 'src/server/services/dataService'
export default async function sendCycleLaunchAnnouncements(cycleId) {
const [cycle, phases] = await Promise.all([
await Cycle.get(cycleId),
await Phase.filter({hasVoting: true}),
])
await Promise.each(phases, phase => _sendAnnouncementToPhase(cycle, phase))
}
async function _sendAnnouncementToPhase(cycle, phase) {
const chatService = require('src/server/services/chatService')
const projects = await Project.filter({cycleId: cycle.id, phaseId: phase.id}).pluck('name', 'goal')
try {
await chatService.sendChannelMessage(phase.channelName, _buildAnnouncement(cycle, projects))
} catch (err) {
console.warn(`Failed to send cycle launch announcement to Phase ${phase.number} for cycle ${cycle.cycleNumber}: ${err}`)
}
}
function _buildAnnouncement(cycle, projects) {
let announcement = `🚀 *Cycle ${cycle.cycleNumber} has been launched!*\n`
if (projects.length > 0) {
const projectListString = projects.map(p => ` • #${p.name} - _${p.goal.title}_`).join('\n')
announcement += `>The following projects have been created:\n${projectListString}`
} else {
announcement += '>No projects created'
}
return announcement
}
|
Add comma to the last element of the array
|
<?php
namespace Moxio\Sniffs\Tests\PHP;
use Moxio\Sniffs\PHP\DisallowImplicitLooseComparisonSniff;
use Moxio\Sniffs\Tests\AbstractSniffTest;
class DisallowImplicitLooseComparisonSniffTest extends AbstractSniffTest
{
protected function getSniffClass()
{
return DisallowImplicitLooseComparisonSniff::class;
}
public function testSniff()
{
$file = __DIR__ . '/DisallowImplicitLooseComparisonSniffTest.inc';
$this->assertFileHasErrorsOnLines($file, [
2,
3,
4,
14,
17,
20,
]);
}
}
|
<?php
namespace Moxio\Sniffs\Tests\PHP;
use Moxio\Sniffs\PHP\DisallowImplicitLooseComparisonSniff;
use Moxio\Sniffs\Tests\AbstractSniffTest;
class DisallowImplicitLooseComparisonSniffTest extends AbstractSniffTest
{
protected function getSniffClass()
{
return DisallowImplicitLooseComparisonSniff::class;
}
public function testSniff()
{
$file = __DIR__ . '/DisallowImplicitLooseComparisonSniffTest.inc';
$this->assertFileHasErrorsOnLines($file, [
2,
3,
4,
14,
17,
20
]);
}
}
|
Configure headers through a constructor
|
<?php
namespace hiapi\Core\Http\Psr15\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CorsMiddleware implements MiddlewareInterface
{
protected $headers = [
'Access-Control-Allow-Origin' => ['*'],
'Access-Control-Request-Method' => ['GET POST'],
];
public function addHeader($name, $value): self
{
$this->headers[$name] = array_merge($this->headers[$name] ?? [], [$value]);
return $this;
}
public function __construct(array $headers = [])
{
foreach ($headers as $name => $value) {
$this->addHeader($name, $value);
}
}
/**
* @inheritDoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
return $this->addHeaders($response);
}
private function addHeaders(ResponseInterface $response)
{
foreach ($this->headers as $name => $headers) {
$response = $response->withHeader($name, $headers);
}
return $response;
}
}
|
<?php
namespace hiapi\Core\Http\Psr15\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CorsMiddleware implements MiddlewareInterface
{
protected $headers = [
'Access-Control-Allow-Origin' => ['*'],
'Access-Control-Request-Method' => ['GET POST'],
];
public function addHeader($name, $value): self
{
$this->headers[$name] = array_merge($this->headers[$name] ?? [], [$value]);
return $this;
}
/**
* @inheritDoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
return $this->addHeaders($response);
}
private function addHeaders(ResponseInterface $response)
{
foreach ($this->headers as $name => $headers) {
$response = $response->withHeader($name, $headers);
}
return $response;
}
}
|
Add a comment explaining why the filter cache doesn't need exipiring
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import BaseSlavedStore
from synapse.storage.filtering import FilteringStore
class SlavedFilteringStore(BaseSlavedStore):
def __init__(self, db_conn, hs):
super(SlavedFilteringStore, self).__init__(db_conn, hs)
# Filters are immutable so this cache doesn't need to be expired
get_user_filter = FilteringStore.__dict__["get_user_filter"]
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import BaseSlavedStore
from synapse.storage.filtering import FilteringStore
class SlavedFilteringStore(BaseSlavedStore):
def __init__(self, db_conn, hs):
super(SlavedFilteringStore, self).__init__(db_conn, hs)
get_user_filter = FilteringStore.__dict__["get_user_filter"]
|
Print stacktrace when Biwa crashes in node.js.
|
var sys = require('sys'),
fs = require('fs'),
path = require('path'),
optparse = require('optparse');
function Options(argv){
var switches = [
[ '--encoding', 'Specify encoding (default: utf8)'],
['-h', '--help', 'Shows help sections']
];
var parser = new optparse.OptionParser(switches);
parser.on('help', function() {
sys.puts('Help');
});
this.args = parser.parse(argv);
}
var opts = new Options(process.argv.slice(2));
var intp = new BiwaScheme.Interpreter(function(e){
sys.puts(e.stack);
process.exit(1);
});
if(opts.args.size() >= 1){
var src = fs.readFileSync(opts.args[0], 'utf8');
intp.evaluate(src);
}
else{
// TODO repl
//sys.print("biwas > ");
}
|
var sys = require('sys'),
fs = require('fs'),
path = require('path'),
optparse = require('optparse');
function Options(argv){
var switches = [
[ '--encoding', 'Specify encoding (default: utf8)'],
['-h', '--help', 'Shows help sections']
];
var parser = new optparse.OptionParser(switches);
parser.on('help', function() {
sys.puts('Help');
});
this.args = parser.parse(argv);
}
var opts = new Options(process.argv.slice(2));
var intp = new BiwaScheme.Interpreter(function(e){
sys.puts(Object.inspect(e));
process.exit(1);
});
if(opts.args.size() >= 1){
var src = fs.readFileSync(opts.args[0], 'utf8');
intp.evaluate(src);
}
else{
// TODO repl
//sys.print("biwas > ");
}
|
Drop use of spread operator (not supported in Safari/Edge yet).
|
export default function ClickSelectionMixin(Base) {
return class ClickSelection extends Base {
constructor(props) {
super(props);
this.click = this.click.bind(this);
}
click(event) {
// REVIEW: is this the best way to reliably map the event target to a
// child?
const parent = event.target.parentNode;
const targetIndex = [].indexOf.call(parent.children, event.target);
if (targetIndex >= 0) {
this.setState((prevState, props) => {
return {
selectedIndex: targetIndex
}
});
}
}
listProps() {
const base = super.listProps ? super.listProps() : {};
return Object.assign({}, base, {
onClick: this.click
});
}
}
}
|
export default function ClickSelectionMixin(Base) {
return class ClickSelection extends Base {
constructor(props) {
super(props);
this.click = this.click.bind(this);
}
click(event) {
// REVIEW: is this the best way to reliably map the event target to a
// child?
const parent = event.target.parentNode;
const targetIndex = [...parent.children].indexOf(event.target);
if (targetIndex >= 0) {
this.setState((prevState, props) => {
return {
selectedIndex: targetIndex
}
});
}
}
listProps() {
const base = super.listProps ? super.listProps() : {};
return Object.assign({}, base, {
onClick: this.click
});
}
}
}
|
Fix bug in media player keys ubuntu
|
import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
});
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
}
});
} catch (e) {
// do nothing.
}
|
import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
});
}
});
} catch (e) {
// do nothing.
}
|
Remove obsolete list resources functions
|
package com.woorea.openstack.heat;
import com.woorea.openstack.base.client.HttpMethod;
import com.woorea.openstack.base.client.OpenStackClient;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.heat.model.Resources;
/**
* v1/{tenant_id}/stacks/{stack_name}/resources
*/
public class ResourcesResource {
private final OpenStackClient client;
public ResourcesResource(OpenStackClient client) {
this.client = client;
}
public ListResources listResources(String name) {
return new ListResources(name);
}
/**
* v1/{tenant_id}/stacks/{stack_name}/resources
*/
public class ListResources extends OpenStackRequest<Resources> {
public ListResources(String name) {
super(client, HttpMethod.GET, "/stacks/" + name + "/resources", null, Resources.class);
}
}
}
|
package com.woorea.openstack.heat;
import com.woorea.openstack.base.client.HttpMethod;
import com.woorea.openstack.base.client.OpenStackClient;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.heat.model.Resources;
/**
* v1/{tenant_id}/stacks/{stack_name}/resources
*/
public class ResourcesResource {
private final OpenStackClient client;
public ResourcesResource(OpenStackClient client) {
this.client = client;
}
public ListResources listResources(String name) {
return new ListResources(name);
}
public List list(String name) {
return new List(name);
}
/**
* v1/{tenant_id}/stacks/{stack_name}/resources
*/
public class ListResources extends OpenStackRequest<Resources> {
public ListResources(String name) {
super(client, HttpMethod.GET, "/stacks/" + name + "/resources", null, Resources.class);
}
}
/**
* v1/{tenant_id}/stacks/{stack_name}/{stack_id}/resources
*/
public class List extends OpenStackRequest<String> {
public List(String name) {
super(client, HttpMethod.GET, "", null, String.class);
}
}
}
|
Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
|
# SpatialDB scons tool
#
# It builds the library for the SpatialDB C++ class library,
# and provides CPP and linker specifications for the header
# and libraries.
#
# SpatialDB depends on SqliteDB, which provides the interface to
# sqlite3. It also depends on SpatiaLite. Since SpatiaLite is
# is also needed by SQLiteDB, we let the sqlitedb tool provide
# the required SpatiaLite plumbing.
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
|
# SpatialDB scons tool
#
# It builds the library for the SpatialDB C++ class library,
# and provides CPP and linker specifications for the header
# and libraries.
#
# SpatialDB depends on SqliteDB, which provides the interface to
# sqlite3. It also depends on SpatiaLite. Since SpatiaLite is
# is also needed by SQLiteDB, we let the sqlitedb tool provide
# the required SpatiaLite plumbing.
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Replace(CCFLAGS=['-g','-O2'])
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
|
Allow str type comparison in py2/3
|
""" Test utilities for ensuring the correctness of products
"""
import arrow
import six
from tilezilla.core import BoundingBox, Band
MAPPING = {
'timeseries_id': six.string_types,
'acquired': arrow.Arrow,
'processed': arrow.Arrow,
'platform': six.string_types,
'instrument': six.string_types,
'bounds': BoundingBox,
'bands': [Band],
'metadata': dict,
'metadata_files': dict
}
def check_attributes(product):
for attr, _type in six.iteritems(MAPPING):
assert hasattr(product, attr)
value = getattr(product, attr)
if isinstance(_type, (type, tuple)):
# Type declaration one or more types
assert isinstance(value, _type)
else:
# Type declaration list of types
assert isinstance(value, type(_type))
for item in value:
assert isinstance(item, tuple(_type))
|
""" Test utilities for ensuring the correctness of products
"""
import arrow
import six
from tilezilla.core import BoundingBox, Band
MAPPING = {
'timeseries_id': str,
'acquired': arrow.Arrow,
'processed': arrow.Arrow,
'platform': str,
'instrument': str,
'bounds': BoundingBox,
'bands': [Band],
'metadata': dict,
'metadata_files': dict
}
def check_attributes(product):
for attr, _type in six.iteritems(MAPPING):
assert hasattr(product, attr)
value = getattr(product, attr)
if isinstance(_type, type):
assert isinstance(value, _type)
else:
assert isinstance(value, type(_type))
for item in value:
assert isinstance(item, tuple(_type))
|
Revert changes to client masking
|
import superagent from 'superagent';
import config from '../config';
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__) {
// Prepend host and port of the API server to the path.
return 'http://localhost:' + config.apiPort + adjustedPath;
}
// Prepend `/api` to relative URL, to proxy to API server.
return '/api' + adjustedPath;
}
/*
* This silly underscore is here to avoid a mysterious "ReferenceError: ApiClient is not defined" error.
* See Issue #14. https://github.com/erikras/react-redux-universal-hot-example/issues/14
*
* Remove it at your own risk.
*/
class _ApiClient {
constructor(req) {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
if (__SERVER__ && req.get('cookie')) {
request.set('cookie', req.get('cookie'));
}
if (data) {
request.send(data);
}
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
}
const ApiClient = _ApiClient;
export default ApiClient;
|
import superagent from 'superagent';
import config from '../config';
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__) {
// Prepend host and port of the API server to the path.
return 'http://localhost:' + config.apiPort + adjustedPath;
}
// Prepend `/api` to relative URL, to proxy to API server.
return '/api' + adjustedPath;
}
export default class ApiClient {
constructor(req) {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
if (__SERVER__ && req.get('cookie')) {
request.set('cookie', req.get('cookie'));
}
if (data) {
request.send(data);
}
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
}
|
Fix line lenght in manifest
|
# coding: utf-8
# @ 2016 florian DA COSTA @ Akretion
# © 2016 @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),'
'ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
|
# coding: utf-8
# @ 2016 florian DA COSTA @ Akretion
# © 2016 @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'External File Location',
'version': '10.0.1.0.0',
'author': 'Akretion,Odoo Community Association (OCA),ThinkOpen Solutions Brasil',
'website': 'http://www.akretion.com/',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': [
'attachment_base_synchronize',
],
'external_dependencies': {
'python': [
'fs',
'paramiko',
],
},
'data': [
'views/menu.xml',
'views/attachment_view.xml',
'views/location_view.xml',
'views/task_view.xml',
'data/cron.xml',
'security/ir.model.access.csv',
],
'demo': [
'demo/task_demo.xml',
],
'installable': True,
'application': False,
}
|
Set empty array on object transformer
|
<?php
namespace Opifer\EavBundle\Form\Transformer;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataTransformerInterface;
class CollectionToObjectTransformer implements DataTransformerInterface
{
/**
* Transforms an ArrayCollection Object to a single Object.
*
* @param \Doctrine\ORM\PersistentCollection $values
*
* @return Object
*/
public function transform($values)
{
if (null === $values || !($values instanceof Collection)) {
return null;
}
return $values->first();
}
/**
* Transforms a single Object to an ArrayCollection
*
* @param Object $value
*
* @return ArrayCollection
*/
public function reverseTransform($value)
{
if ($value instanceof Collection) {
return $value;
}
$collection = new ArrayCollection();
if(null !== $value) {
$collection->add($value);
}
return $collection;
}
}
|
<?php
namespace Opifer\EavBundle\Form\Transformer;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataTransformerInterface;
class CollectionToObjectTransformer implements DataTransformerInterface
{
/**
* Transforms an ArrayCollection Object to a single Object.
*
* @param \Doctrine\ORM\PersistentCollection $values
*
* @return Object
*/
public function transform($values)
{
if (null === $values || !($values instanceof Collection)) {
return null;
}
return $values->first();
}
/**
* Transforms a single Object to an ArrayCollection
*
* @param Object $value
*
* @return ArrayCollection
*/
public function reverseTransform($value)
{
if ($value instanceof Collection) {
return $value;
}
$collection = new ArrayCollection();
$collection->add($value);
return $collection;
}
}
|
Remove export of nonexisting class
|
// !!
// This module defines ProseMirror's document model, the data
// structure used to define and inspect content documents. It
// includes:
//
// * The [node](#Node) type that represents document elements
//
// * The [schema](#Schema) types used to tag and constrain the
// document structure
//
// This module does not depend on the browser API being available
// (i.e. you can load it into any JavaScript environment).
export {Node} from "./node"
export {ResolvedPos} from "./resolvedpos"
export {Fragment} from "./fragment"
export {Slice, ReplaceError} from "./replace"
export {Mark} from "./mark"
export {SchemaSpec, Schema, SchemaError,
NodeType, Block, Textblock, Inline, Text,
MarkType, Attribute, NodeKind} from "./schema"
export {defaultSchema, Doc, BlockQuote, OrderedList, BulletList, ListItem,
HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak,
CodeMark, EmMark, StrongMark, LinkMark} from "./defaultschema"
export {findDiffStart, findDiffEnd} from "./diff"
export {ModelError} from "./error"
|
// !!
// This module defines ProseMirror's document model, the data
// structure used to define and inspect content documents. It
// includes:
//
// * The [node](#Node) type that represents document elements
//
// * The [schema](#Schema) types used to tag and constrain the
// document structure
//
// This module does not depend on the browser API being available
// (i.e. you can load it into any JavaScript environment).
export {Node, PosContext} from "./node"
export {ResolvedPos} from "./resolvedpos"
export {Fragment} from "./fragment"
export {Slice, ReplaceError} from "./replace"
export {Mark} from "./mark"
export {SchemaSpec, Schema, SchemaError,
NodeType, Block, Textblock, Inline, Text,
MarkType, Attribute, NodeKind} from "./schema"
export {defaultSchema, Doc, BlockQuote, OrderedList, BulletList, ListItem,
HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak,
CodeMark, EmMark, StrongMark, LinkMark} from "./defaultschema"
export {findDiffStart, findDiffEnd} from "./diff"
export {ModelError} from "./error"
|
Add long description and bump version number
|
# -*- coding: utf-8 -*-
from setuptools import setup
VERSION = '0.1.3'
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='tree_extractor',
version=VERSION,
description="Lib to extract html elements by preserving ancestors and cleaning CSS",
long_description=long_description,
author=u'Jurismarchés',
author_email='contact@jurismarches.com',
url='https://github.com/jurismarches/tree_extractor',
packages=[
'tree_extractor'
],
install_requires=[
'cssselect==0.9.1',
'tinycss==0.3',
'lxml==3.3.5'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python :: 3.4',
],
test_suite='tree_extractor.tests'
)
|
# -*- coding: utf-8 -*-
from setuptools import setup
VERSION = '0.1.2'
setup(
name='tree_extractor',
version=VERSION,
description="Lib to extract html elements by preserving ancestors and cleaning CSS",
author=u'Jurismarchés',
author_email='contact@jurismarches.com',
url='https://github.com/jurismarches/tree_extractor',
packages=[
'tree_extractor'
],
install_requires=[
'cssselect==0.9.1',
'tinycss==0.3',
'lxml==3.3.5'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python :: 3.4',
],
test_suite='tree_extractor.tests'
)
|
Switch the format ES6 back to ES5 to make it compatible with IE11
|
'use strict';
var PinyinHelper = require('./lib/PinyinHelper');
var ChineseHelper = require('./lib/ChineseHelper');
var PinyinFormat = require('./lib/PinyinHelper');
var pinyin4js = {
WITH_TONE_MARK :"WITH_TONE_MARK", //带声调
WITHOUT_TONE :"WITHOUT_TONE", //不带声调
WITH_TONE_NUMBER :"WITH_TONE_NUMBER", //数字代表声调
FIRST_LETTER :"FIRST_LETTER", //首字母风格
convertToPinyinString: function(str, separator, format) {
return PinyinHelper.PinyinHelper.convertToPinyinString(str, separator, format);
},
convertToSimplifiedChinese: function(str) {
return ChineseHelper.ChineseHelper.convertToSimplifiedChinese(str);
},
convertToTraditionalChinese: function(str) {
return ChineseHelper.ChineseHelper.convertToTraditionalChinese(str);
},
getShortPinyin: function(str) {
return PinyinHelper.PinyinHelper.getShortPinyin(str);
}
}
;(function(){
global.PinyinHelper = PinyinHelper.PinyinHelper;
global.ChineseHelper = ChineseHelper.ChineseHelper;
global.PinyinFormat = PinyinFormat.PinyinFormat;
})();
module.exports = pinyin4js
|
'use strict';
var PinyinHelper = require('./lib/PinyinHelper');
var ChineseHelper = require('./lib/ChineseHelper');
var PinyinFormat = require('./lib/PinyinHelper');
var pinyin4js = {
WITH_TONE_MARK :"WITH_TONE_MARK", //带声调
WITHOUT_TONE :"WITHOUT_TONE", //不带声调
WITH_TONE_NUMBER :"WITH_TONE_NUMBER", //数字代表声调
FIRST_LETTER :"FIRST_LETTER", //首字母风格
convertToPinyinString(str, separator, format) {
return PinyinHelper.PinyinHelper.convertToPinyinString(str, separator, format)
},
convertToSimplifiedChinese(str) {
return ChineseHelper.ChineseHelper.convertToSimplifiedChinese(str)
},
convertToTraditionalChinese(str) {
return ChineseHelper.ChineseHelper.convertToTraditionalChinese(str)
},
getShortPinyin(str) {
return PinyinHelper.PinyinHelper.getShortPinyin(str)
}
}
;(function(){
global.PinyinHelper = PinyinHelper.PinyinHelper;
global.ChineseHelper = ChineseHelper.ChineseHelper;
global.PinyinFormat = PinyinFormat.PinyinFormat;
})();
module.exports = pinyin4js
|
[AdminBundle] Test console exception subscriber without instantiating a specific command
|
<?php
namespace Kunstmaan\AdminBundle\Tests\EventListener;
use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionSubscriberTest extends TestCase
{
public function testListener()
{
// Remove when sf3.4 support is removed
if (!class_exists(ConsoleErrorEvent::class)) {
// Nothing to test
return;
}
$error = new \TypeError('An error occurred');
$output = $this->createMock(OutputInterface::class);
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('critical');
$subscriber = new ConsoleExceptionSubscriber($logger);
$subscriber->onConsoleError(new ConsoleErrorEvent(new ArgvInput(['console.php', 'test:run', '--foo=baz', 'buzz']), $output, $error, new Command('test:run')));
}
}
|
<?php
namespace Kunstmaan\AdminBundle\Tests\EventListener;
use Kunstmaan\AdminBundle\Command\ApplyAclCommand;
use Kunstmaan\AdminBundle\EventListener\ConsoleExceptionSubscriber;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleExceptionSubscriberTest extends TestCase
{
public function testListener()
{
if (!class_exists(ConsoleErrorEvent::class)) {
// Nothing to test
return;
}
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('critical')->willReturn(true);
$subscriber = new ConsoleExceptionSubscriber($logger);
$command = new ApplyAclCommand();
$exception = new \Exception();
$input = $this->createMock(InputInterface::class);
$output = $this->createMock(OutputInterface::class);
$event = new ConsoleErrorEvent($input, $output, $exception, $command);
$subscriber->onConsoleError($event);
}
}
|
Fix eslint checking lib directory
|
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended'],
env: {
node: true,
},
rules: {
'arrow-parens': 'error',
'func-names': 'off',
'id-length': ['error', { exceptions: ['i', 'j', 'e', 'a', 'b', 't'] }],
'import/prefer-default-export': 'off',
'prefer-arrow-callback': 'error',
'quote-props': ['error', 'as-needed'],
'space-before-function-paren': ['error', 'never'],
},
plugins: ['prettier'],
overrides: [
{
files: ['src/**/*.ts', 'test/**/*.ts'],
plugins: ['@typescript-eslint'],
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.test.json',
},
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:prettier/recommended',
'prettier',
],
},
{
files: ['*.js'],
extends: ['plugin:prettier/recommended', 'prettier'],
},
],
};
|
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended'],
env: {
node: true,
},
rules: {
'arrow-parens': 'error',
'func-names': 'off',
'id-length': ['error', { exceptions: ['i', 'j', 'e', 'a', 'b', 't'] }],
'import/prefer-default-export': 'off',
'prefer-arrow-callback': 'error',
'quote-props': ['error', 'as-needed'],
'space-before-function-paren': ['error', 'never'],
},
plugins: ['prettier'],
overrides: [
{
files: ['**/*.ts'],
plugins: ['@typescript-eslint'],
parserOptions: {
tsconfigRootDir: __dirname,
project: './tsconfig.test.json',
},
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:prettier/recommended',
'prettier',
],
},
{
files: ['**/*.js'],
extends: ['plugin:prettier/recommended', 'prettier'],
},
],
};
|
Fix after upgrade node v7
|
'use strict';
var restify = require('restify');
var js2xmlparser = require('js2xmlparser');
var server = restify.createServer({
formatters: {
'application/json; q=5': function format(req, res, body) {
res.setHeader('Content-type', 'application/hal+json');
res.send(JSON.stringify(body));
},
'application/xml; q=0': function formatFoo(req, res, body) {
res.send(js2xmlparser('document', body));
}
}
});
server
.use(restify.fullResponse())
.use(restify.bodyParser())
;
server.pre(restify.pre.userAgentConnection());
require('./routes')(server);
server.listen(8002);
|
'use strict';
var restify = require('restify');
var js2xmlparser = require('js2xmlparser');
var server = restify.createServer({
formatters: {
'application/json; q=5': function format(req, res, body) {
res.setHeader('Content-type', 'application/hal+json');
return JSON.stringify(body);
},
'application/xml; q=0': function formatFoo(req, res, body) {
return js2xmlparser('document', body);
}
}
});
server
.use(restify.fullResponse())
.use(restify.bodyParser())
;
server.pre(restify.pre.userAgentConnection());
require('./routes')(server);
server.listen(8002);
|
Optimize SQL queries used for fetching clouds
|
from rest_framework import permissions as rf_permissions
from rest_framework import exceptions
from nodeconductor.core import viewsets
from nodeconductor.cloud import models
from nodeconductor.cloud import serializers
from nodeconductor.structure import filters as structure_filters
from nodeconductor.structure import models as structure_models
class FlavorViewSet(viewsets.ReadOnlyModelViewSet):
model = models.Flavor
serializer_class = serializers.FlavorSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
class CloudViewSet(viewsets.ModelViewSet):
queryset = models.Cloud.objects.all().prefetch_related('flavors')
serializer_class = serializers.CloudSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
def pre_save(self, cloud):
super(CloudViewSet, self).pre_save(cloud)
if not cloud.customer.roles.filter(
permission_group__user=self.request.user,
role_type=structure_models.CustomerRole.OWNER,
).exists():
raise exceptions.PermissionDenied()
|
from rest_framework import permissions as rf_permissions
from rest_framework import exceptions
from nodeconductor.core import viewsets
from nodeconductor.cloud import models
from nodeconductor.cloud import serializers
from nodeconductor.structure import filters as structure_filters
from nodeconductor.structure import models as structure_models
class FlavorViewSet(viewsets.ReadOnlyModelViewSet):
model = models.Flavor
serializer_class = serializers.FlavorSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
class CloudViewSet(viewsets.ModelViewSet):
model = models.Cloud
serializer_class = serializers.CloudSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
def pre_save(self, cloud):
super(CloudViewSet, self).pre_save(cloud)
if not cloud.customer.roles.filter(
permission_group__user=self.request.user,
role_type=structure_models.CustomerRole.OWNER,
).exists():
raise exceptions.PermissionDenied()
|
Fix header not being validated if 'auth.header' option is not given.
In authenticate middleware.
|
import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
if (header) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
|
import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var verifyHeader = ( !! config.header)
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
if (verifyHeader) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
|
Fix legacy kernel config usage
|
import * as path from 'path'
import { Loader } from './loader'
var loader
const system = () => {
if (typeof loader === 'undefined') {
let scope = new URL(self.registration.scope)
let base = scope
if (KERNEL_CONFIG_BASE) {
let base = new URL(path.join(scope.pathname, path.resolve(KERNEL_CONFIG_BASE)), scope)
}
loader = new Loader({
base: base
})
if (KERNEL_CONFIG_WORKER_EMBED) {
loader.set(KERNEL_CONFIG_WORKER_INIT, require(KERNEL_CONFIG_WORKER_INIT))
}
}
return loader
}
const init = async (fn) => {
return system().import(path.resolve(KERNEL_CONFIG_WORKER_INIT)).then(fn)
}
export default function() {
this.addEventListener('install', (event) => {
event.waitUntil(init(worker => worker.install(event)))
})
this.addEventListener('activate', (event) => {
event.waitUntil(init(worker => worker.activate(event)))
})
this.addEventListener('fetch', (event) => {
event.waitUntil(init(worker => worker.fetch(event)))
})
this.addEventListener('message', (event) => {
if(event.data === 'kernel:sw-force-reload') {
loader = undefined
}
event.waitUntil(init(worker => worker.message(event)))
})
}
|
import * as path from 'path'
import { Loader } from './loader'
var loader
const system = () => {
if (typeof loader === 'undefined') {
let scope = new URL(self.registration.scope)
let base = new URL(path.join(scope.pathname, path.resolve(kernel_conf.base)), scope)
loader = new Loader({
base: base
})
if (KERNEL_CONFIG_WORKER_EMBED) {
loader.set(KERNEL_CONFIG_WORKER_INIT, require(KERNEL_CONFIG_WORKER_INIT))
}
}
return loader
}
const init = async (fn) => {
return system().import(path.resolve(kernel_conf.initsw)).then(fn)
}
export default function() {
this.addEventListener('install', (event) => {
event.waitUntil(init(worker => worker.install(event)))
})
this.addEventListener('activate', (event) => {
event.waitUntil(init(worker => worker.activate(event)))
})
this.addEventListener('fetch', (event) => {
event.waitUntil(init(worker => worker.fetch(event)))
})
this.addEventListener('message', (event) => {
if(event.data === 'kernel:sw-force-reload') {
loader = undefined
}
event.waitUntil(init(worker => worker.message(event)))
})
}
|
Fix fatal error when setting API key
No such property $url, updated to use constant
|
<?php namespace TeamWorkPm;
class Auth
{
const URL = 'https://authenticate.teamworkpm.net/';
private static $config = [
'url' => null,
'key' => null
];
public static function set()
{
$num_args = func_num_args();
if ($num_args === 1) {
self::$config['url'] = self::URL;
self::$config['key'] = func_get_arg(0);
self::$config['url'] = Factory::build('account')->authenticate()->url;
} elseif ($num_args === 2) {
self::$config['url'] = $url = func_get_arg(0);
if ($is_subdomain = (strpos($url, '.') === false)) {
self::$config['url'] = self::URL;
}
self::$config['key'] = func_get_arg(1);
if ($is_subdomain) {
$url = Factory::build('account')->authenticate()->url;
}
self::$config['url'] = $url;
}
}
public static function get()
{
return array_values(self::$config);
}
}
|
<?php namespace TeamWorkPm;
class Auth
{
const URL = 'https://authenticate.teamworkpm.net/';
private static $config = [
'url' => null,
'key' => null
];
public static function set()
{
$num_args = func_num_args();
if ($num_args === 1) {
self::$config['url'] = self::$url;
self::$config['key'] = func_get_arg(0);
self::$config['url'] = Factory::build('account')->authenticate()->url;
} elseif ($num_args === 2) {
self::$config['url'] = $url = func_get_arg(0);
if ($is_subdomain = (strpos($url, '.') === false)) {
self::$config['url'] = self::URL;
}
self::$config['key'] = func_get_arg(1);
if ($is_subdomain) {
$url = Factory::build('account')->authenticate()->url;
}
self::$config['url'] = $url;
}
}
public static function get()
{
return array_values(self::$config);
}
}
|
Make sure files and FS are properly closed in open_archive
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
|
Replace $ with jQuery for noConflict mode
When jQuery is in noConflict mode, the $ operator can be claimed by other frameworks (ProtoType, MooTools). To avoid JS errors, jQuery plugins should not use $ but jQuery instead.
|
jQuery(document).ready(function () {
var rotationMultiplier = 3.6;
// For each div that its id ends with "circle", do the following.
jQuery( "div[id$='circle']" ).each(function() {
// Save all of its classes in an array.
var classList = jQuery( this ).attr('class').split(/\s+/);
// Iterate over the array
for (var i = 0; i < classList.length; i++) {
/* If there's about a percentage class, take the actual percentage and apply the
css transformations in all occurences of the specified percentage class,
even for the divs without an id ending with "circle" */
if (classList[i].match("^p")) {
var rotationPercentage = classList[i].substring(1, classList[i].length);
var rotationDegrees = rotationMultiplier*rotationPercentage;
jQuery('.c100.p'+rotationPercentage+ ' .bar').css({
'-webkit-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-moz-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-ms-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-o-transform' : 'rotate(' + rotationDegrees + 'deg)',
'transform' : 'rotate(' + rotationDegrees + 'deg)'
});
}
}
});
});
|
$(document).ready(function () {
var rotationMultiplier = 3.6;
// For each div that its id ends with "circle", do the following.
$( "div[id$='circle']" ).each(function() {
// Save all of its classes in an array.
var classList = $( this ).attr('class').split(/\s+/);
// Iterate over the array
for (var i = 0; i < classList.length; i++) {
/* If there's about a percentage class, take the actual percentage and apply the
css transformations in all occurences of the specified percentage class,
even for the divs without an id ending with "circle" */
if (classList[i].match("^p")) {
var rotationPercentage = classList[i].substring(1, classList[i].length);
var rotationDegrees = rotationMultiplier*rotationPercentage;
$('.c100.p'+rotationPercentage+ ' .bar').css({
'-webkit-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-moz-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-ms-transform' : 'rotate(' + rotationDegrees + 'deg)',
'-o-transform' : 'rotate(' + rotationDegrees + 'deg)',
'transform' : 'rotate(' + rotationDegrees + 'deg)'
});
}
}
});
});
|
Set alias id on message, if it exists.
|
const DataComposer = require('./BaseComposer');
const dataHandler = require('./DataHandler');
const eventCentral = require('../EventCentral');
const storageManager = require('../StorageManager');
class MessageComposer extends DataComposer {
constructor() {
super({
handler: dataHandler.messages,
completionEvent: eventCentral.Events.COMPLETE_MESSAGE,
dependencies: [
dataHandler.messages,
dataHandler.rooms,
dataHandler.users,
dataHandler.teams,
],
});
this.MessageTypes = {
CHAT: 'chat',
WHISPER: 'whisper',
BROADCAST: 'broadcast',
MESSAGE: 'message',
};
}
getMessage({
messageId,
}) {
const message = this.handler.getObject({ objectId: messageId });
if (message) {
message.creatorName = this.createCreatorName({ object: message });
}
return message;
}
sendMessage({
message,
callback,
}) {
const aliasId = storageManager.getAliasId();
const messageToSend = message;
if (aliasId) { messageToSend.ownerAliasId = aliasId; }
this.handler.createObject({
callback,
params: { message },
});
}
}
const messageComposer = new MessageComposer();
module.exports = messageComposer;
|
const DataComposer = require('./BaseComposer');
const dataHandler = require('./DataHandler');
const eventCentral = require('../EventCentral');
class MessageComposer extends DataComposer {
constructor() {
super({
handler: dataHandler.messages,
completionEvent: eventCentral.Events.COMPLETE_MESSAGE,
dependencies: [
dataHandler.messages,
dataHandler.rooms,
dataHandler.users,
dataHandler.teams,
],
});
this.MessageTypes = {
CHAT: 'chat',
WHISPER: 'whisper',
BROADCAST: 'broadcast',
MESSAGE: 'message',
};
}
getMessage({
messageId,
}) {
const message = this.handler.getObject({ objectId: messageId });
if (message) {
message.creatorName = this.createCreatorName({ object: message });
}
return message;
}
sendMessage({
message,
callback,
}) {
this.handler.createObject({
callback,
params: { message },
});
}
}
const messageComposer = new MessageComposer();
module.exports = messageComposer;
|
PUBDEV-6170: Add a technote explaining what to do when Jetty is missing
|
package water.webserver.iface;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* Finds implementation of {@link HttpServerFacade} found on the classpath.
* There must be exactly one present.
*/
public class HttpServerLoader {
public static final HttpServerFacade INSTANCE;
static {
final ServiceLoader<HttpServerFacade> serviceLoader = ServiceLoader.load(HttpServerFacade.class);
final Iterator<HttpServerFacade> iter = serviceLoader.iterator();
if (! iter.hasNext()) {
throw new IllegalStateException("HTTP Server cannot be loaded: No implementation of HttpServerFacade found on classpath. Please refer to https://0xdata.atlassian.net/browse/TN-13 for details.");
}
INSTANCE = iter.next();
if (iter.hasNext()) {
final StringBuilder sb = new StringBuilder(INSTANCE.getClass().getName());
while (iter.hasNext()) {
sb.append(", ");
sb.append(iter.next().getClass().getName());
}
throw new IllegalStateException("HTTP Server cannot be loaded: Multiple implementations of HttpServerFacade found on classpath: " + sb + ". Please refer to https://0xdata.atlassian.net/browse/TN-13 for details.");
}
}
}
|
package water.webserver.iface;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* Finds implementation of {@link HttpServerFacade} found on the classpath.
* There must be exactly one present.
*/
public class HttpServerLoader {
public static final HttpServerFacade INSTANCE;
static {
final ServiceLoader<HttpServerFacade> serviceLoader = ServiceLoader.load(HttpServerFacade.class);
final Iterator<HttpServerFacade> iter = serviceLoader.iterator();
if (! iter.hasNext()) {
throw new IllegalStateException("No implementation of HttpServerFacade found on classpath");
}
INSTANCE = iter.next();
if (iter.hasNext()) {
final StringBuilder sb = new StringBuilder(INSTANCE.getClass().getName());
while (iter.hasNext()) {
sb.append(",");
sb.append(iter.next().getClass().getName());
}
throw new IllegalStateException("Multiple implementations of HttpServerFacade found on classpath: " + sb);
}
}
}
|
Fix uia_controls registration only when UIA is supported
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
|
Revert to the original import path.
|
// Copyright © 2015-2017 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.
package yara
import (
"github.com/hillu/go-yara/internal/callbackdata"
)
var callbackData = callbackdata.MakePool(256)
func toint64(number interface{}) int64 {
switch number.(type) {
case int:
return int64(number.(int))
case int8:
return int64(number.(int8))
case int16:
return int64(number.(int16))
case int32:
return int64(number.(int32))
case int64:
return int64(number.(int64))
case uint:
return int64(number.(uint))
case uint8:
return int64(number.(uint8))
case uint16:
return int64(number.(uint16))
case uint32:
return int64(number.(uint32))
case uint64:
return int64(number.(uint64))
}
panic("wrong number")
}
|
// Copyright © 2015-2017 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.
package yara
import (
"github.com/VirusTotal/go-yara/internal/callbackdata"
)
var callbackData = callbackdata.MakePool(256)
func toint64(number interface{}) int64 {
switch number.(type) {
case int:
return int64(number.(int))
case int8:
return int64(number.(int8))
case int16:
return int64(number.(int16))
case int32:
return int64(number.(int32))
case int64:
return int64(number.(int64))
case uint:
return int64(number.(uint))
case uint8:
return int64(number.(uint8))
case uint16:
return int64(number.(uint16))
case uint32:
return int64(number.(uint32))
case uint64:
return int64(number.(uint64))
}
panic("wrong number")
}
|
Support evernote:// and other URIs
|
package com.todoist.markup;
import java.util.regex.Pattern;
class Patterns {
public static final Pattern HEADER = Pattern.compile("^\\*\\s*");
public static final Pattern BOLD = Pattern.compile("!!\\s*((?!!!).+?)\\s*!!");
public static final Pattern ITALIC = Pattern.compile("__\\s*((?!__).+?)\\s*__");
public static final Pattern LINK = Pattern.compile("((?:\\w+)://[^\\s><\\[\\],]+)(?:\\s+\\(([^)]+)\\))?");
public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
public static final Pattern THUNDERBIRD =
Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}
|
package com.todoist.markup;
import java.util.regex.Pattern;
class Patterns {
public static final Pattern HEADER = Pattern.compile("^\\*\\s*");
public static final Pattern BOLD = Pattern.compile("!!\\s*((?!!!).+?)\\s*!!");
public static final Pattern ITALIC = Pattern.compile("__\\s*((?!__).+?)\\s*__");
public static final Pattern LINK = Pattern.compile("((?:ftp|https?)://[^\\s><\\[\\],]+)(?:\\s+\\(([^)]+)\\))?");
public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
public static final Pattern THUNDERBIRD =
Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}
|
Fix warnings from phpunit about deprecated assertType
|
<?php
namespace VXML;
class EventTest extends \PHPUnit_Framework_TestCase {
/**
* @var VXML\Event
*/
private $event;
/**
* @var VXML\Rule\RuleAbstract
*/
private $rule;
/**
* @var VXML\Context
*/
private $context;
/**
* @var VXML\Response
*/
private $response;
protected function setUp()
{
parent::setUp ();
$this->rule = new Rule\Equal('field_a', array('equal' => 'test'));
$this->context = new Context(array('field_a' => 'test'));
$this->response = new Response();
$this->event = new Event($this->rule, $this->context, $this->response);
}
protected function tearDown()
{
$this->event = null;
parent::tearDown ();
}
public function testGetRule()
{
$this->assertInstanceOf('VXML\Rule\RuleAbstract', $this->event->getRule());
}
public function testGetContext()
{
$this->assertInstanceOf('VXML\Context', $this->event->getContext());
}
public function testGetResponse()
{
$this->assertInstanceOf('VXML\Response', $this->event->getResponse());
}
}
|
<?php
namespace VXML;
class EventTest extends \PHPUnit_Framework_TestCase {
/**
* @var VXML\Event
*/
private $event;
/**
* @var VXML\Rule\RuleAbstract
*/
private $rule;
/**
* @var VXML\Context
*/
private $context;
/**
* @var VXML\Response
*/
private $response;
protected function setUp()
{
parent::setUp ();
$this->rule = new Rule\Equal('field_a', array('equal' => 'test'));
$this->context = new Context(array('field_a' => 'test'));
$this->response = new Response();
$this->event = new Event($this->rule, $this->context, $this->response);
}
protected function tearDown()
{
$this->event = null;
parent::tearDown ();
}
public function testGetRule()
{
$this->assertType('VXML\Rule\RuleAbstract', $this->event->getRule());
}
public function testGetContext()
{
$this->assertType('VXML\Context', $this->event->getContext());
}
public function testGetResponse()
{
$this->assertType('VXML\Response', $this->event->getResponse());
}
}
|
Include tick in expiry types
|
import moment from 'moment';
import ContractType from './helpers/contract_type';
export const onChangeExpiry = (store) => {
const { contract_type, duration_unit, expiry_date, expiry_type, server_time } = store;
const duration_is_day = expiry_type === 'duration' && duration_unit === 'd';
const expiry_is_after_today = expiry_type === 'endtime' && moment.utc(expiry_date).isAfter(moment(server_time).utc(), 'day');
let contract_expiry_type = 'daily';
if (!duration_is_day && !expiry_is_after_today) {
contract_expiry_type = duration_unit === 't' ? 'tick' : 'intraday';
}
return {
contract_expiry_type,
// TODO: there will be no barrier available if contract is only daily but client chooses intraday endtime. we should find a way to handle this.
...(contract_type && ContractType.getBarriers(contract_type, contract_expiry_type)), // barrier value changes for intraday/daily
};
};
|
import moment from 'moment';
import ContractType from './helpers/contract_type';
export const onChangeExpiry = (store) => {
const { contract_type, duration_unit, expiry_date, expiry_type, server_time } = store;
const duration_is_day = expiry_type === 'duration' && duration_unit === 'd';
const expiry_is_after_today = expiry_type === 'endtime' && moment.utc(expiry_date).isAfter(moment(server_time).utc(), 'day');
const contract_expiry_type = duration_is_day || expiry_is_after_today ? 'daily' : 'intraday';
return {
contract_expiry_type,
// TODO: there will be no barrier available if contract is only daily but client chooses intraday endtime. we should find a way to handle this.
...(contract_type && ContractType.getBarriers(contract_type, contract_expiry_type)), // barrier value changes for intraday/daily
};
};
|
Revert "Increase payload limit to 1.5MB"
This reverts commit eb59950038a363baca64593379739fcb4eeea22f.
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1.5MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
Fix: Reduce visibility of protected class members to private
|
<?php
namespace Application\Controller;
use Application\Service\RepositoryRetriever;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ContributorsController extends AbstractActionController
{
const LIST_LIMIT = 36;
/**
* @var RepositoryRetriever
*/
private $repositoryRetriever;
/**
* @var array
*/
private $repositoryData;
/**
* @param RepositoryRetriever $repositoryRetriever
* @param array $repositoryData
*/
public function __construct(RepositoryRetriever $repositoryRetriever, array $repositoryData)
{
$this->repositoryRetriever = $repositoryRetriever;
$this->repositoryData = $repositoryData;
}
public function indexAction()
{
$contributors = $this->repositoryRetriever->getContributors($this->repositoryData['owner'], $this->repositoryData['name'], self::LIST_LIMIT);
$metadata = $this->repositoryRetriever->getUserRepositoryMetadata($this->repositoryData['owner'], $this->repositoryData['name']);
return new ViewModel([
'contributors' => $contributors,
'metadata' => $metadata,
]);
}
}
|
<?php
namespace Application\Controller;
use Application\Service\RepositoryRetriever;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ContributorsController extends AbstractActionController
{
const LIST_LIMIT = 36;
/**
* @var RepositoryRetriever
*/
protected $repositoryRetriever;
/**
* @var array
*/
protected $repositoryData;
/**
* @param RepositoryRetriever $repositoryRetriever
* @param array $repositoryData
*/
public function __construct(RepositoryRetriever $repositoryRetriever, array $repositoryData)
{
$this->repositoryRetriever = $repositoryRetriever;
$this->repositoryData = $repositoryData;
}
public function indexAction()
{
$contributors = $this->repositoryRetriever->getContributors($this->repositoryData['owner'], $this->repositoryData['name'], self::LIST_LIMIT);
$metadata = $this->repositoryRetriever->getUserRepositoryMetadata($this->repositoryData['owner'], $this->repositoryData['name']);
return new ViewModel([
'contributors' => $contributors,
'metadata' => $metadata,
]);
}
}
|
Fix declaring extra constants when `intl` is loaded
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Php55 as p;
if (PHP_VERSION_ID >= 50500) {
return;
}
if (!function_exists('boolval')) {
function boolval($val) { return p\Php55::boolval($val); }
}
if (!function_exists('json_last_error_msg')) {
function json_last_error_msg() { return p\Php55::json_last_error_msg(); }
}
if (!function_exists('array_column')) {
function array_column($array, $columnKey, $indexKey = null) { return p\Php55ArrayColumn::array_column($array, $columnKey, $indexKey); }
}
if (!function_exists('hash_pbkdf2')) {
function hash_pbkdf2($algorithm, $password, $salt, $iterations, $length = 0, $rawOutput = false) { return p\Php55::hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, $rawOutput); }
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Php55 as p;
if (PHP_VERSION_ID < 50500) {
if (!function_exists('boolval')) {
function boolval($val) { return p\Php55::boolval($val); }
}
if (!function_exists('json_last_error_msg')) {
function json_last_error_msg() { return p\Php55::json_last_error_msg(); }
}
if (!function_exists('array_column')) {
function array_column($array, $columnKey, $indexKey = null) { return p\Php55ArrayColumn::array_column($array, $columnKey, $indexKey); }
}
if (!function_exists('hash_pbkdf2')) {
function hash_pbkdf2($algorithm, $password, $salt, $iterations, $length = 0, $rawOutput = false) { return p\Php55::hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, $rawOutput); }
}
}
|
conan: Make cmake-module-common a dev-only requirement
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.1.2"
class CMakeIncludeGuardConan(ConanFile):
name = "cmake-include-guard"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-include-guard"
licence = "MIT"
options = {
"dev": [True, False]
}
default_options = "dev=False"
def requirements(self):
if self.options.dev:
self.requires("cmake-module-common/master@smspillaz/cmake-module-common")
def source(self):
zip_name = "cmake-include-guard.zip"
download("https://github.com/polysquare/"
"cmake-include-guard/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/cmake-include-guard",
src="cmake-include-guard-" + VERSION,
keep_path=True)
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.1.2"
class CMakeIncludeGuardConan(ConanFile):
name = "cmake-include-guard"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
requires = ("cmake-module-common/master@smspillaz/cmake-module-common", )
generators = "cmake"
url = "http://github.com/polysquare/cmake-include-guard"
licence = "MIT"
def source(self):
zip_name = "cmake-include-guard.zip"
download("https://github.com/polysquare/"
"cmake-include-guard/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/cmake-include-guard",
src="cmake-include-guard-" + VERSION,
keep_path=True)
|
Fix package data so that VERSION file actually gets installed
|
from setuptools import setup, find_packages
import sys, os
PACKAGE = 'mtdna'
VERSION = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'oldowan', PACKAGE, 'VERSION')).read().strip()
desc_lines = open('README', 'r').readlines()
setup(name='oldowan.%s' % PACKAGE,
version=VERSION,
description=desc_lines[0],
long_description=''.join(desc_lines[2:]),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Bio-Informatics"
],
keywords='',
platforms=['Any'],
author='Ryan Raaum',
author_email='code@raaum.org',
url='http://www.raaum.org/software/oldowan',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
namespace_packages = ['oldowan'],
data_files=[("oldowan/%s" % PACKAGE, ["oldowan/%s/VERSION" % PACKAGE])],
zip_safe=False,
test_suite = 'nose.collector',
)
|
from setuptools import setup, find_packages
import sys, os
PACKAGE = 'mtdna'
VERSION = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'oldowan', PACKAGE, 'VERSION')).read().strip()
desc_lines = open('README', 'r').readlines()
setup(name='oldowan.%s' % PACKAGE,
version=VERSION,
description=desc_lines[0],
long_description=''.join(desc_lines[2:]),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Bio-Informatics"
],
keywords='',
platforms=['Any'],
author='Ryan Raaum',
author_email='code@raaum.org',
url='http://www.raaum.org/software/oldowan',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=False,
namespace_packages = ['oldowan'],
data_files=[("oldowan/%s" % PACKAGE, ["oldowan/%s/VERSION" % PACKAGE])],
zip_safe=False,
test_suite = 'nose.collector',
)
|
Use the gallery_image method for required information
|
from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
|
from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
|
Change Jenkins settings.py to use env vars
|
import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('DB_USERNAME', ''),
'TEST_NAME': 'test_cla_backend%s' % (os.environ.get('BACKEND_BASE_PORT', '')), # WARNING: if you want to change this, you NEED to change the dropdb arg in frontend build.py as well
'USER': os.environ.get('DB_USERNAME', ''),
'PASSWORD': os.environ.get('DB_PASSWORD', ''),
'HOST': os.environ.get('DB_HOST', ''),
'PORT': os.environ.get('DB_PORT', ''),
}
}
JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner'
#HOST_NAME = ""
ALLOWED_HOSTS = [
'*'
]
|
import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cla_backend',
'TEST_NAME': 'test_cla_backend%s' % (os.environ.get('BACKEND_BASE_PORT', '')), # WARNING: if you want to change this, you NEED to change the dropdb arg in frontend build.py as well
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner'
#HOST_NAME = ""
ALLOWED_HOSTS = [
'*'
]
|
Remove ShufflePeers() to avoid partion in setup.
|
package main
import (
"bufio"
"fmt"
"os"
"github.com/go-distributed/gog/agent"
"github.com/go-distributed/gog/config"
)
func main() {
config, err := config.ParseConfig()
if err != nil {
fmt.Println("Failed to parse configuration", err)
return
}
ag := agent.NewAgent(config)
ag.RegisterMessageHandler(msgCallBack)
fmt.Printf("serving at %v...\n", config.AddrStr)
go ag.Serve()
if config.Peers != nil {
if err := ag.Join(config.Peers); err != nil {
fmt.Println("No available peers")
//return
}
}
input := bufio.NewReader(os.Stdin)
for {
fmt.Println("input a message:")
bs, err := input.ReadString('\n')
if err != nil {
fmt.Println("error reading:", err)
break
}
if bs == "list\n" {
ag.List()
continue
}
fmt.Println(bs)
ag.Broadcast([]byte(bs))
}
}
func msgCallBack(msg []byte) {
fmt.Println(string(msg))
}
|
package main
import (
"bufio"
"fmt"
"os"
"github.com/go-distributed/gog/agent"
"github.com/go-distributed/gog/config"
)
func main() {
config, err := config.ParseConfig()
if err != nil {
fmt.Println("Failed to parse configuration", err)
return
}
ag := agent.NewAgent(config)
ag.RegisterMessageHandler(msgCallBack)
fmt.Printf("serving at %v...\n", config.AddrStr)
go ag.Serve()
if config.Peers != nil {
if err := ag.Join(config.ShufflePeers()); err != nil {
fmt.Println("No available peers")
//return
}
}
input := bufio.NewReader(os.Stdin)
for {
fmt.Println("input a message:")
bs, err := input.ReadString('\n')
if err != nil {
fmt.Println("error reading:", err)
break
}
if bs == "list\n" {
ag.List()
continue
}
fmt.Println(bs)
ag.Broadcast([]byte(bs))
}
}
func msgCallBack(msg []byte) {
fmt.Println(string(msg))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.