text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add logging and increase timeout
|
from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
|
from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
|
Remove the allocation of a variable in make_course_path
|
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
|
details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
course_path = course_dest + find_details_subdir(clbid) + '.json'
return course_path
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
|
Add peek() and revise main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[-1]
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def show(self):
return self.items
def main():
s = Stack()
print('Is empty: {}'.format(s.is_empty()))
s.push(4)
s.push('dog')
print('Peek: {}'.format(s.peek()))
s.push(True)
print('Size: {}'.format(s.size()))
print('Is empty: {}'.format(s.is_empty()))
s.push(8.4)
print('Pop: {}'.format(s.pop()))
print('Pop: {}'.format(s.pop()))
print('Size: {}'.format(s.size()))
print('Show: {}'.format(s.show()))
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def show(self):
return self.items
def main():
s = Stack()
print(s.is_empty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.is_empty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())
print(s.show())
if __name__ == '__main__':
main()
|
Remove whatever was causing HHVM segfault
|
<?php
namespace Pinq\Tests\Integration\Collection;
class ApplyTest extends CollectionTest
{
/**
* @dataProvider Everything
*/
public function testThatExecutionIsNotDeferred(\Pinq\ICollection $Collection, array $Data)
{
if(count($Data) > 0) {
$this->AssertThatExecutionIsNotDeferred([$Collection, 'Apply']);
}
}
/**
* @dataProvider AssocOneToTen
*/
public function testThatCollectionApplyOperatesOnTheSameCollection(\Pinq\ICollection $Collection, array $Data)
{
$Multiply = function (&$I) { $I *= 10; };
$Collection->Apply($Multiply);
array_walk($Data, $Multiply);
$this->AssertMatches($Collection, $Data);
}
}
|
<?php
namespace Pinq\Tests\Integration\Collection;
class ApplyTest extends CollectionTest
{
/**
* @dataProvider Everything
*/
public function testThatExecutionIsNotDeferred(\Pinq\ICollection $Collection, array $Data)
{
if(count($Data) > 0) {
$this->AssertThatExecutionIsNotDeferred([$Collection, 'Apply']);
}
}
/**
* @dataProvider AssocOneToTen
*/
public function testThatCollectionApplyOperatesOnTheSameCollection(\Pinq\ICollection $Collection, array $Data)
{
static $Count = 0;
$Count++;
var_dump($Count);
$Multiply = function (&$I) { $I = "\\r" . $I * 10 . PHP_EOL; };
$Collection->Apply($Multiply);
array_walk($Data, $Multiply);
$this->AssertMatches($Collection, $Data);
}
}
|
Return float for interval instead of int.
|
import random
class BackoffTimer(object):
def __init__(self, ratio=1, max_interval=None, min_interval=None):
self.c = 0
self.ratio = ratio
self.max_interval = max_interval
self.min_interval = min_interval
def is_reset(self):
return self.c == 0
def reset(self):
self.c = 0
return self
def success(self):
self.c = max(self.c - 1, 0)
return self
def failure(self):
self.c += 1
return self
def get_interval(self):
k = pow(2, self.c) - 1
interval = random.random() * k * self.ratio
if self.max_interval is not None:
interval = min(interval, self.max_interval)
if self.min_interval is not None:
interval = max(interval, self.min_interval)
return interval
|
from random import randint
class BackoffTimer(object):
def __init__(self, ratio=1, max_interval=None, min_interval=None):
self.c = 0
self.ratio = ratio
self.max_interval = max_interval
self.min_interval = min_interval
def is_reset(self):
return self.c == 0
def reset(self):
self.c = 0
return self
def success(self):
self.c = max(self.c - 1, 0)
return self
def failure(self):
self.c += 1
return self
def get_interval(self):
k = pow(2, self.c) - 1
interval = randint(0, k) * self.ratio
if self.max_interval is not None:
interval = min(interval, self.max_interval)
if self.min_interval is not None:
interval = max(interval, self.min_interval)
return interval
|
Add info about required updates in AttributeEntityType
|
class AttributeInputType:
"""The type that we expect to render the attribute's values as."""
DROPDOWN = "dropdown"
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
CHOICES = [
(DROPDOWN, "Dropdown"),
(MULTISELECT, "Multi Select"),
(FILE, "File"),
(REFERENCE, "Reference"),
]
# list of the input types that can be used in variant selection
ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]
class AttributeType:
PRODUCT_TYPE = "product-type"
PAGE_TYPE = "page-type"
CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")]
class AttributeEntityType:
"""Type of a reference entity type. Must match the name of the graphql type.
After adding new value, `REFERENCE_VALUE_NAME_MAPPING`
and `ENTITY_TYPE_TO_MODEL_MAPPING` in saleor/graphql/attribute/utils.py
must be updated.
"""
PAGE = "Page"
PRODUCT = "Product"
CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
|
class AttributeInputType:
"""The type that we expect to render the attribute's values as."""
DROPDOWN = "dropdown"
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
CHOICES = [
(DROPDOWN, "Dropdown"),
(MULTISELECT, "Multi Select"),
(FILE, "File"),
(REFERENCE, "Reference"),
]
# list of the input types that can be used in variant selection
ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]
class AttributeType:
PRODUCT_TYPE = "product-type"
PAGE_TYPE = "page-type"
CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")]
class AttributeEntityType:
"""Type of a reference entity type. Must match the name of the graphql type."""
PAGE = "Page"
PRODUCT = "Product"
CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
|
Add assertions for login test
|
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App;
class LoginTest extends TestCase
{
use DatabaseMigrations;
public function testBasicTest()
{
$this->get('/')->assertRedirect('/login');
$this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ])
->assertStatus(401);
}
public function testLoggedIn()
{
$user = [
'email' => 'example@example.com',
'name' => 'Example',
'password' => 'testtest',
];
factory(App\User::class)->create($user);
$this->post('/login', $user)->assertRedirect('/');
}
public function testLogout()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)->post('/logout')->assertRedirect('/');
}
}
|
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App;
class LoginTest extends TestCase
{
use DatabaseMigrations;
public function testBasicTest()
{
$this->get('/')->assertRedirect('/login');
}
public function testLoggedIn()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)->get('/')->assertStatus(200);
}
public function testLogout()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)->post('/logout')->assertRedirect('/');
}
}
|
Debug and add test cases
|
// Method that performs basic string compression using the counts of repeated characters
function compressStr(str) {
var output = "", // will return this variable as final compressed string
currChar = "", // represents character we are searching for in string
currCount = ""; // counts number of times character is repeated
// iterate through entire string
for (i = 0; i < str.length; i++) {
// if the character we are searching for in string matches the character being looked at
if (currChar !== str[i]) {
output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated
currChar = str[i]; // move on to the next character
currCount = 1; // count resets to 1 since we have moved on to the next character
} else { // if there is a match add to the repeated count
currCount++;
}
}
output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where currChar does not match the character being looked at
return output;
}
// test cases
compressStr("aaaaaaaa"); // expect to return "a8"
compressStr("abbcccdddd"); // expect to return "a1b2c3d4"
|
// Method that performs basic string compression using the counts of repeated characters
function compressStr(str) {
var output = "", // will return this variable as final compressed string
currChar = "", // represents character we are searching for in string
currCount = "", // counts number of times character is repeated
// maxCount = ""; // maximum count
// iterate through entire string
for (i = 0; i < str.length; i++) {
// if the character we are searching for in string matches the character being looked at
if ( currChar !== str[i]) {
output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated
// maxCount = Math.max(maxCount, currCount); // choose the larger value between maxCount and currCount
currChar = str[i]; // move on to the next character
currCount = 1; // count resets to 1 since we have moved on to the next character
} else { // if there is a match add to the repeated count
currCount++;
}
output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where the character we are searching for in string matches the character being looked at
// maxCount = Math.max(maxCount, currCount);
return output;
}
}
|
Fix silly typo "recusrive" => "recursive"
|
// Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recursive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
|
// Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recusrive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
|
Remove log message already produced in superclass
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;
import java.time.Duration;
import java.util.logging.Level;
/**
* Removes expired sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval, true);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected double maintain() {
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofMinutes(90);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
}
return 1.0;
}
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;
import java.time.Duration;
import java.util.logging.Level;
/**
* Removes expired sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval, true);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected double maintain() {
log.log(Level.FINE, () -> "Running " + SessionsMaintainer.class.getSimpleName());
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofMinutes(90);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
}
return 1.0;
}
}
|
Replace typekit script with css
|
export default ({children, links, typekitKey, title, gaKey, appContent, styletronSheets, meta}) => {
return (
<html lang="en">
<head>
<title>{title}</title>
{meta ? meta.map(attrs => <meta {...attrs}/>) : ''}
{styletronSheets.map(sheet =>
<style className="styletron" media={sheet.media} dangerouslySetInnerHTML={{__html:
sheet.css
}}/>
)}
{typekitKey ? <link rel="stylesheet" href={
`https://use.typekit.net/${typekitKey}.css`
}/> : ''}
{links ? links.map(attrs => <link {...attrs}/>) : ''}
</head>
<body>
<div
id="app"
dangerouslySetInnerHTML={{__html: appContent}}
/>
</body>
<script src="/client.bundle.js"></script>
{gaKey ? <script dangerouslySetInnerHTML={{__html: gaScript(gaKey)}}/> : ''}
{gaKey ? <script src="https://www.google-analytics.com/analytics.js" async defer/> : ''}
</html>
)};
function gaScript(key) {
return [
`window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;`,
`ga('create','${key}','auto');ga('send','pageview')`
].join('');
}
|
export default ({children, links, typekitKey, title, gaKey, appContent, styletronSheets, meta}) => {
return (
<html lang="en">
<head>
<title>{title}</title>
{meta ? meta.map(attrs => <meta {...attrs}/>) : ''}
{styletronSheets.map(sheet =>
<style className="styletron" media={sheet.media} dangerouslySetInnerHTML={{__html:
sheet.css
}}/>
)}
{typekitKey ? <script src={
`https://use.typekit.net/${typekitKey}.js`
}/> : ''}
{typekitKey ? <script dangerouslySetInnerHTML={{__html:
'try{Typekit.load({async:true});}catch(e){}'
}}/> : ''}
{links ? links.map(attrs => <link {...attrs}/>) : ''}
</head>
<body>
<div
id="app"
dangerouslySetInnerHTML={{__html: appContent}}
/>
</body>
<script src="/client.bundle.js"></script>
{gaKey ? <script dangerouslySetInnerHTML={{__html: gaScript(gaKey)}}/> : ''}
{gaKey ? <script src="https://www.google-analytics.com/analytics.js" async defer/> : ''}
</html>
)};
function gaScript(key) {
return [
`window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;`,
`ga('create','${key}','auto');ga('send','pageview')`
].join('');
}
|
Convert README.md file into .rst
|
#!/usr/bin/env python
import setuptools
import shutil
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
import shakyo
try:
import pypandoc
with open("README.rst", "w") as f:
f.write(pypandoc.convert("README.md", "rst"))
except ImportError:
shutil.copyfile("README.md", "README")
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
entry_points={"console_scripts" : ["shakyo=shakyo:main"]},
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Programming Language :: Python :: 3.5",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
|
#!/usr/bin/env python
import setuptools
import sys
if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5)
or sys.version_info.major > 3):
exit("Sorry, Python's version must be later than 3.5.")
import shakyo
setuptools.setup(
name=shakyo.__name__,
version=shakyo.__version__,
description="a tool to learn about something just by copying it by hand",
license="Public Domain",
author="raviqqe",
author_email="raviqqe@gmail.com",
url="http://github.com/raviqqe/shakyo/",
py_modules=[shakyo.__name__],
entry_points={"console_scripts" : ["shakyo=shakyo:main"]},
install_requires=["text_unidecode", "validators"],
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: Public Domain",
"Operating System :: POSIX",
"Programming Language :: Python :: 3.5",
"Topic :: Education :: Computer Aided Instruction (CAI)",
"Topic :: Games/Entertainment",
],
)
|
Add a dumb catch to the data handlers handle call
|
import Registry from './Registry';
import {flow, isFunction, isString, omit} from 'lodash';
export default class DataHandler {
/**
* Register a new data handler using the registry.
*/
static set(path, handler) {
Registry.set('dataHandlers.' + path, handler);
}
/**
* Retrieves a data handler given an object path.
*/
static get(path) {
return Registry.get('dataHandlers.' + path);
}
/**
* Call all the data handlers
*
* @@TODO - we should catch failures here and
* @@TODO - provide meaningful error messages
*/
static handle(hs, componentData, dashboardData, e) {
try {
let handlers = (hs || []).map((h) => {
console.log('DH', arguments, h);
let handler = isString(h) ? { name: h } : h ;
let funcHandler = DataHandler.get(handler.name);
let args = omit(handler,'name');
return funcHandler.bind(this, componentData, dashboardData, args, e);
});
let handle = flow(handlers);
return (isFunction(handle)) ? handle(componentData, dashboardData) : componentData;
} catch (e) {
console.error("Error in data handler. This could mean that one of your data handlers is missing from the registry. Here are the handlers we're trying to process:", e, arguments);
}
}
}
|
import Registry from './Registry';
import {flow, isFunction, isString, omit} from 'lodash';
export default class DataHandler {
/**
* Register a new data handler using the registry.
*/
static set(path, handler) {
Registry.set('dataHandlers.' + path, handler);
}
/**
* Retrieves a data handler given an object path.
*/
static get(path) {
return Registry.get('dataHandlers.' + path);
}
/**
* Call all the data handlers.
*/
static handle(hs, componentData, dashboardData, e) {
let handlers = (hs || []).map((h) => {
let handler = isString(h) ? { name: h } : h ;
let funcHandler = DataHandler.get(handler.name);
let args = omit(handler,'name');
return funcHandler.bind(this, componentData, dashboardData, args, e);
});
let handle = flow(handlers);
return (isFunction(handle)) ? handle(componentData, dashboardData) : componentData;
}
}
|
Set browserStack timeout in an attempt to fix failing CI builds
|
module.exports = function (config) {
config.set({
frameworks: ['mocha'],
files: [
'./node_modules/unexpected/unexpected.js',
'./node_modules/sinon/pkg/sinon.js',
'./lib/unexpected-sinon.js',
'./test/common/browser.js',
'./test/monkeyPatchSinonStackFrames.js',
'./test/unexpected-sinon.spec.js',
],
client: {
mocha: {
reporter: 'html',
timeout: 60000,
},
},
browserStack: {
// Attempt to fix timeouts on CI:
// https://github.com/karma-runner/karma-browserstack-launcher/pull/168#issuecomment-582373514
timeout: 1800,
},
browsers: ['ChromeHeadless', 'ie11'],
customLaunchers: {
ie11: {
base: 'BrowserStack',
browser: 'IE',
browser_version: '11',
os: 'Windows',
os_version: '7',
},
},
reporters: ['dots', 'BrowserStack'],
});
};
|
module.exports = function (config) {
config.set({
frameworks: ['mocha'],
files: [
'./node_modules/unexpected/unexpected.js',
'./node_modules/sinon/pkg/sinon.js',
'./lib/unexpected-sinon.js',
'./test/common/browser.js',
'./test/monkeyPatchSinonStackFrames.js',
'./test/unexpected-sinon.spec.js',
],
client: {
mocha: {
reporter: 'html',
timeout: 60000,
},
},
browsers: ['ChromeHeadless', 'ie11'],
customLaunchers: {
ie11: {
base: 'BrowserStack',
browser: 'IE',
browser_version: '11',
os: 'Windows',
os_version: '7',
},
},
reporters: ['dots', 'BrowserStack'],
});
};
|
Add RequestMiddleware if debug is on
|
<?php
namespace App\Bootstrap;
use App\CInterface\BootstrapInterface;
use App\Middleware\RequestLoggerMiddleware;
use App\Middleware\OAuthMiddleware;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconRest\Api;
/**
* Class MiddlewareBootstrap
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Bootstrap\Bootstrap
*/
class MiddlewareBootstrap implements BootstrapInterface
{
public function run(Injectable $api, DiInterface $di, Config $config)
{
if ($config->oauth->enabled) {
$api->attach(new OAuthMiddleware());
}
if ($config->environment != 'production' && $config->debug) {
$api->attach(new RequestLoggerMiddleware());
}
}
}
|
<?php
namespace App\Bootstrap;
use App\CInterface\BootstrapInterface;
use App\Middleware\RequestLoggerMiddleware;
use App\Middleware\OAuthMiddleware;
use Phalcon\Config;
use Phalcon\Di\Injectable;
use Phalcon\DiInterface;
use PhalconRest\Api;
/**
* Class MiddlewareBootstrap
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Bootstrap\Bootstrap
*/
class MiddlewareBootstrap implements BootstrapInterface
{
public function run(Injectable $api, DiInterface $di, Config $config)
{
if ($config->oauth->enabled) {
$api->attach(new OAuthMiddleware());
}
if ($config->environment != 'production') {
$api->attach(new RequestLoggerMiddleware());
}
}
}
|
Add WorkDir field to System struct
|
package gen
type Config struct {
Source string `json:"source"`
Destination string `json:'destination"`
Safe bool `json:"safe"`
Excluede []string `json:"exclude"`
Include string `json""include"`
KeepFiles string `json:"keep_files"`
TimeZone string `json:"timezone"`
Encoding string `json:"encoding"`
Port int `json:"port"`
Host string `json:"host"`
BaseURL string `json:"base_url"`
}
type System struct {
Boot *Boot `json:"boot"`
Config *Config `json:"config"`
Plan *Plan `json:"plan"`
WorkDir string `json:"work_dir"`
}
type Boot struct {
ConfiFile string `json:"config_file"`
PlanFile string `json:"plan_file"`
ENV map[string]string `json:"env"`
}
type Theme struct {
Name string `json:"name"`
Author []Author `json:"author"`
}
type Author struct {
Name string `json:"name"`
Github string `json:"github"`
Twitter string `json:"twitter"`
Linkedin string `json:"linkedin"`
Email string `json:"email"`
Website string `json:"website"`
}
|
package gen
type Config struct {
Source string `json:"source"`
Destination string `json:'destination"`
Safe bool `json:"safe"`
Excluede []string `json:"exclude"`
Include string `json""include"`
KeepFiles string `json:"keep_files"`
TimeZone string `json:"timezone"`
Encoding string `json:"encoding"`
Port int `json:"port"`
Host string `json:"host"`
BaseURL string `json:"base_url"`
}
type System struct {
Boot *Boot `json:"boot"`
Config *Config `json:"config"`
Plan *Plan `json:"plan"`
}
type Boot struct {
ConfiFile string `json:"config_file"`
PlanFile string `json:"plan_file"`
ENV map[string]string `json:"env"`
}
type Theme struct {
Name string `json:"name"`
Author []Author `json:"author"`
}
type Author struct {
Name string `json:"name"`
Github string `json:"github"`
Twitter string `json:"twitter"`
Linkedin string `json:"linkedin"`
Email string `json:"email"`
Website string `json:"website"`
}
|
Use add_handler instead of set handlers as a list.
|
# -*- coding: utf-8 -*-
import unittest
from flask.ext.sqlalchemy import SQLAlchemy
import flask_featureflags as feature_flags
from flask_featureflags.contrib.sqlalchemy import SQLAlchemyFeatureFlags
from tests.fixtures import app, feature_setup
db = SQLAlchemy(app)
SQLAlchemyHandler = SQLAlchemyFeatureFlags(db)
class SQLAlchemyFeatureFlagTest(unittest.TestCase):
@classmethod
def setupClass(cls):
feature_setup.add_handler(SQLAlchemyHandler)
@classmethod
def tearDownClass(cls):
feature_setup.clear_handlers()
def setUp(self):
self.app_ctx = app.app_context()
self.app_ctx.push()
db.create_all()
m1 = SQLAlchemyHandler.model(feature='active', is_active=True)
m2 = SQLAlchemyHandler.model(feature='inactive')
db.session.add_all([m1, m2])
db.session.commit()
def tearDown(self):
db.session.close()
db.drop_all()
self.app_ctx.pop()
def test_flag_active(self):
self.assertTrue(feature_flags.is_active('active'))
def test_flag_inactive(self):
self.assertFalse(feature_flags.is_active('inactive'))
def test_flag_not_found(self):
self.assertFalse(feature_flags.is_active('not_found'))
def test_flag_not_found_raise_handler_exception(self):
self.assertRaises(feature_flags.NoFeatureFlagFound,
SQLAlchemyHandler, 'not_found')
|
# -*- coding: utf-8 -*-
import unittest
from flask.ext.sqlalchemy import SQLAlchemy
import flask_featureflags as feature_flags
from flask_featureflags.contrib.sqlalchemy import SQLAlchemyFeatureFlags
from tests.fixtures import app, feature_setup
db = SQLAlchemy(app)
SQLAlchemyHandler = SQLAlchemyFeatureFlags(db)
class SQLAlchemyFeatureFlagTest(unittest.TestCase):
@classmethod
def setupClass(cls):
feature_setup.handlers = [SQLAlchemyHandler]
@classmethod
def tearDownClass(cls):
feature_setup.clear_handlers()
def setUp(self):
self.app_ctx = app.app_context()
self.app_ctx.push()
db.create_all()
m1 = SQLAlchemyHandler.model(feature='active', is_active=True)
m2 = SQLAlchemyHandler.model(feature='inactive')
db.session.add_all([m1, m2])
db.session.commit()
def tearDown(self):
db.session.close()
db.drop_all()
self.app_ctx.pop()
def test_flag_active(self):
self.assertTrue(feature_flags.is_active('active'))
def test_flag_inactive(self):
self.assertFalse(feature_flags.is_active('inactive'))
def test_flag_not_found(self):
self.assertFalse(feature_flags.is_active('not_found'))
def test_flag_not_found_raise_handler_exception(self):
self.assertRaises(feature_flags.NoFeatureFlagFound,
SQLAlchemyHandler, 'not_found')
|
Add skip to failing test
|
import React from 'react';
import ReactDOM from 'react-dom';
import { expect } from 'chai';
import MarkupFrame from '../src';
function mount( component ) {
const contentArea = window.document.querySelector( '#content' );
ReactDOM.render( component, contentArea );
}
describe( '<MarkupFrame />', function() {
it( 'renders an iframe', function() {
mount( <MarkupFrame markup="" /> );
const iframes = window.document.querySelectorAll( 'iframe' );
expect( iframes ).to.have.length( 1 );
} );
it( 'injects props.markup into the iframe', function() {
mount( <MarkupFrame markup="<h1>Hello World</h1>" /> );
const iframe = window.document.querySelector( 'iframe' );
expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>Hello World</h1>' )
} );
it.skip( 'calls props.onLoad with the iframe document', function( done ) {
const onLoad = function( doc ) {
doc.querySelector( 'h1' ).innerHTML = 'greetings';
const iframe = window.document.querySelector( 'iframe' );
expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>greetings</h1>' );
done();
};
mount( <MarkupFrame markup="<h1>Hello World</h1>" onLoad={ onLoad } /> );
} );
} );
|
import React from 'react';
import ReactDOM from 'react-dom';
import { expect } from 'chai';
import MarkupFrame from '../src';
function mount( component ) {
const contentArea = window.document.querySelector( '#content' );
ReactDOM.render( component, contentArea );
}
describe( '<MarkupFrame />', function() {
it( 'renders an iframe', function() {
mount( <MarkupFrame markup="" /> );
const iframes = window.document.querySelectorAll( 'iframe' );
expect( iframes ).to.have.length( 1 );
} );
it( 'injects props.markup into the iframe', function() {
mount( <MarkupFrame markup="<h1>Hello World</h1>" /> );
const iframe = window.document.querySelector( 'iframe' );
expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>Hello World</h1>' )
} );
it( 'calls props.onLoad with the iframe document', function( done ) {
const onLoad = function( doc ) {
doc.querySelector( 'h1' ).innerHTML = 'greetings';
const iframe = window.document.querySelector( 'iframe' );
expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>greetings</h1>' );
done();
};
mount( <MarkupFrame markup="<h1>Hello World</h1>" onLoad={ onLoad } /> );
} );
} );
|
Make search not case sensitive.
|
/**
* Search functionality for filtering tiles.
*
* Matt Weeks
*/
function stuff() {
removeEDR(document.getElementById('navbarInput-01').value, "tileLiproject");
}
function removeEDR(stringFind, tileClass) {
if (stringFind != "") {
var tiles = document.getElementsByClassName(tileClass);
for (i = 0; i < tiles.length; i++) {
var tile = tiles[i];
tile.className = tile.className.replace(" hideTile", "");
// console.log(tile.firstChild.innerText)
if (tile.firstChild.innerText.toUpperCase().indexOf(stringFind.toUpperCase()) == -1) {
tile.className = tile.className + " hideTile";
}
}
}
else {
clearSearch(tileClass);
}
}
function clearSearch(tileClass) {
var tiles = document.getElementsByClassName(tileClass);
for (i = 0; i < tiles.length; i++) {
var tile = tiles[i];
tile.className = tile.className.replace(" hideTile", "");
}
}
|
/**
* Search functionality for filtering tiles.
*
* Matt Weeks
*/
function stuff() {
removeEDR(document.getElementById('navbarInput-01').value, "tileLiproject");
}
function removeEDR(stringFind, tileClass) {
if (stringFind != "") {
var tiles = document.getElementsByClassName(tileClass);
for (i = 0; i < tiles.length; i++) {
var tile = tiles[i];
tile.className = tile.className.replace(" hideTile", "");
// console.log(tile.firstChild.innerText)
if (tile.firstChild.innerText.indexOf(stringFind) == -1) {
tile.className = tile.className + " hideTile";
}
}
}
else {
clearSearch(tileClass);
}
}
function clearSearch(tileClass) {
var tiles = document.getElementsByClassName(tileClass);
for (i = 0; i < tiles.length; i++) {
var tile = tiles[i];
tile.className = tile.className.replace(" hideTile", "");
}
}
|
Load site interface translation by default
|
<?php
namespace Concrete\Core\Localization\Translator\Adapter\Zend\Translation\Loader\Gettext;
use Concrete\Core\Localization\Translator\Translation\Loader\AbstractTranslationLoader;
use Concrete\Core\Localization\Translator\TranslatorAdapterInterface;
/**
* Translation loader that loads the site interface translations for the Zend
* translation adapter.
*
* @author Antti Hukkanen <antti.hukkanen@mainiotech.fi>
*/
class SiteTranslationLoader extends AbstractTranslationLoader
{
/**
* {@inheritDoc}
*/
public function loadTranslations(TranslatorAdapterInterface $translatorAdapter)
{
$languageFile = DIR_LANGUAGES_SITE_INTERFACE . "/" . $translatorAdapter->getLocale() . ".mo";
if (is_file($languageFile)) {
$translator = $translatorAdapter->getTranslator();
$translator->addTranslationFile('gettext', $languageFile);
}
}
}
|
<?php
namespace Concrete\Core\Localization\Translator\Adapter\Zend\Translation\Loader\Gettext;
use Concrete\Core\Localization\Translator\Translation\Loader\AbstractTranslationLoader;
use Concrete\Core\Localization\Translator\TranslatorAdapterInterface;
/**
* Translation loader that loads the site interface translations for the Zend
* translation adapter.
*
* @author Antti Hukkanen <antti.hukkanen@mainiotech.fi>
*/
class SiteTranslationLoader extends AbstractTranslationLoader
{
/**
* {@inheritDoc}
*/
public function loadTranslations(TranslatorAdapterInterface $translatorAdapter)
{
if ($this->app->make('multilingual/detector')->isEnabled()) {
$languageFile = DIR_LANGUAGES_SITE_INTERFACE . "/" . $translatorAdapter->getLocale() . ".mo";
if (is_file($languageFile)) {
$translator = $translatorAdapter->getTranslator();
$translator->addTranslationFile('gettext', $languageFile);
}
}
}
}
|
Fix for pathnames other than "/"
|
(function (window) {
window.__env = window.__env || {};
if (window.location.port) {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + window.location.pathname;
}
else {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + '/';
}
window.__env.apiUrl = window.__env.hostUrl + 'api/';
window.__env.intontationUrl = window.__env.hostUrl + 'intonation/';
window.__env.annotatorUrl = window.__env.hostUrl + 'annotator/api/';
window.__env.baseUrl = '/';
window.__env.siteName = 'ISCAN';
window.__env.enableDebug = true;
}(this));
|
(function (window) {
window.__env = window.__env || {};
if (window.location.port) {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/';
}
else {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + '/';
}
window.__env.apiUrl = window.__env.hostUrl + 'api/';
window.__env.intontationUrl = window.__env.hostUrl + 'intonation/';
window.__env.annotatorUrl = window.__env.hostUrl + 'annotator/api/';
window.__env.baseUrl = '/';
window.__env.siteName = 'ISCAN';
window.__env.enableDebug = true;
}(this));
|
Add an option to create just the module file
|
#!/usr/bin/env node
const program = require("commander");
const _ = require("lodash");
const utils = require("./utils");
var dest = "";
program
.usage("<module-name> [options]")
.arguments("<module-name>")
.action(function (moduleName) {
cmdModuleName = moduleName;
})
.option("-a, --ctrl-alias <alias>", "Sets an alias for the controller. Defaults to vm.")
.option("-m, --module-only", "Creates only the module.ts file.")
.parse(process.argv);
if (typeof cmdModuleName === "undefined") {
console.log("You must specify a name for the module.");
process.exit(1);
}
program.ctrlAlias = program.ctrlAlias || "vm";
cmdModuleName = utils.camelCase(cmdModuleName);
dest = utils.hyphenate(cmdModuleName.concat("/"));
var vals = {
appName: utils.camelCase(utils.getAppName()),
name: cmdModuleName,
pName: utils.pascalCase(cmdModuleName),
hName: utils.hyphenate(cmdModuleName),
ctrlAlias: program.ctrlAlias,
decoratorPath: utils.getDecoratorPath(dest),
tplPath: utils.getRelativePath()
};
if (program.moduleOnly) {
var tpls = utils.readTemplate("module", "_name.ts");
} else {
var tpls = utils.readTemplates("module");
}
tpls = utils.compileTemplates(tpls, vals, cmdModuleName);
utils.writeFiles(tpls, dest);
|
#!/usr/bin/env node
const program = require("commander");
const _ = require("lodash");
const utils = require("./utils");
var dest = "";
program
.usage("<module-name> [options]")
.arguments("<module-name>")
.action(function (moduleName) {
cmdModuleName = moduleName;
})
.option("-a, --ctrl-alias <alias>", "Sets an alias for the controller. Defaults to vm.")
.parse(process.argv);
if (typeof cmdModuleName === "undefined") {
console.log("You must specify a name for the module.");
process.exit(1);
}
program.ctrlAlias = program.ctrlAlias || "vm";
cmdModuleName = utils.camelCase(cmdModuleName);
dest = utils.hyphenate(cmdModuleName.concat("/"));
var vals = {
appName: utils.camelCase(utils.getAppName()),
name: cmdModuleName,
pName: utils.pascalCase(cmdModuleName),
hName: utils.hyphenate(cmdModuleName),
ctrlAlias: program.ctrlAlias,
decoratorPath: utils.getDecoratorPath(dest),
tplPath: utils.getRelativePath()
};
var tpls = utils.readTemplates("module");
tpls = utils.compileTemplates(tpls, vals, cmdModuleName);
utils.writeFiles(tpls, dest);
|
Change tab size to 2
|
import React, { Component } from 'react'
import CodeMirror from 'react-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
require('codemirror/mode/jsx/jsx')
class LiveEditor extends Component {
constructor(props) {
super(props)
this.handleCodeChange = this.handleCodeChange.bind(this)
}
handleCodeChange(code) {
this.props.updateCode(code)
}
render() {
const options = {
mode: 'jsx',
lineWrapping: true,
smartIndent: true,
matchBrackets: true,
theme: 'monokai',
readOnly: false,
lineNumbers: true,
tabSize: 2,
indentUnit: 2,
}
return (
<div className="live-editor">
<CodeMirror
ref={(ref) => { this.wrapper = ref }}
className="codemirror"
external="true"
options={options}
value={this.props.code}
onChange={this.handleCodeChange}
/>
</div>
)
}
}
LiveEditor.propTypes = {
code: React.PropTypes.string.isRequired,
updateCode: React.PropTypes.func.isRequired,
}
LiveEditor.defaultProps = {
code: '',
}
export default LiveEditor
|
import React, { Component } from 'react'
import CodeMirror from 'react-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
require('codemirror/mode/jsx/jsx')
class LiveEditor extends Component {
constructor(props) {
super(props)
this.handleCodeChange = this.handleCodeChange.bind(this)
}
handleCodeChange(code) {
this.props.updateCode(code)
}
render() {
const options = {
mode: 'jsx',
lineWrapping: true,
smartIndent: true,
matchBrackets: true,
theme: 'monokai',
readOnly: false,
lineNumbers: true,
}
return (
<div className="live-editor">
<CodeMirror
ref={(ref) => { this.wrapper = ref }}
className="codemirror"
external="true"
options={options}
value={this.props.code}
onChange={this.handleCodeChange}
/>
</div>
)
}
}
LiveEditor.propTypes = {
code: React.PropTypes.string.isRequired,
updateCode: React.PropTypes.func.isRequired,
}
LiveEditor.defaultProps = {
code: '',
}
export default LiveEditor
|
Add trailing comma to last item in Menu array
|
<?php
namespace Setup;
class Menus
{
/**
* Initialization
* This method should be run from functions.php
*/
public static function init()
{
add_action( 'init', array(__CLASS__, 'register') );
}
/**
* Registers menus within our theme
*/
public static function register()
{
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'components-theme' ),
'utility' => __( 'Utility Menu', 'components-theme' ),
'footer-menu' => __( 'Footer Menu', 'components-theme' ),
'footer-legal' => __( 'Footer Legal', 'components-theme' ),
) );
}
}
|
<?php
namespace Setup;
class Menus
{
/**
* Initialization
* This method should be run from functions.php
*/
public static function init()
{
add_action( 'init', array(__CLASS__, 'register') );
}
/**
* Registers menus within our theme
*/
public static function register()
{
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'components-theme' ),
'utility' => __( 'Utility Menu', 'components-theme' ),
'footer-menu' => __( 'Footer Menu', 'components-theme' ),
'footer-legal' => __( 'Footer Legal', 'components-theme' )
) );
}
}
|
Add a message when refusing due to a lack of query parameter
|
"use strict";
var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
if(!req.query.query) {
return next(new restify.ConflictError("Missing query parameter"));
}
async.waterfall([
function getDocuments(cb) {
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments({ search: req.query.query, render_templates: true }, cb);
},
function remapDocuments(documentsRes, cb) {
res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
return {
type: document.document_type.name,
id: document.id,
date: document.modification_date,
snippet: document.rendered_snippet,
title: document.rendered_title
};
}));
cb();
}
], next);
};
|
"use strict";
var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
if(!req.query.query) {
return next(new restify.ConflictError());
}
async.waterfall([
function getDocuments(cb) {
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments({ search: req.query.query, render_templates: true }, cb);
},
function remapDocuments(documentsRes, cb) {
res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
return {
type: document.document_type.name,
id: document.id,
date: document.modification_date,
snippet: document.rendered_snippet,
title: document.rendered_title
};
}));
cb();
}
], next);
};
|
Exit when backButton pressed in menu
|
package com.robitdroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class RobitDroid extends Activity {
private ImageView imageview;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageview = (ImageView) findViewById(R.id.ImageViewRobit);
imageview.getLayoutParams().height = 400;
}
public void selfStart(View view) {
Log.v("RobitDroid", "In selfStart method");
// Start new game
Intent i = new Intent(view.getContext(), GameScreen.class);
startActivity(i);
}
public void showInstructions(View view) {
showDialog(0);
}
@Override
public void onBackPressed() {
finish();
}
}
|
package com.robitdroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class RobitDroid extends Activity {
private ImageView imageview;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageview = (ImageView) findViewById(R.id.ImageViewRobit);
imageview.getLayoutParams().height = 400;
}
public void selfStart(View view) {
Log.v("RobitDroid", "In selfStart method");
// Start new game
Intent i = new Intent(view.getContext(), GameScreen.class);
startActivity(i);
}
public void showInstructions(View view) {
showDialog(0);
}
}
|
Add window.__PROMISE_INSTRUMENTATION__ flag to register RSVP.on callbacks
|
import Promise from "./rsvp/promise";
import EventTarget from "./rsvp/events";
import denodeify from "./rsvp/node";
import all from "./rsvp/all";
import race from "./rsvp/race";
import hash from "./rsvp/hash";
import rethrow from "./rsvp/rethrow";
import defer from "./rsvp/defer";
import { config, configure } from "./rsvp/config";
import map from "./rsvp/map";
import resolve from "./rsvp/resolve";
import reject from "./rsvp/reject";
import asap from "./rsvp/asap";
import filter from "./rsvp/filter";
config.async = asap; // default async is asap;
function async(callback, arg) {
config.async(callback, arg);
}
function on() {
config.on.apply(config, arguments);
}
function off() {
config.off.apply(config, arguments);
}
// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') {
var callbacks = window.__PROMISE_INSTRUMENTATION__;
configure('instrument', true);
for (var eventName in callbacks) {
if (callbacks.hasOwnProperty(eventName)) {
on(eventName, callbacks[eventName]);
}
}
}
export { Promise, EventTarget, all, race, hash, rethrow, defer, denodeify, configure, on, off, resolve, reject, async, map, filter };
|
import Promise from "./rsvp/promise";
import EventTarget from "./rsvp/events";
import denodeify from "./rsvp/node";
import all from "./rsvp/all";
import race from "./rsvp/race";
import hash from "./rsvp/hash";
import rethrow from "./rsvp/rethrow";
import defer from "./rsvp/defer";
import { config, configure } from "./rsvp/config";
import map from "./rsvp/map";
import resolve from "./rsvp/resolve";
import reject from "./rsvp/reject";
import asap from "./rsvp/asap";
import filter from "./rsvp/filter";
config.async = asap; // default async is asap;
function async(callback, arg) {
config.async(callback, arg);
}
function on() {
config.on.apply(config, arguments);
}
function off() {
config.off.apply(config, arguments);
}
export { Promise, EventTarget, all, race, hash, rethrow, defer, denodeify, configure, on, off, resolve, reject, async, map, filter };
|
Change of repo name. Update effected paths
|
import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
def plot_artificial_sms_dataset():
tau = pm.rdiscrete_uniform(0, 80)
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
plt.bar(np.arange(80), data, color="#348ABD")
plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
plt.xlim(0, 80)
plt.title("More example of artificial datasets")
for i in range(1, 5):
plt.subplot(4, 1, i)
plot_artificial_sms_dataset()
plt.show()
if __name__ == '__main__':
main()
|
import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
def plot_artificial_sms_dataset():
tau = pm.rdiscrete_uniform(0, 80)
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
plt.bar(np.arange(80), data, color="#348ABD")
plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
plt.xlim(0, 80)
plt.title("More example of artificial datasets")
for i in range(1, 5):
plt.subplot(4, 1, i)
plot_artificial_sms_dataset()
plt.show()
if __name__ == '__main__':
main()
|
feat(role): Add isAdmin to user store if is admin
|
'use strict'
var rootDir = __dirname.split('/')
rootDir.pop()
rootDir = rootDir.join('/')
var app =
{ rootDir: rootDir
}
var Role = require(__dirname + '/../routes/roles/model')(app)
var User = require(__dirname + '/../routes/users/model')(app)
module.exports = function *checkRole() {
var cb = function(resolve, reject) {
var route = this.originalUrl
var userRoles = this.auth.Roles
var method = this.request.method.toLowerCase()
var roleCount = userRoles.length
// Concat all routes arrays
var whitelist = []
for(let i = 0; i < roleCount; i++) {
// If admin - full access
if(userRoles[i].name === 'admin') {
this.auth.isAdmin = true
resolve(true)
}
whitelist = whitelist.concat(userRoles[i].Routes)
}
var routeCount = whitelist.length
for (let i = 0; i < routeCount; i++) {
var routeItem = whitelist[i]
var regexp = new RegExp(routeItem.url)
var routeMethod = routeItem.method.toLowerCase()
if
( routeMethod === method &&
route.match(regexp)
) {
return resolve(true)
}
}
return reject(false)
}.bind(this)
return new Promise(cb)
}
|
'use strict'
var rootDir = __dirname.split('/')
rootDir.pop()
rootDir = rootDir.join('/')
var app =
{ rootDir: rootDir
}
var Role = require(__dirname + '/../routes/roles/model')(app)
var User = require(__dirname + '/../routes/users/model')(app)
module.exports = function *checkRole() {
var cb = function(resolve, reject) {
var route = this.originalUrl
var userRoles = this.auth.Roles
var method = this.request.method.toLowerCase()
var roleCount = userRoles.length
// Concat all routes arrays
var whitelist = []
for(let i = 0; i < roleCount; i++) {
// If admin - full access
if(userRoles[i].name === 'admin') {
resolve(true)
}
whitelist = whitelist.concat(userRoles[i].Routes)
}
var routeCount = whitelist.length
for (let i = 0; i < routeCount; i++) {
var routeItem = whitelist[i]
var regexp = new RegExp(routeItem.url)
var routeMethod = routeItem.method.toLowerCase()
if
( routeMethod === method &&
route.match(regexp)
) {
return resolve(true)
}
}
return reject(false)
}.bind(this)
return new Promise(cb)
}
|
Allow versions of requests between 1.0.0 and 2.0.0
Requests is semantically versioned, so minor version changes are expected to be compatible.
|
from setuptools import setup
from setuptools import find_packages
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '2.5.5'
setup(
# Basic package information.
name='twython',
version=__version__,
packages=find_packages(),
# Packaging options.
include_package_data=True,
# Package dependencies.
install_requires=['simplejson', 'requests>=1.0.0, <2.0.0', 'requests_oauthlib==0.3.0'],
# Metadata for PyPI.
author='Ryan McGrath',
author_email='ryan@venodesigns.net',
license='MIT License',
url='http://github.com/ryanmcgrath/twython/tree/master',
keywords='twitter search api tweet twython',
description='An easy (and up to date) way to access Twitter data with Python.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet'
]
)
|
from setuptools import setup
from setuptools import find_packages
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '2.5.5'
setup(
# Basic package information.
name='twython',
version=__version__,
packages=find_packages(),
# Packaging options.
include_package_data=True,
# Package dependencies.
install_requires=['simplejson', 'requests==1.1.0', 'requests_oauthlib==0.3.0'],
# Metadata for PyPI.
author='Ryan McGrath',
author_email='ryan@venodesigns.net',
license='MIT License',
url='http://github.com/ryanmcgrath/twython/tree/master',
keywords='twitter search api tweet twython',
description='An easy (and up to date) way to access Twitter data with Python.',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet'
]
)
|
DOC: Set default syntax highlighting language to 'none'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
Add CORS handler for Location header
|
package feeds
import (
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
"google.golang.org/appengine"
)
func Run() {
dao := datastoreFeedsDao{}
router := mux.NewRouter()
corsHandler := cors.New(cors.Options{
AllowedHeaders:{"Location"},
})
router.Handle("/feeds", corsHandler(getFeedsHandler{dao})).
Methods(http.MethodGet)
getHandler := corsHandler(getFeedHandler{dao})
router.Handle("/feeds/{feedId}", getHandler).
Methods(http.MethodGet)
postHandler := corsHandler(postHttpHandler{appengine.NewContext, fetchRssWithUrlFetch, dao})
router.Handle("/feeds", postHandler).
Methods(http.MethodPost).
Headers("Content-Type", "application/json")
http.Handle("/", corsHandler(router))
}
|
package feeds
import (
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
"google.golang.org/appengine"
)
func Run() {
dao := datastoreFeedsDao{}
router := mux.NewRouter()
router.Handle("/feeds", cors.Default().Handler(getFeedsHandler{dao})).
Methods(http.MethodGet)
getHandler := cors.Default().Handler(getFeedHandler{dao})
router.Handle("/feeds/{feedId}", getHandler).
Methods(http.MethodGet)
postHandler := cors.Default().Handler(postHttpHandler{appengine.NewContext, fetchRssWithUrlFetch, dao})
router.Handle("/feeds", postHandler).
Methods(http.MethodPost).
Headers("Content-Type", "application/json")
http.Handle("/", cors.Default().Handler(router))
}
|
Fix for renamed module util -> utils
|
#!/usr/bin/env python
import os.path as osp
import chainer
import fcn
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.utils.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import os.path as osp
import chainer
import fcn.data
import fcn.util
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
|
Remove a couple of console.log calls
|
var path = require("path");
var mvc = exports = module.exports;
/**
* Enable having multiple folders for views to support the
* module/mymodule/views structure
*/
mvc.EnableMultipeViewsFolders = function(app) {
// Monkey-patch express to accept multiple paths for looking up views.
// this path may change depending on your setup.
var lookup_proxy = app.settings.view.prototype.lookup;
app.settings.view.prototype.lookup = function(viewName) {
var context, match;
if (this.root instanceof Array) {
for (var i = 0; i < this.root.length; i++) {
context = {root: this.root[i]};
match = lookup_proxy.call(context, viewName);
if (match) {
return match;
}
}
return null;
}
return lookup_proxy.call(this, viewName);
};
}
/**
* Add a view to express so it's enabled
*/
mvc.addView = function(app, directory) {
var views = app.settings.views;
var currentView = path.join(directory, 'views');
views.push(currentView);
app.set('views', views);
}
|
var path = require("path");
var mvc = exports = module.exports;
/**
* Enable having multiple folders for views to support the
* module/mymodule/views structure
*/
mvc.EnableMultipeViewsFolders = function(app) {
// Monkey-patch express to accept multiple paths for looking up views.
// this path may change depending on your setup.
var lookup_proxy = app.settings.view.prototype.lookup;
app.settings.view.prototype.lookup = function(viewName) {
console.log(viewName);
var context, match;
if (this.root instanceof Array) {
for (var i = 0; i < this.root.length; i++) {
context = {root: this.root[i]};
console.log(context);
match = lookup_proxy.call(context, viewName);
if (match) {
return match;
}
}
return null;
}
return lookup_proxy.call(this, viewName);
};
}
/**
* Add a view to express so it's enabled
*/
mvc.addView = function(app, directory) {
var views = app.settings.views;
var currentView = path.join(directory, 'views');
views.push(currentView);
app.set('views', views);
}
|
Add --include-ts to find error script
|
const { writeFileSync } = require('fs')
const alltests = require('./test-results')
const includeTs = process.argv.includes('--include-ts')
const results = [
...alltests.testResults[0].assertionResults,
...(includeTs ? alltests.testResults[1].assertionResults : [])
]
.filter(_ => _.failureMessages.length === 1)
.map(_ => _.failureMessages[0])
.map(_ => _.split('[')[0])
.map(_ => (_.includes('SYNTAX ERROR') ? 'SYNTAX ERROR' : _))
.map(_ => _.split('\n')[0])
.map(_ => (_.startsWith('Error:') ? _.split(':')[2] : _))
.reduce((count, err) => {
count[err] = !count[err] ? 1 : count[err] + 1
return count
}, {})
const count = Object.entries(results)
.sort(([, count1], [, count2]) => count2 - count1)
.map(_ => _[1] + ' ' + _[0])
.join('\n')
console.log(count)
|
const { writeFileSync } = require('fs')
const alltests = require('./test-results')
const results = alltests.testResults[0].assertionResults
.filter(_ => _.failureMessages.length === 1)
.map(_ => _.failureMessages[0])
.map(_ => _.split('[')[0])
.map(_ => (_.includes('SYNTAX ERROR') ? 'SYNTAX ERROR' : _))
.map(_ => _.split('\n')[0])
.map(_ => (_.startsWith('Error:') ? _.split(':')[2] : _))
.reduce((count, err) => {
count[err] = !count[err] ? 1 : count[err] + 1
return count
}, {})
const count = Object.entries(results)
.sort(([, count1], [, count2]) => count2 - count1)
.map(_ => _[1] + ' ' + _[0])
.join('\n')
console.log(count)
|
Simplify prove tests with read.Term_
|
package golog
import "github.com/mndrix/golog/read"
import "testing"
func TestFacts (t *testing.T) {
rt := read.Term_
db := NewDatabase().
Asserta(rt(`father(michael).`)).
Asserta(rt(`father(marc).`))
t.Logf("%s\n", db.String())
// these should be provably true
if !IsTrue(db, rt(`father(michael).`)) {
t.Errorf("Couldn't prove father(michael)")
}
if !IsTrue(db, rt(`father(marc).`)) {
t.Errorf("Couldn't prove father(marc)")
}
// these should not be provable
if IsTrue(db, rt(`father(sue).`)) {
t.Errorf("Proved father(sue)")
}
if IsTrue(db, rt(`father(michael,marc).`)) {
t.Errorf("Proved father(michael, marc)")
}
if IsTrue(db, rt(`mother(michael).`)) {
t.Errorf("Proved mother(michael)")
}
}
|
package golog
import . "github.com/mndrix/golog/term"
import "testing"
func TestFacts (t *testing.T) {
db := NewDatabase().
Asserta(NewTerm("father", NewTerm("michael"))).
Asserta(NewTerm("father", NewTerm("marc")))
t.Logf("%s\n", db.String())
// these should be provably true
if !IsTrue(db, NewTerm("father", NewTerm("michael"))) {
t.Errorf("Couldn't prove father(michael)")
}
if !IsTrue(db, NewTerm("father", NewTerm("marc"))) {
t.Errorf("Couldn't prove father(marc)")
}
// these should not be provable
if IsTrue(db, NewTerm("father", NewTerm("sue"))) {
t.Errorf("Proved father(sue)")
}
if IsTrue(db, NewTerm("father", NewTerm("michael"), NewTerm("marc"))) {
t.Errorf("Proved father(michael, marc)")
}
if IsTrue(db, NewTerm("mother", NewTerm("michael"))) {
t.Errorf("Proved mother(michael)")
}
}
|
Disable wrapInEval for standalone builds.
|
/* jshint node: true */
var mergeTrees = require('broccoli-merge-trees');
var pickFiles = require('broccoli-static-compiler');
var compileES6 = require('broccoli-es6-concatenator');
var templateCompiler = require('broccoli-ember-hbs-template-compiler');
var registry = require('./registry');
var wrap = require('./wrap');
var version = require('../package.json').version;
var appTree = pickFiles('../app-addon', { srcDir: '/', destDir: 'app-addon'});
var templateTree = templateCompiler('../app-addon/templates', { module: true });
templateTree = pickFiles(templateTree, {srcDir: '/', destDir: 'app-addon/templates'});
var vendorTree = mergeTrees(['../vendor-addon', '../vendor']);
vendorTree = pickFiles(vendorTree, { srcDir: '/', destDir: 'vendor' });
var precompiled = mergeTrees([vendorTree, appTree, templateTree]);
var registrations = registry(pickFiles(precompiled, {srcDir: '/app-addon', destDir: '/'}));
var compiled = compileES6(mergeTrees(['.', mergeTrees([precompiled, registrations])]), {
wrapInEval: false,
loaderFile: 'vendor/loader/loader.js',
inputFiles: ['vendor/liquid-fire.js', 'app-addon/**/*.js'],
ignoredModules: ['ember'],
outputFile: '/liquid-fire-' + version + '.js',
legacyFilesToAppend: ['registry-output.js', 'glue.js']
});
module.exports = wrap(compiled);
|
/* jshint node: true */
var mergeTrees = require('broccoli-merge-trees');
var pickFiles = require('broccoli-static-compiler');
var compileES6 = require('broccoli-es6-concatenator');
var templateCompiler = require('broccoli-ember-hbs-template-compiler');
var registry = require('./registry');
var wrap = require('./wrap');
var version = require('../package.json').version;
var appTree = pickFiles('../app-addon', { srcDir: '/', destDir: 'app-addon'});
var templateTree = templateCompiler('../app-addon/templates', { module: true });
templateTree = pickFiles(templateTree, {srcDir: '/', destDir: 'app-addon/templates'});
var vendorTree = mergeTrees(['../vendor-addon', '../vendor']);
vendorTree = pickFiles(vendorTree, { srcDir: '/', destDir: 'vendor' });
var precompiled = mergeTrees([vendorTree, appTree, templateTree]);
var registrations = registry(pickFiles(precompiled, {srcDir: '/app-addon', destDir: '/'}));
var compiled = compileES6(mergeTrees(['.', mergeTrees([precompiled, registrations])]), {
loaderFile: 'vendor/loader/loader.js',
inputFiles: ['vendor/liquid-fire.js', 'app-addon/**/*.js'],
ignoredModules: ['ember'],
outputFile: '/liquid-fire-' + version + '.js',
legacyFilesToAppend: ['registry-output.js', 'glue.js']
});
module.exports = wrap(compiled);
|
Add activation auth method, needed for lost password in tests
|
<?php
class Kwf_User_AuthPassword_FnF extends Kwf_Model_FnF
{
protected $_toStringField = 'email';
protected $_hasDeletedFlag = true;
protected function _init()
{
$this->_data = array(
array('id'=>1, 'email' => 'test@vivid.com', 'password' => md5('foo'.'123'), 'password_salt' => '123', 'deleted'=>false),
array('id'=>2, 'email' => 'testdel@vivid.com', 'password' => md5('bar'.'1234'), 'password_salt' => '1234', 'deleted'=>true),
);
parent::_init();
}
public function getAuthMethods()
{
return array(
'password' => new Kwf_User_Auth_PasswordFields($this),
'activation' => new Kwf_User_Auth_ActivationFields($this),
);
}
}
|
<?php
class Kwf_User_AuthPassword_FnF extends Kwf_Model_FnF
{
protected $_toStringField = 'email';
protected $_hasDeletedFlag = true;
protected function _init()
{
$this->_data = array(
array('id'=>1, 'email' => 'test@vivid.com', 'password' => md5('foo'.'123'), 'password_salt' => '123', 'deleted'=>false),
array('id'=>2, 'email' => 'testdel@vivid.com', 'password' => md5('bar'.'1234'), 'password_salt' => '1234', 'deleted'=>true),
);
parent::_init();
}
public function getAuthMethods()
{
return array(
'password' => new Kwf_User_Auth_PasswordFields($this)
);
}
}
|
Fix XSS issue in demo
|
$(function() {
// When we're using HTTPS, use WSS too.
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
chatsock.onmessage = function(message) {
var data = JSON.parse(message.data);
var chat = $("#chat")
var ele = $('<tr></tr>')
ele.append(
$("<td></td>").text(data.timestamp)
)
ele.append(
$("<td></td>").text(data.handle)
)
ele.append(
$("<td></td>").text(data.message)
)
chat.append(ele)
};
$("#chatform").on("submit", function(event) {
var message = {
handle: $('#handle').val(),
message: $('#message').val(),
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
});
});
|
$(function() {
// When we're using HTTPS, use WSS too.
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
chatsock.onmessage = function(message) {
var data = JSON.parse(message.data);
$("#chat").append('<tr>'
+ '<td>' + data.timestamp + '</td>'
+ '<td>' + data.handle + '</td>'
+ '<td>' + data.message + ' </td>'
+ '</tr>');
};
$("#chatform").on("submit", function(event) {
var message = {
handle: $('#handle').val(),
message: $('#message').val(),
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
});
});
|
Use updateHead instead of createRef
|
var oauthAuth = new GitHub(logged ? { token: logged } : {}),
repo = oauthAuth.getRepo(OWNER_NAME, PROJECT_NAME),
auth = logged ? oauthAuth.getUser() : false;
// READ REPO
repo.getDetails(function(e,r){
// CHECK ADMIN
if (r.permissions && r.permissions.admin) {
// Show admin link
document.querySelector('a[href*="admin"][hidden]').removeAttribute('hidden');
// CHECK FORK
if (r.owner.type === "User" && r.fork) {
// Check synch
// var parentNwo = [r.parent.owner.login, r.parent.name].join('/');
var parentRepo = oauthAuth.getRepo(r.parent.owner.login, r.parent.name);
// Get parent ref
parentRepo.getRef('heads/master', function(e,r) {
console.log('parent ref', r.object.sha);
if (r.object.sha != BUILD_REVISION) {
// Update ref
repo.updateHead('refs/heads/master', r.object.sha, true, function (e,r) {
console.log('new ref', r);
dialog('updated: new ref');
});
}
});
}
}
});
|
var oauthAuth = new GitHub(logged ? { token: logged } : {}),
repo = oauthAuth.getRepo(OWNER_NAME, PROJECT_NAME),
auth = logged ? oauthAuth.getUser() : false;
// READ REPO
repo.getDetails(function(e,r){
// CHECK ADMIN
if (r.permissions && r.permissions.admin) {
// Show admin link
document.querySelector('a[href*="admin"][hidden]').removeAttribute('hidden');
// CHECK FORK
if (r.owner.type === "User" && r.fork) {
// Check synch
// var parentNwo = [r.parent.owner.login, r.parent.name].join('/');
var parentRepo = oauthAuth.getRepo(r.parent.owner.login, r.parent.name);
// Get parent ref
parentRepo.getRef('heads/master', function(e,r) {
console.log('parent ref', r.object.sha);
if (r.object.sha != BUILD_REVISION) {
// Update ref
repo.createRef({ ref: 'refs/heads/master', sha: r.object.sha }, function (e,r) {
console.log('new ref', r);
flash('updated: new ref');
});
}
});
}
}
});
|
Remove the need to define a default validator
|
<?php
namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Dependency injection container compiler pass to register markup validation
* processors. It finds all services having the "markup_validator.processor"
* tag and adds them to the validator
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class RegisterValidatorsPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
if (isset($attributes[0]['alias'])) {
$container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
}
}
}
}
|
<?php
namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Dependency injection container compiler pass to register markup validation
* processors. It finds all services having the "markup_validator.processor"
* tag and adds them to the validator
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class RegisterValidatorsPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('markup_validator')) {
return ;
}
foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
if (isset($attributes[0]['alias'])) {
$container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
}
}
}
}
|
Move over tweaks to munge-phdr script from chromium repo
Some cosmetic changes were made on the chromium side since we copied it.
Catch up to those, still preparing to remove the chromium copy ASAP.
BUG= none
TEST= trybots
R=bradchen@google.com
Review URL: http://codereview.chromium.org/8728008
git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@7312 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
|
#!/usr/bin/env python
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This takes three command-line arguments:
MUNGE-PHDR-PROGRAM file name of program built from
nacl_helper_bootstrap_munge_phdr.c
INFILE raw linked ELF file name
OUTFILE output file name
We just run the MUNGE-PHDR-PROGRAM on a copy of INFILE.
That modifies the file in place. Then we move it to OUTFILE.
We only have this wrapper script because nacl_helper_bootstrap_munge_phdr.c
wants to modify a file in place (and it would be a much longer and more
fragile program if it created a fresh ELF output file instead).
"""
import shutil
import subprocess
import sys
def Main(argv):
if len(argv) != 4:
print 'Usage: %s MUNGE-PHDR-PROGRAM INFILE OUTFILE' % argv[0]
return 1
[prog, munger, infile, outfile] = argv
tmpfile = outfile + '.tmp'
shutil.copy(infile, tmpfile)
segment_num = '2'
subprocess.check_call([munger, tmpfile, segment_num])
shutil.move(tmpfile, outfile)
return 0
if __name__ == '__main__':
sys.exit(Main(sys.argv))
|
#!/usr/bin/python
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This takes three command-line arguments:
# MUNGE-PHDR-PROGRAM file name of program built from
# nacl_helper_bootstrap_munge_phdr.c
# INFILE raw linked ELF file name
# OUTFILE output file name
#
# We just run the MUNGE-PHDR-PROGRAM on a copy of INFILE.
# That modifies the file in place. Then we move it to OUTFILE.
#
# We only have this wrapper script because nacl_helper_bootstrap_munge_phdr.c
# wants to modify a file in place (and it would be a much longer and more
# fragile program if it created a fresh ELF output file instead).
import shutil
import subprocess
import sys
def Main(argv):
if len(argv) != 4:
print 'Usage: %s MUNGE-PHDR-PROGRAM INFILE OUTFILE' % argv[0]
sys.exit(1)
[prog, munger, infile, outfile] = argv
tmpfile = outfile + '.tmp'
shutil.copy(infile, tmpfile)
segment_num = '2'
subprocess.check_call([munger, tmpfile, segment_num])
shutil.move(tmpfile, outfile)
if __name__ == '__main__':
Main(sys.argv)
|
Test: Add output returned by the fixer
|
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require('../../../lib/rules/no-const-outside-module-scope');
var RuleTester = require('eslint').RuleTester;
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
}
});
ruleTester.run('no-const-outside-module-scope', rule, {
valid: [
'const FOOBAR = 5;',
'export const FOOBAR = 5;'
],
invalid: [{
code: '{ const FOOBAR = 5; }',
output: '{ let FOOBAR = 5; }',
errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }]
}, {
code: 'function foobar() { const FOOBAR = 5; return FOOBAR; }',
output: 'function foobar() { let FOOBAR = 5; return FOOBAR; }',
errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }]
}]
});
|
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require('../../../lib/rules/no-const-outside-module-scope');
var RuleTester = require('eslint').RuleTester;
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
}
});
ruleTester.run('no-const-outside-module-scope', rule, {
valid: [
'const FOOBAR = 5;',
'export const FOOBAR = 5;'
],
invalid: [{
code: '{ const FOOBAR = 5; }',
errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }]
}, {
code: 'function foobar() { const FOOBAR = 5; return FOOBAR; }',
errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }]
}]
});
|
Create Model with instances and securityGroups
|
package jp.ac.nii.prl.mape.monitoring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.SecurityGroup;
import jp.ac.nii.prl.mape.monitoring.model.Model;
import jp.ac.nii.prl.mape.monitoring.service.EC2Service;
import jp.ac.nii.prl.mape.monitoring.service.ModelService;
@RestController
@RequestMapping("/monitor")
@Component
public class MonitoringController {
@Autowired
private EC2Service ec2Service;
@Autowired
private ModelService modelService;
@RequestMapping(value="/instances", method=RequestMethod.GET)
public List<Instance> getInstances() {
return ec2Service.getInstances();
}
@RequestMapping(value="/securityGroups", method=RequestMethod.GET)
public List<SecurityGroup> getSecurityGroups() {
return ec2Service.getSecurityGroups();
}
@RequestMapping(method=RequestMethod.GET)
public Model getModel() {
return modelService.createModel(ec2Service.getInstances(), ec2Service.getSecurityGroups());
}
}
|
package jp.ac.nii.prl.mape.monitoring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.amazonaws.services.ec2.model.Instance;
import jp.ac.nii.prl.mape.monitoring.model.Model;
import jp.ac.nii.prl.mape.monitoring.service.EC2Service;
@RestController
@RequestMapping("/monitor")
@Component
public class MonitoringController {
@Autowired
private EC2Service ec2Service;
@RequestMapping(method=RequestMethod.GET)
public List<Instance> monitor() {
System.out.println("Here");
return ec2Service.getInstances();
}
}
|
Add python_requires to help pip
|
import os
from setuptools import setup
long_description = 'Please see our GitHub README'
if os.path.exists('README.txt'):
long_description = open('README.txt').read()
base_url = 'https://github.com/sendgrid/'
version = '3.1.0'
setup(
name='python_http_client',
version=version,
author='Elmer Thomas',
author_email='dx@sendgrid.com',
url='{}python-http-client'.format(base_url),
download_url='{}python-http-client/tarball/{}'.format(base_url, version),
packages=['python_http_client'],
license='MIT',
description='HTTP REST client, simplified for Python',
long_description=long_description,
keywords=[
'REST',
'HTTP',
'API'],
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
]
)
|
import os
from setuptools import setup
long_description = 'Please see our GitHub README'
if os.path.exists('README.txt'):
long_description = open('README.txt').read()
base_url = 'https://github.com/sendgrid/'
version = '3.1.0'
setup(
name='python_http_client',
version=version,
author='Elmer Thomas',
author_email='dx@sendgrid.com',
url='{}python-http-client'.format(base_url),
download_url='{}python-http-client/tarball/{}'.format(base_url, version),
packages=['python_http_client'],
license='MIT',
description='HTTP REST client, simplified for Python',
long_description=long_description,
keywords=[
'REST',
'HTTP',
'API'],
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
]
)
|
Fix relative references to assets
|
#!/usr/bin/env node
var fs = require('fs')
var html2png = require('html2png');
var path = require('path');
var command = path.basename(process.argv.slice(1));
var args = process.argv.slice(2);
if (args.length == 0) {
console.log('Usage: ' + command + ' [text]');
process.exit();
}
fs.readFile(__dirname + '/tweet.html', 'utf8', function(err, data) {
if (err) throw err;
data = data.replace(/YOLO/g, args.join(' '));
var screenshot = html2png({ width: 642, height: 280, browser: 'chrome'});
screenshot.render(data, function (err, data) {
if (err) throw err;
fs.writeFile(process.cwd() + "/tweet.png", data, function(err) {
if (err) throw err;
screenshot.close();
});
});
});
|
#!/usr/bin/env node
var fs = require('fs')
var html2png = require('html2png');
var path = require('path');
var command = path.basename(process.argv.slice(1));
var args = process.argv.slice(2);
if (args.length == 0) {
console.log('Usage: ' + command + ' [text]');
process.exit();
}
fs.readFile('tweet.html', 'utf8', function(err, data) {
if (err) throw err;
data = data.replace(/YOLO/g, args.join(' '));
var screenshot = html2png({ width: 642, height: 280, browser: 'chrome'});
screenshot.render(data, function (err, data) {
if (err) throw err;
fs.writeFile("tweet.png", data, function(err) {
if (err) throw err;
screenshot.close();
});
});
});
|
Add support for Arch Linux mathjax package
Fixes #4.
|
# This file is part of python-markups module
# License: 3-clause BSD, see LICENSE file
# Copyright: (C) Dmitry Shachnev, 2012-2018
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URLS = (
'file:///usr/share/javascript/mathjax/MathJax.js', # Debian libjs-mathjax
'file:///usr/share/mathjax/MathJax.js', # Arch Linux mathjax
)
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
if style is None:
style = PYGMENTS_STYLE
if style == '':
return ''
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter(style=style).get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if not webenv:
for url in MATHJAX_LOCAL_URLS:
if os.path.exists(url[7:]): # strip file://
return url
return MATHJAX_WEB_URL
|
# This file is part of python-markups module
# License: 3-clause BSD, see LICENSE file
# Copyright: (C) Dmitry Shachnev, 2012-2018
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
if style is None:
style = PYGMENTS_STYLE
if style == '':
return ''
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter(style=style).get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
return MATHJAX_LOCAL_URL
else:
return MATHJAX_WEB_URL
|
Test against a clause head and body
|
package golog
import "testing"
func TestAsserta(t *testing.T) {
db0 := NewDatabase()
db1 := db0.Asserta(NewTerm("alpha"))
db2 := db1.Asserta(NewTerm("beta"))
foo := NewTerm("foo", NewTerm("one"), NewTerm("two"))
body := NewTerm("alpha")
db3 := db2.Asserta(NewTerm(":-", foo, body))
t.Logf(db3.String()) // helpful for debugging
// do we have the right number of clauses?
if db0.ClauseCount() != 0 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db1.ClauseCount() != 1 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db2.ClauseCount() != 2 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db3.ClauseCount() != 3 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
}
|
package golog
import "testing"
func TestAsserta(t *testing.T) {
db0 := NewDatabase()
db1 := db0.Asserta(NewTerm("alpha"))
db2 := db1.Asserta(NewTerm("beta"))
db3 := db2.Asserta(NewTerm("gamma", NewTerm("greek to me")))
// do we have the right number of clauses?
if db0.ClauseCount() != 0 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db1.ClauseCount() != 1 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db2.ClauseCount() != 2 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
if db3.ClauseCount() != 3 {
t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
}
}
|
Remove app argument from init.
|
var debug = require('debug')('initialize');
function Initializer() {
this._phases = [];
}
Initializer.prototype.init = function(cb) {
var self = this
, phases = this._phases
, idx = 0;
function next(err) {
if (err) { return cb(err); }
var phase = phases[idx++];
// all done
if (!phase) { return cb && cb(); }
try {
debug('%s', phase.name || 'anonymous');
var arity = phase.length;
if (arity == 1) {
phase(next);
} else {
phase();
next();
}
} catch (ex) {
next(ex);
}
}
next();
}
Initializer.prototype.phase = function(fn) {
this._phases.push(fn);
}
module.exports = Initializer;
|
var debug = require('debug')('initialize');
function Initializer() {
this._phases = [];
}
Initializer.prototype.init = function(app, cb) {
var self = this
, phases = this._phases
, idx = 0;
function next(err) {
if (err) { return cb(err); }
var phase = phases[idx++];
// all done
if (!phase) { return cb && cb(); }
try {
debug('%s', phase.name || 'anonymous');
var arity = phase.length;
if (arity == 1) {
phase(next);
} else {
phase();
next();
}
} catch (ex) {
next(ex);
}
}
next();
}
Initializer.prototype.phase = function(fn) {
this._phases.push(fn);
}
module.exports = Initializer;
|
Bump version 0.2.1 -> 0.2.2
|
from setuptools import setup
from setuptools import find_packages
install_requires = [
'zeep>=1.6',
]
tests_require = [
'pytest>3',
'mock',
]
setup(
name='pyAEATsii',
version='0.2.2',
description='A python wrapper for the AEAT SII webservices',
author="Calidae S.L.",
author_email="dev@calidae.com",
url='http://www.calidae.com/',
download_url='https://github.com/calidae/python-aeat_sii',
install_requires=install_requires,
setup_requires=['pytest-runner'],
tests_require=tests_require,
extras_require={
'test': tests_require,
},
entry_points={},
package_dir={'': 'src'},
packages=find_packages('src'),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
from setuptools import setup
from setuptools import find_packages
install_requires = [
'zeep>=1.6',
]
tests_require = [
'pytest>3',
'mock',
]
setup(
name='pyAEATsii',
version='0.2.1',
description='A python wrapper for the AEAT SII webservices',
author="Calidae S.L.",
author_email="dev@calidae.com",
url='http://www.calidae.com/',
download_url='https://github.com/calidae/python-aeat_sii',
install_requires=install_requires,
setup_requires=['pytest-runner'],
tests_require=tests_require,
extras_require={
'test': tests_require,
},
entry_points={},
package_dir={'': 'src'},
packages=find_packages('src'),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
Add indexes to service migration
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;
class Service extends Migration
{
public function up()
{
$capsule = new Capsule();
$capsule::schema()->create('service', function (Blueprint $table) {
$table->increments('id');
$table->string('serial_number')->nullable();
$table->string('service_name');
$table->string('service_state');
$table->bigInteger('timestamp');
$table->index('serial_number');
$table->index('service_name');
$table->index('service_state');
});
}
public function down()
{
$capsule = new Capsule();
$capsule::schema()->dropIfExists('service');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;
class Service extends Migration
{
public function up()
{
$capsule = new Capsule();
$capsule::schema()->create('service', function (Blueprint $table) {
$table->increments('id');
$table->string('serial_number')->nullable();
$table->string('service_name');
$table->string('service_state');
$table->bigInteger('timestamp');
});
}
public function down()
{
$capsule = new Capsule();
$capsule::schema()->dropIfExists('service');
}
}
|
Change alias from F to E
|
package sack
import (
"fmt"
"github.com/codegangsta/cli"
)
func shellInit(c *cli.Context) {
sh := `
sack=$(which sack)
alias S="${sack} -s"
alias E="${sack} -e"
`
fmt.Println(sh)
}
func shellEval(c *cli.Context) {
sh := "eval \"$(sack init)\""
fmt.Println(sh)
}
/*
// TODO: Add bash and zsh autocomplete
CREDIT: https://github.com/codegangsta/cli/blob/master/autocomplete/bash_autocomplete
_cli_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts=$( ${COMP_WORDS[@]:0:COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete $PROG
*/
|
package sack
import (
"fmt"
"github.com/codegangsta/cli"
)
func shellInit(c *cli.Context) {
sh := `
sack=$(which sack)
alias S="${sack} -s"
alias F="${sack} -e"
`
fmt.Println(sh)
}
func shellEval(c *cli.Context) {
sh := "eval \"$(sack init)\""
fmt.Println(sh)
}
/*
// TODO: Add bash and zsh autocomplete
_cli_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts=$( ${COMP_WORDS[@]:0:COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete $PROG
*/
|
Fix missing implode() $glue parameter.
|
<?php
declare(strict_types=1);
/*
* This file is part of Badcow DNS Library.
*
* (c) Samuel Williams <sam@badcow.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Badcow\DNS\Parser;
class StringIterator extends \ArrayIterator
{
/**
* StringIterator constructor.
*
* @param string $string
*/
public function __construct(string $string = '')
{
parent::__construct(str_split($string));
}
/**
* @param string $value
*
* @return bool
*/
public function is(string $value): bool
{
return $value === $this->current();
}
/**
* @param string $value
*
* @return bool
*/
public function isNot(string $value): bool
{
return $value !== $this->current();
}
/**
* @return string
*/
public function __toString()
{
return implode('', $this->getArrayCopy());
}
}
|
<?php
declare(strict_types=1);
/*
* This file is part of Badcow DNS Library.
*
* (c) Samuel Williams <sam@badcow.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Badcow\DNS\Parser;
class StringIterator extends \ArrayIterator
{
/**
* StringIterator constructor.
*
* @param string $string
*/
public function __construct(string $string = '')
{
parent::__construct(str_split($string));
}
/**
* @param string $value
*
* @return bool
*/
public function is(string $value): bool
{
return $value === $this->current();
}
/**
* @param string $value
*
* @return bool
*/
public function isNot(string $value): bool
{
return $value !== $this->current();
}
/**
* @return string
*/
public function __toString()
{
return implode($this->getArrayCopy());
}
}
|
Fix regeneratorRuntime missing in tests
|
module.exports = api => {
api.cache(true);
const presets = [
[
'@babel/preset-env',
process.env.NODE_ENV === 'test'
? {
useBuiltIns: 'usage', // for regeneratorRuntime
}
: {
modules: false,
},
],
'@babel/preset-react',
'@babel/preset-typescript',
];
const plugins = ['@babel/plugin-proposal-class-properties'];
return {
presets,
plugins,
};
};
|
module.exports = api => {
api.cache(true);
const presets = [
[
'@babel/preset-env',
process.env.NODE_ENV === 'test'
? {}
: {
modules: false,
},
],
'@babel/preset-react',
'@babel/preset-typescript',
];
const plugins = ['@babel/plugin-proposal-class-properties'];
return {
presets,
plugins,
};
};
|
Fix warning if children is null
|
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import styles from './Base.module.css';
const renderLabel = label => {
if (typeof label === 'undefined') {
return null;
}
return <div className={styles.label}>{label}</div>;
};
const renderCount = count => {
if (typeof count === 'undefined') {
return null;
}
return <div className={styles.count}>{count}</div>;
};
const Base = ({ className, style, children, label, count, onClick }) => (
<div
className={cn(className, styles.container)}
style={style}
onClick={onClick}
>
<div>{children}</div>
{renderLabel(label)}
{renderCount(count)}
</div>
);
Base.propTypes = {
className: PropTypes.string,
children: PropTypes.node,
label: PropTypes.string,
count: PropTypes.number,
style: PropTypes.object,
onClick: PropTypes.func,
};
export default Base;
|
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import styles from './Base.module.css';
const renderLabel = label => {
if (typeof label === 'undefined') {
return null;
}
return <div className={styles.label}>{label}</div>;
};
const renderCount = count => {
if (typeof count === 'undefined') {
return null;
}
return <div className={styles.count}>{count}</div>;
};
const Base = ({ className, style, children, label, count, onClick }) => (
<div
className={cn(className, styles.container)}
style={style}
onClick={onClick}
>
<div>{children}</div>
{renderLabel(label)}
{renderCount(count)}
</div>
);
Base.propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
label: PropTypes.string,
count: PropTypes.number,
style: PropTypes.object,
onClick: PropTypes.func,
};
export default Base;
|
Fix public cacheBy for domain model.
|
<?php
namespace Websanova\EasyCache\Models;
class Domain extends BaseModel
{
protected $table = 'websanova_easycache_domains';
protected $cacheKey = 'domains';
public $cacheBy = 'slug';
public $timestamps = false;
public function slug()
{
return $this->select('*');
}
public function items()
{
return $this->hasMany('\Websanova\EasyCache\Models\Item');
}
public function comments()
{
return $this->hasMany('\Websanova\EasyCache\Models\Comment');
}
public function recountItems()
{
return $this->items()->active();
}
public function recountComments()
{
return $this->comments()->active();
}
}
|
<?php
namespace Websanova\EasyCache\Models;
class Domain extends BaseModel
{
protected $table = 'websanova_easycache_domains';
protected $cacheKey = 'domains';
protected $cacheBy = 'slug';
public $timestamps = false;
public function slug()
{
return $this->select('*');
}
public function items()
{
return $this->hasMany('\Websanova\EasyCache\Models\Item');
}
public function comments()
{
return $this->hasMany('\Websanova\EasyCache\Models\Comment');
}
public function recountItems()
{
return $this->items()->active();
}
public function recountComments()
{
return $this->comments()->active();
}
}
|
Add a couple more tags.
|
'use strict';
module.exports.generic = require('./generic');
module.exports.everything = module.exports.generic('everything','everything');
module.exports.outcome = module.exports.generic('outcome');
module.exports.outcome.success = module.exports.outcome('success');
module.exports.outcome.failure = module.exports.outcome('failure');
module.exports.outcome.timeout = module.exports.outcome('timeout');
module.exports.protocol = module.exports.generic('protocol');
module.exports.service = module.exports.generic('service');
module.exports.serviceCall = module.exports.generic('service-call');
module.exports.api = module.exports.generic('api');
module.exports.apiCall = module.exports.generic('api-call');
module.exports.testcase = module.exports.generic('testcase');
module.exports.testcaseCompletion = module.exports.generic('testcaseCompletion');
module.exports.section = module.exports.generic('section');
module.exports.sectionCompletion = module.exports.generic('sectionCompletion');
module.exports.raw = require('./raw');
|
'use strict';
module.exports.generic = require('./generic');
module.exports.outcome = module.exports.generic('outcome');
module.exports.outcome.success = module.exports.outcome('success');
module.exports.outcome.failure = module.exports.outcome('failure');
module.exports.outcome.timeout = module.exports.outcome('timeout');
module.exports.protocol = module.exports.generic('protocol');
module.exports.service = module.exports.generic('service');
module.exports.api = module.exports.generic('api');
module.exports.apicall = module.exports.generic('apicall');
module.exports.testcase = module.exports.generic('testcase');
module.exports.testcaseCompletion = module.exports.generic('testcaseCompletion');
module.exports.section = module.exports.generic('section');
module.exports.sectionCompletion = module.exports.generic('sectionCompletion');
module.exports.raw = require('./raw');
|
Add comment about toggling devtools
|
const {Menu} = require('electron')
const menubar = require('menubar')
// Toggle with cmd + alt + i
require('electron-debug')({showDevTools: true})
const mb = menubar({
width: 220,
height: 206,
preloadWindow: true,
icon: `${__dirname}/img/icon-0-Template.png`
})
// Make menubar accessible to the renderer
global.sharedObject = {mb}
mb.on('ready', () => {
console.log('app is ready')
})
mb.on('after-create-window', () => {
mb.window.loadURL(`file://${__dirname}/index.html`)
const contextMenu = Menu.buildFromTemplate([
{label: 'Quit', click: () => {
mb.app.quit()
}}
])
mb.tray.on('right-click', () => {
mb.tray.popUpContextMenu(contextMenu)
})
})
|
const {Menu} = require('electron')
const menubar = require('menubar')
require('electron-debug')({showDevTools: true});
const mb = menubar({
width: 220,
height: 206,
preloadWindow: true,
icon: `${__dirname}/img/icon-0-Template.png`
})
// Make menubar accessible to the renderer
global.sharedObject = {mb}
mb.on('ready', () => {
console.log('app is ready')
})
mb.on('after-create-window', () => {
mb.window.loadURL(`file://${__dirname}/index.html`)
const contextMenu = Menu.buildFromTemplate([
{label: 'Quit', click: () => {
mb.app.quit()
}}
])
mb.tray.on('right-click', () => {
mb.tray.popUpContextMenu(contextMenu)
})
})
|
Add compress: false for proper results.
|
var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false, compress: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
|
var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
|
Use /wm/device/all/json for all devices and /*** where *** is a filter by mac, vlan, ip, etc
|
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.devicemanager.web;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;
import net.floodlightcontroller.restserver.RestletRoutable;
/**
* Routable for device rest api
*/
public class DeviceRoutable implements RestletRoutable {
@Override
public String basePath() {
return "/wm/device";
}
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("/all/json", DeviceResource.class);
router.attach("/", DeviceResource.class);
router.attach("/debug", DeviceEntityResource.class);
return router;
}
}
|
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.devicemanager.web;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;
import net.floodlightcontroller.restserver.RestletRoutable;
/**
* Routable for device rest api
*/
public class DeviceRoutable implements RestletRoutable {
@Override
public String basePath() {
return "/wm/device";
}
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("/json", DeviceResource.class);
router.attach("/debug", DeviceEntityResource.class);
return router;
}
}
|
Fix reading values of username and password from the basic authwntication form
Wrong selectors were used.
|
'use strict';
SwaggerUi.Views.BasicAuthButton = Backbone.View.extend({
initialize: function (opts) {
this.options = opts || {};
this.router = this.options.router;
},
render: function(){
var template = this.template();
$(this.el).html(template(this.model));
return this;
},
events: {
'click #basic_auth_button' : 'togglePasswordContainer',
'click #apply_basic_auth' : 'applyPassword'
},
applyPassword: function(){
var username = $('#input_username').val();
var password = $('#input_password').val();
var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
this.router.api.clientAuthorizations.add(this.model.type, basicAuth);
this.router.load();
$('#basic_auth_container').hide();
},
togglePasswordContainer: function(){
if ($('#basic_auth_container').length) {
var elem = $('#basic_auth_container').show();
if (elem.is(':visible')){
elem.slideUp();
} else {
// hide others
$('.auth_container').hide();
elem.show();
}
}
},
template: function(){
return Handlebars.templates.basic_auth_button_view;
}
});
|
'use strict';
SwaggerUi.Views.BasicAuthButton = Backbone.View.extend({
initialize: function (opts) {
this.options = opts || {};
this.router = this.options.router;
},
render: function(){
var template = this.template();
$(this.el).html(template(this.model));
return this;
},
events: {
'click #basic_auth_button' : 'togglePasswordContainer',
'click #apply_basic_auth' : 'applyPassword'
},
applyPassword: function(){
var username = $('.input_username').val();
var password = $('.input_password').val();
var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
this.router.api.clientAuthorizations.add(this.model.type, basicAuth);
this.router.load();
$('#basic_auth_container').hide();
},
togglePasswordContainer: function(){
if ($('#basic_auth_container').length) {
var elem = $('#basic_auth_container').show();
if (elem.is(':visible')){
elem.slideUp();
} else {
// hide others
$('.auth_container').hide();
elem.show();
}
}
},
template: function(){
return Handlebars.templates.basic_auth_button_view;
}
});
|
Use N4JDB.query to create a (:Meteo4j {name: 'hello world'}) node
|
if (Meteor.isServer) {
// Check if there are any nodes with the Meteo4J label in the
// database, using a standard cypher query
var label = "Meteo4j"
var cypher = "MATCH (n:" + label + ") RETURN n"
var options = null
Meteor.N4JDB.query(cypher, options, matchCallback)
function matchCallback(error, nodeArray) {
console.log(error, nodeArray)
if (error) {
return console.log(error)
}
// There are no nodes, create one
if (!nodeArray.length) {
cypher = "CREATE (n:" + label + " {name: 'hello world'})"
Meteor.N4JDB.query(cypher, options, createCallback)
function createCallback(error, resultArray) {
if (error) {
return console.error('New node not created:', error)
// { [Error: Unexpected end of input: expected whitespace, ')' or a relationship pattern...
}
//console.log(result) // []
// The node is ready to use. See it at...
// http://localhost:7474/browser/
// ... using the query:
// MATCH (n:Meteo4j) RETURN n
}
}
}
}
|
if (Meteor.isServer) {
// Check if there are any nodes at all in the database
var query = 'MATCH (n) RETURN n'
var options = null
Meteor.N4JDB.query(query, options, callback) // output is undefined
// The database sends its response to a callback
function callback(error, nodeArray) {
console.log(error, nodeArray) // JSON.stringify(nodeArray))
// null
// [{ n: { db: [Object], _request: [Object], _data: [Object] } }]
if (error) {
return console.log(error)
}
if (!nodeArray.length) {
var node = Meteor.N4JDB.createNode({name: 'hello world'})
// node is not saved to the database: you must manually save it
node.save(function (error, savedNode) {
if (error) {
return console.error('New node not saved:', error)
}
// The node is ready to use. See it at...
// http://localhost:7474/browser/
// ... using the query:
// MATCH (n) RETURN n
})
}
}
}
|
Clarify error if otp is wrong
|
#!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for blimp: ' + domain_req_url)
r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp})
if r.status_code == 200:
print('Success: %s' % r.text)
result_dict = r.json()
if "domain" in result_dict:
with open(domain_txt_path, 'w') as domain_txt_file:
domain_txt_file.write(result_dict['domain'])
quit(0)
else:
quit(1)
else:
print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text)
quit(1)
|
#!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for blimp: ' + domain_req_url)
r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp})
if r.status_code == 200:
print('Success: %s' % r.text)
result_dict = r.json()
if "domain" in result_dict:
with open(domain_txt_path, 'w') as domain_txt_file:
domain_txt_file.write(result_dict['domain'])
quit(0)
else:
quit(1)
else:
print('Error: %s' % r.text)
quit(1)
|
Load block styles via amp_post_template_head action
|
<?php
/**
* Load the reader mode template.
*
* @package AMP
*/
/**
* Queried post.
*
* @global WP_Post $post
*/
global $post;
// Populate the $post without calling the_post() to prevent entering The Loop. This ensures that templates which
// contain The Loop will still loop over the posts. Otherwise, if a template contains The Loop then calling the_post()
// here will advance the WP_Query::$current_post to the next_post. See WP_Query::the_post().
$post = get_queried_object(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
setup_postdata( $post );
/**
* Fires before rendering a post in AMP.
*
* This action is not triggered when 'amp' theme support is present. Instead, you should use 'template_redirect' action and check if `is_amp_endpoint()`.
*
* @since 0.2
*
* @param int $post_id Post ID.
*/
do_action( 'pre_amp_render_post', get_queried_object_id() );
require_once AMP__DIR__ . '/includes/amp-post-template-functions.php';
amp_post_template_init_hooks();
// Support and load Core block styles.
current_theme_supports( 'wp-block-styles' );
add_action(
'amp_post_template_head',
static function () {
global $wp_styles;
wp_common_block_scripts_and_styles();
$wp_styles->do_items();
}
);
$amp_post_template = new AMP_Post_Template( get_queried_object_id() );
$amp_post_template->load();
|
<?php
/**
* Load the reader mode template.
*
* @package AMP
*/
/**
* Queried post.
*
* @global WP_Post $post
*/
global $post;
// Populate the $post without calling the_post() to prevent entering The Loop. This ensures that templates which
// contain The Loop will still loop over the posts. Otherwise, if a template contains The Loop then calling the_post()
// here will advance the WP_Query::$current_post to the next_post. See WP_Query::the_post().
$post = get_queried_object(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
setup_postdata( $post );
/**
* Fires before rendering a post in AMP.
*
* This action is not triggered when 'amp' theme support is present. Instead, you should use 'template_redirect' action and check if `is_amp_endpoint()`.
*
* @since 0.2
*
* @param int $post_id Post ID.
*/
do_action( 'pre_amp_render_post', get_queried_object_id() );
require_once AMP__DIR__ . '/includes/amp-post-template-functions.php';
amp_post_template_init_hooks();
$amp_post_template = new AMP_Post_Template( get_queried_object_id() );
$amp_post_template->load();
|
Use gulp to generate one app.css, and separate 'fonts' task
|
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('default', ['sass', 'fonts'], function () {
});
gulp.task('sass', function () {
return gulp.src('./styles/warriormachines_2016/theme/sass/app.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css'));
});
gulp.task('fonts', function() {
gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}')
.pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts'));
});
gulp.task('sass:watch', function () {
gulp.watch('./styles/warriormachines_2016/theme/sass/app.scss', ['sass']);
});
|
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('default', ['sass'], function () {
//gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}')
// .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts'));
});
gulp.task('sass', function () {
return gulp.src('./styles/warriormachines_2016/theme/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./styles/warriormachines_2016/theme/sass/*.scss', ['sass']);
});
|
Add react production mode support in webpack
|
let webpack = require('webpack');
let path = require('path');
let BUILD_DIR = path.resolve(__dirname, 'client/dist');
let APP_DIR = path.resolve(__dirname, 'client/src');
// console.log("path.resolve()", path.resolve());
// console.log("path.resolve(__dirname)", path.resolve(__dirname));
// console.log("BUILD_DIR", BUILD_DIR);
let config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel'
},
{test: /\.css/, loader: 'style-loader!css-loader'},
{test: /\.less$/, loader: 'style!css!less'},
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
};
module.exports = config;
|
let webpack = require('webpack');
let path = require('path');
let BUILD_DIR = path.resolve(__dirname, 'client/dist');
let APP_DIR = path.resolve(__dirname, 'client/src');
// console.log("path.resolve()", path.resolve());
// console.log("path.resolve(__dirname)", path.resolve(__dirname));
// console.log("BUILD_DIR", BUILD_DIR);
let config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel'
},
{test: /\.css/, loader: 'style-loader!css-loader'},
{test: /\.less$/, loader: 'style!css!less'},
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
}
};
module.exports = config;
|
Add more verbose error to reporte on Travis parserXML.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
element=root.findall('.//FatalError')[0]
eprint("Error detected")
print(infile)
print(element.text)
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
print(infile)
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
Fix for sticking virtual keys
|
/*
* Copyright 2012 Kulikov Dmitriy
* Copyright 2017 Nikita Shakarun
*
* 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 javax.microedition.util;
public class ArrayStack<E> {
public static final int DELTA = 100;
private Object[] data;
private int index;
public ArrayStack() {
clear();
}
public synchronized void push(E value) {
if (index >= data.length - 1) {
Object[] temp = new Object[data.length + DELTA];
System.arraycopy(data, 0, temp, 0, data.length);
data = temp;
}
data[++index] = value;
}
public synchronized E pop() {
if (index < 0) {
return null;
}
return (E) data[index--];
}
public synchronized void clear() {
data = new Object[0];
index = -1;
}
}
|
/*
* Copyright 2012 Kulikov Dmitriy
* Copyright 2017 Nikita Shakarun
*
* 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 javax.microedition.util;
public class ArrayStack<E> {
public static final int DELTA = 100;
protected Object[] data;
protected int index;
public ArrayStack() {
clear();
}
public void push(E value) {
if (index >= data.length - 1) {
Object[] temp = new Object[data.length + DELTA];
System.arraycopy(data, 0, temp, 0, data.length);
data = temp;
}
data[++index] = value;
}
public E pop() {
if (index < 0) {
return null;
}
return (E) data[index--];
}
public void clear() {
data = new Object[0];
index = -1;
}
}
|
Use "\n" to fix waiting for prompt in feature tests on CI
|
import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
ENTER = "\n"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the interactive command')
def step_impl(context):
process = pexpect.spawn(context.text)
time.sleep(0.5)
type(process, ENTER)
class Output(object):
pass
context.output = Output()
context.output.stderr = ""
context.output.stdout = ""
context.process = process
@when(u'I type')
def step_impl(context):
cmd = context.text.strip() + "\n"
context.output.stdout = type(context.process, cmd)
@when(u'I exit the shell')
def step_impl(context):
context.process.send("exit\n")
|
import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
UP_ARROW = "\x1b[A"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', process.before).strip()
@when(u'I run the interactive command')
def step_impl(context):
process = pexpect.spawn(context.text)
time.sleep(0.5)
type(process, UP_ARROW)
class Output(object):
pass
context.output = Output()
context.output.stderr = ""
context.output.stdout = ""
context.process = process
@when(u'I type')
def step_impl(context):
cmd = context.text.strip() + "\n"
context.output.stdout = type(context.process, cmd)
@when(u'I exit the shell')
def step_impl(context):
context.process.send("exit\n")
|
Fix incorrect login url for sign in form on frontpage
|
<form name="loginform" action="<?php echo wp_login_url(home_url());?>" method="post">
<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
<input type="hidden" name="user-cookie" value="1" />
<p>
<input type="text" name="log" placeholder="E-postadress eller nick"
<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
/>
<input type="password" name="pwd" placeholder="Lösenord" />
</p>
<p>
<label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
Håll mig inloggad</label>
<input type="submit" name="submit" class="small" value="Logga in" />
</p>
</form>
|
<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
<input type="hidden" name="user-cookie" value="1" />
<p>
<input type="text" name="log" placeholder="E-postadress eller nick"
<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
/>
<input type="password" name="pwd" placeholder="Lösenord" />
</p>
<p>
<label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
Håll mig inloggad</label>
<input type="submit" name="submit" class="small" value="Logga in" />
</p>
</form>
|
Fix for modules with null [[Prototype]] chain
A module created in the following ways:
module.exports = Object.create(null)
module.exports = { __proto__: null }
won't have hasOwnProperty() available on it.
So it’s safer to use Object.prototype.hasOwnProperty.call(myObj, prop)
instead of myObj.hasOwnProperty(prop)
|
'use strict';
var isReactClassish = require('./isReactClassish'),
isReactElementish = require('./isReactElementish');
function makeExportsHot(m) {
if (isReactElementish(m.exports)) {
return false;
}
var freshExports = m.exports,
foundReactClasses = false;
if (isReactClassish(m.exports)) {
m.exports = m.makeHot(m.exports, '__MODULE_EXPORTS');
foundReactClasses = true;
}
for (var key in m.exports) {
if (Object.prototype.hasOwnProperty.call(freshExports, key) &&
isReactClassish(freshExports[key])) {
if (Object.getOwnPropertyDescriptor(m.exports, key).writable) {
m.exports[key] = m.makeHot(freshExports[key], '__MODULE_EXPORTS_' + key);
foundReactClasses = true;
} else {
console.warn("Can't make class " + key + " hot reloadable due to being read-only. You can exclude files or directories (for example, /node_modules/) using 'exclude' option in loader configuration.");
}
}
}
return foundReactClasses;
}
module.exports = makeExportsHot;
|
'use strict';
var isReactClassish = require('./isReactClassish'),
isReactElementish = require('./isReactElementish');
function makeExportsHot(m) {
if (isReactElementish(m.exports)) {
return false;
}
var freshExports = m.exports,
foundReactClasses = false;
if (isReactClassish(m.exports)) {
m.exports = m.makeHot(m.exports, '__MODULE_EXPORTS');
foundReactClasses = true;
}
for (var key in m.exports) {
if (freshExports.hasOwnProperty(key) &&
isReactClassish(freshExports[key])) {
if (Object.getOwnPropertyDescriptor(m.exports, key).writable) {
m.exports[key] = m.makeHot(freshExports[key], '__MODULE_EXPORTS_' + key);
foundReactClasses = true;
} else {
console.warn("Can't make class " + key + " hot reloadable due to being read-only. You can exclude files or directories (for example, /node_modules/) using 'exclude' option in loader configuration.");
}
}
}
return foundReactClasses;
}
module.exports = makeExportsHot;
|
Set git author on Travis
|
import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
await exec(
[
'git commit',
`--author 'Vinson Chuong <vinsonchuong@gmail.com>'`,
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
|
import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
await exec(
`git commit -m 'Automatically update dependencies' package.json`,
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
|
Improve mongo logging, so we only log unexpected disconnects.
This cleans things up a bit so normal shutdown doesn't spew mongo
disconnect errors.
|
'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function(error) {
var logEvent = true;
if(event === 'disconnecting') {
mongoose.expectedCloseInProgress = true;
}
if(mongoose.expectedCloseInProgress) {
if(event === 'disconnecting' || event === 'disconnected' || event === 'close') {
logEvent = false;
}
}
if(event === 'close') {
mongoose.expectedCloseInProgress = false;
}
if(logEvent) {
logger.error('Mongo event: ' + event, error);
}
});
});
module.exports = function(callback) {
var config = require('api-umbrella-config').global();
// Connect to mongo using mongoose.
//
// Note: For this application, we don't particularly need an ODM like
// Mongoose, and the lower-level mongodb driver would meet our needs.
// However, when using the standalone driver, we were experiencing
// intermittent mongo connection drops in staging and production
// environments. I can't figure out how to reproduce the original issue in a
// testable way, so care should be taken if switching how mongo connects. See
// here for more details: https://github.com/NREL/api-umbrella/issues/17
mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};
|
'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function() {
logger.error('Mongo '+ event, arguments);
});
});
module.exports = function(callback) {
var config = require('api-umbrella-config').global();
// Connect to mongo using mongoose.
//
// Note: For this application, we don't particularly need an ODM like
// Mongoose, and the lower-level mongodb driver would meet our needs.
// However, when using the standalone driver, we were experiencing
// intermittent mongo connection drops in staging and production
// environments. I can't figure out how to reproduce the original issue in a
// testable way, so care should be taken if switching how mongo connects. See
// here for more details: https://github.com/NREL/api-umbrella/issues/17
mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};
|
Add contribute.json to the nickname blacklist
Ref #1535
|
// nicknameblacklist.js
//
// list of banished nicknames
//
// Copyright 2017, Ryan Riddle
//
// 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.
"use strict";
module.exports = ["api",
"oauth",
"public",
"robots.txt",
"humans.txt",
".well-known",
"sitemap.xml",
"favicon.ico",
"contribute.json"];
|
// nicknameblacklist.js
//
// list of banished nicknames
//
// Copyright 2017, Ryan Riddle
//
// 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.
"use strict";
module.exports = ["api",
"oauth",
"public",
"robots.txt",
"humans.txt",
".well-known",
"sitemap.xml",
"favicon.ico"];
|
Add checking whether Error has the property 'captureStackTrace'
|
/**
* Copyright 2015 Jaime Pajuelo
*
* 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.
*/
"use strict";
fmval.validators.ValidationError = (function () {
/**
* @constructor
* @param {String} message
*/
var ValidationError = function ValidationError(message) {
if (this.parentClass.hasOwnProperty('captureStackTrace')) {
this.parentClass.captureStackTrace(this, this.constructor);
}
this.message = message;
this.element = document.createElement('p');
this.element.className = "control-error";
this.element.textContent = message;
};
ValidationError.inherit(Error);
/**
* @type {String}
*/
ValidationError.member('name', "ValidationError");
return ValidationError;
})();
|
/**
* Copyright 2015 Jaime Pajuelo
*
* 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.
*/
"use strict";
fmval.validators.ValidationError = (function () {
/**
* @constructor
* @param {String} message
*/
var ValidationError = function ValidationError(message) {
this.parentClass.captureStackTrace(this, this.constructor);
this.message = message;
this.element = document.createElement('p');
this.element.className = "control-error";
this.element.textContent = message;
};
ValidationError.inherit(Error);
/**
* @type {String}
*/
ValidationError.member('name', "ValidationError");
return ValidationError;
})();
|
Use sync storage instead of local storage
|
// if you checked "fancy-settings" in extensionizr.com, uncomment this lines
// var settings = new Store("settings", {
// "sample_setting": "This is how you use Store.js to remember values"
// });
function generateUUID() {
let id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return id;
}
const defaults = {
id: generateUUID(),
username: "test-user",
};
class StorageService {
constructor() {
this.storage = chrome.storage.sync;
this.storage.get(defaults, (items) => {
this.storage.set(items);
})
}
reset() {
this.storage.clear(() => {
defaults.id = generateUUID();
this.set(defaults);
});
}
get(key) {
return new Promise((resolve) => {
this.storage.get(key, (item) => {
resolve(item[key]);
});
});
}
set(key, value) {
let data = {};
data[key] = value;
this.storage.set(data);
}
remove(key) {
this.storage.remove(key);
}
}
window.BackgroundStorageService = new StorageService();
|
// if you checked "fancy-settings" in extensionizr.com, uncomment this lines
// var settings = new Store("settings", {
// "sample_setting": "This is how you use Store.js to remember values"
// });
function generateUUID() {
let id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return id;
}
const defaults = {
id: generateUUID(),
username: "test-user",
};
class StorageService {
constructor() {
this.storage = chrome.storage.local;
this.storage.get(defaults, (items) => {
this.storage.set(items);
})
}
reset() {
this.storage.clear(() => {
defaults.id = generateUUID();
this.set(defaults);
});
}
get(key) {
return new Promise((resolve) => {
this.storage.get(key, (item) => {
resolve(item[key]);
});
});
}
set(key, value) {
let data = {};
data[key] = value;
this.storage.set(data);
}
remove(key) {
this.storage.remove(key);
}
}
window.BackgroundStorageService = new StorageService();
|
Add statusActions arg to remote call sig
|
/**
RemoteCall
@description function that makes the remote call using the fetch polyfill,
running a series of provided lifecycle hooks
@exports @default {function} callRemoteResource
**/
/* eslint no-unused-vars:0 */
// TODO: should probably use a global fetch instance if we can
import fetch from 'isomorphic-fetch';
/**
@private
@name callRemoteResource
@desc makes a call using the fetch API w/ the given request data & hooks
@param {object} request
@param {string} request.uri
@param {string} request.method
@param {object} request.headers
@param {string} request.body
@param {object} request.requestOps arbitrary options passed to fetch
@param {array} statusActions an array of objects w/ code & callback keys
@param {object} hooks the lifecycle hooks evaluated at various times
@param {function} hooks.onBeforeCall
@param {function} hooks.onCallSuccess(data, response)
@param {function} hooks.onCallFailure(statusCode, data, response)
**/
export default function callRemoteResource(request, statusActions, hooks) {
return null;
}
|
/**
RemoteCall
@description function that makes the remote call using the fetch polyfill,
running a series of provided lifecycle hooks
@exports @default {function} callRemoteResource
**/
/* eslint no-unused-vars:0 */
// TODO: should probably use a global fetch instance if we can
import fetch from 'isomorphic-fetch';
/**
@private
@name callRemoteResource
@desc makes a call using the fetch API w/ the given request data & hooks
@param {object} request
@param {string} request.uri
@param {string} request.method
@param {object} request.headers
@param {string} request.body
@param {object} request.requestOps arbitrary options passed to fetch
@param {object} hooks the lifecycle hooks evaluated at various times
@param {function} hooks.onBeforeCall
@param {function} hooks.onCallSuccess(data, response)
@param {function} hooks.onCallFailure(statusCode, data, response)
**/
export default function callRemoteResource(request, hooks) {
return null;
}
|
Use non-reserved user table name
|
package com.maddogs.domain;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;
@Entity
@Table(name = "tuser")
public class User extends PersistableDomainObject{
private String name;
private String email;
private String password;
@OneToMany
private List<Tag> tags;
@OneToMany
private List<Run> runs;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public List<Run> getRuns() {
return runs;
}
public void setRuns(List<Run> runs) {
this.runs = runs;
}
}
|
package com.maddogs.domain;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import java.util.List;
@Entity
public class User extends PersistableDomainObject{
private String name;
private String email;
private String password;
@OneToMany
private List<Tag> tags;
@OneToMany
private List<Run> runs;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public List<Run> getRuns() {
return runs;
}
public void setRuns(List<Run> runs) {
this.runs = runs;
}
}
|
Configure Enzyme for React 16.
|
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
/*
Setup and takedown
*/
function createMountNode ({ context, mountNodeId }) {
const internalmountNodeId = mountNodeId || 'mount-node';
context.dom = document.createElement('div');
const mountNode = document.body.appendChild(context.dom);
mountNode.id = internalmountNodeId;
return mountNode;
}
const mountComponent = (instance) =>
function () {
this.dom = document.createElement('div');
const mountNode = document.body.appendChild(this.dom);
mountNode.id = 'mount-node';
this.wrapper = mount(instance, { attachTo: mountNode });
};
function unmountComponent () {
this.wrapper.unmount();
document.body.removeChild(this.dom);
}
function destroyMountNode ({ wrapper, mountNode }) {
wrapper.unmount();
document.body.removeChild(mountNode);
}
export { createMountNode, destroyMountNode, mountComponent, unmountComponent };
|
import { mount } from 'enzyme';
/*
Setup and takedown
*/
function createMountNode ({ context, mountNodeId }) {
const internalmountNodeId = mountNodeId || 'mount-node';
context.dom = document.createElement('div');
const mountNode = document.body.appendChild(context.dom);
mountNode.id = internalmountNodeId;
return mountNode;
}
const mountComponent = (instance) =>
function () {
this.dom = document.createElement('div');
const mountNode = document.body.appendChild(this.dom);
mountNode.id = 'mount-node';
this.wrapper = mount(instance, { attachTo: mountNode });
};
function unmountComponent () {
this.wrapper.unmount();
document.body.removeChild(this.dom);
}
function destroyMountNode ({ wrapper, mountNode }) {
wrapper.unmount();
document.body.removeChild(mountNode);
}
export { createMountNode, destroyMountNode, mountComponent, unmountComponent };
|
Reduce print statement console clustering
|
#!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import lexer, parser, env
TEA_VERSION = "0.0.5-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, parsing and evaluating."""
if expression == "exit":
context.flags.append("exit")
return
try:
tokens = lexer.run(expression)
#print('Generated tokens:', ', '.join((str(e) for e in tokens)))
tree = parser.generate(tokens)
#print(tree)
return tree.eval(context).data
except Exception as e:
return str(e)
def main():
"""Run the CLI."""
# print application title
print(TEA_TITLE)
# run REPL
context = env.empty_context()
context.load(runtime.lib)
while "done" not in context.flags:
output = interpret(input(CLI_SYMBOL), context)
while "continue" in context.flags:
output = interpret(input(CLI_SPACE), context)
if "exit" in context.flags:
return
print(output)
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import lexer, parser, env
TEA_VERSION = "0.0.5-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, parsing and evaluating."""
if expression == "exit":
context.flags.append("exit")
return
tokens = lexer.run(expression)
print('Generated tokens:', ', '.join((str(e) for e in tokens)))
tree = parser.generate(tokens)
print(tree)
return tree.eval(context).data
def main():
"""Run the CLI."""
# print application title
print(TEA_TITLE)
# run REPL
context = env.empty_context()
context.load(runtime.lib)
while "done" not in context.flags:
output = interpret(input(CLI_SYMBOL), context)
while "continue" in context.flags:
output = interpret(input(CLI_SPACE), context)
if "exit" in context.flags:
return
print(output)
if __name__ == "__main__":
main()
|
Fix the database session init to work with the flask debug server.
The debug webserver consists of two parts: the watcher that watches
the files for changes and the worker that is forked and will be restarted
after each modification. Sqlachemy uses a SingletonPool that will not
work with this if the database was initialized within the watcher.
See [1] for more detailed information.
[1] http://docs.sqlalchemy.org/en/rel_0_8/dialects/sqlite.html#threading-pooling-behavior
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import StaticPool
session = None
def init_session(connection_string=None, drop=False):
if connection_string is None:
engine = create_engine('sqlite://',
echo=True,
connect_args={'check_same_thread':False},
poolclass=StaticPool)
else:
engine = create_engine(connection_string)
from database.model import Base
global session
if drop:
try:
old_session = session
Base.metadata.drop_all(bind=old_session.bind)
except:
pass
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base.metadata.create_all(bind=engine)
session = db_session
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
session = None
def init_session(connection_string=None, drop=False):
if connection_string is None:
connection_string = 'sqlite://'
from database.model import Base
global session
if drop:
try:
old_session = session
Base.metadata.drop_all(bind=old_session.bind)
except:
pass
engine = create_engine(connection_string, echo=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base.metadata.create_all(bind=engine)
session = db_session
|
Revert "populate the name in the event list"
This reverts commit 26cdf5c120aece5d7d1db2e21610bb46eaf35c30.
|
/**
* This file is licensed under the University of Illinois/NCSA Open Source License. See LICENSE.TXT for details.
*/
package edu.illinois.codingtracker.operations;
import java.util.Date;
import org.eclipse.core.runtime.AssertionFailedException;
import org.eclipse.ui.IEditorPart;
import edu.illinois.codingtracker.helpers.Configuration;
import edu.illinois.codingtracker.helpers.Debugger;
/**
*
* @author Stas Negara
*
*/
public class Event {
//Made public to be able to assign when the replayer is loaded/reset
private String eventName = "";
private long timestamp;
public Event() {
timestamp= System.currentTimeMillis();
}
public Event(long timestamp) {
this.timestamp= timestamp;
}
public long getTime() {
return timestamp;
}
public Date getDate() {
return new Date(timestamp);
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getDescription() {
return "";
}
@Override
public String toString() {
return eventName + " (" + timestamp + ")";
}
}
|
/**
* This file is licensed under the University of Illinois/NCSA Open Source License. See LICENSE.TXT for details.
*/
package edu.illinois.codingtracker.operations;
import java.util.Date;
import org.eclipse.core.runtime.AssertionFailedException;
import org.eclipse.ui.IEditorPart;
import edu.illinois.codingtracker.helpers.Configuration;
import edu.illinois.codingtracker.helpers.Debugger;
/**
*
* @author Stas Negara
*
*/
public class Event {
//Made public to be able to assign when the replayer is loaded/reset
private String eventName = "";
private long timestamp;
public Event() {
timestamp= System.currentTimeMillis();
}
public Event(long timestamp) {
this.timestamp= timestamp;
}
public long getTime() {
return timestamp;
}
public Date getDate() {
return new Date(timestamp);
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getDescription() {
return getEventName();
}
@Override
public String toString() {
return eventName + " (" + timestamp + ")";
}
}
|
fix: Allow spaces/special chars in application names
closes #534
|
'use strict';
const joi = require('joi');
const applicationSchema = joi
.object()
.options({ stripUnknown: false })
.keys({
appName: joi.string().required(),
sdkVersion: joi.string().optional(),
strategies: joi
.array()
.optional()
.items(joi.string(), joi.any().strip()),
description: joi
.string()
.allow('')
.optional(),
url: joi
.string()
.allow('')
.optional(),
color: joi
.string()
.allow('')
.optional(),
icon: joi
.string()
.allow('')
.optional(),
});
module.exports = applicationSchema;
|
'use strict';
const joi = require('joi');
const { nameType } = require('./util');
const applicationSchema = joi
.object()
.options({ stripUnknown: false })
.keys({
appName: nameType,
sdkVersion: joi.string().optional(),
strategies: joi
.array()
.optional()
.items(joi.string(), joi.any().strip()),
description: joi
.string()
.allow('')
.optional(),
url: joi
.string()
.allow('')
.optional(),
color: joi
.string()
.allow('')
.optional(),
icon: joi
.string()
.allow('')
.optional(),
});
module.exports = applicationSchema;
|
Add support for dataset Object
|
/* global SVGElement */
import { setStyle } from './setstyle';
import { isFunction, getEl } from './util';
const xlinkns = 'http://www.w3.org/1999/xlink';
export const setAttr = (view, arg1, arg2) => {
const el = getEl(view);
let isSVG = el instanceof SVGElement;
if (arg2 !== undefined) {
if (arg1 === 'style') {
setStyle(el, arg2);
} else if (isSVG && isFunction(arg2)) {
el[arg1] = arg2;
} else if (arg1 === 'dataset') {
setData(el, arg2);
} else if (!isSVG && (arg1 in el || isFunction(arg2))) {
el[arg1] = arg2;
} else {
if (isSVG && (arg1 === 'xlink')) {
setXlink(el, arg2);
return;
}
el.setAttribute(arg1, arg2);
}
} else {
for (const key in arg1) {
setAttr(el, key, arg1[key]);
}
}
};
function setXlink (el, obj) {
for (const key in obj) {
el.setAttributeNS(xlinkns, key, obj[key]);
}
}
function setData (el, obj) {
for (const key in obj) {
el.dataset[key] = obj[key];
}
}
|
/* global SVGElement */
import { setStyle } from './setstyle';
import { isFunction, getEl } from './util';
const xlinkns = 'http://www.w3.org/1999/xlink';
export const setAttr = (view, arg1, arg2) => {
const el = getEl(view);
let isSVG = el instanceof SVGElement;
if (arg2 !== undefined) {
if (arg1 === 'style') {
setStyle(el, arg2);
} else if (isSVG && isFunction(arg2)) {
el[arg1] = arg2;
} else if (!isSVG && (arg1 in el || isFunction(arg2))) {
el[arg1] = arg2;
} else {
if (isSVG && (arg1 === 'xlink')) {
setXlink(el, arg2);
return;
}
el.setAttribute(arg1, arg2);
}
} else {
for (const key in arg1) {
setAttr(el, key, arg1[key]);
}
}
};
function setXlink (el, obj) {
for (const key in obj) {
el.setAttributeNS(xlinkns, key, obj[key]);
}
}
|
Refresh monitoring.nagios.log and fix pylint+pep8.
|
# -*- coding: UTF-8 -*-
# Copyright (C) Vincent BESANCON <besancon.vincent@gmail.com>
#
# 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.
"""Configure the default logger handler."""
import logging as log
# Setup basic logging
log.basicConfig(format='[%(levelname)s] (%(module)s) %(message)s')
logger = log.getLogger('monitoring')
logger.setLevel(log.INFO)
# TODO: find a way to show the correct module name where this is called.
def debug_multiline(message):
"""Dirty manner to show a logging message on multiple lines."""
for line in message.splitlines():
logger.debug("\t%s", line)
|
#===============================================================================
# -*- coding: UTF-8 -*-
# Module : log
# Author : Vincent BESANCON aka 'v!nZ' <besancon.vincent@gmail.com>
# Description : Base to have some logging.
#-------------------------------------------------------------------------------
# This file is part of NagiosPPT (Nagios Python Plugin Template).
#
# NagiosPPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# NagiosPPT 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 NagiosPPT. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
import logging as log
# Setup basic logging
log.basicConfig(format='[%(levelname)s] (%(module)s) %(message)s')
logger = log.getLogger('monitoring')
logger.setLevel(log.INFO)
# TODO: find a way to show the correct module name where this is called.
def debug_multiline(message):
for line in message.splitlines():
logger.debug("\t%s" % line)
|
Fix bug in webhook server
|
'use strict';
var http = require('http');
var spawn = require('child_process').spawn;
http.createServer(function(req, res) {
var json = '';
if (req.method !== 'POST') {
return;
}
if (req.headers['x-github-event'] !== 'push') {
return;
}
req.on('data', function(chunk) {
json += chunk;
});
req.on('end', function() {
var data = JSON.parse(json);
if (data.ref === 'refs/heads/master') {
// The spawned process invokes Grunt, which will fail if run in a "detached"
// state *without* I/O redirection.
spawn(__dirname + '/deploy.sh', [], {
detached: true,
stdio: 'ignore'
});
}
res.end();
});
req.on('error', function() {
res.end();
});
}).listen(1337, '0.0.0.0');
console.log('Server running at http://0.0.0.0:1337/');
|
'use strict';
var http = require('http');
var spawn = require('child_process').spawn;
http.createServer(function(req, res) {
var json = '';
if (req.method !== 'POST') {
return;
}
if (req.headers['x-github-event'] !== 'push') {
return;
}
req.on('data', function(chunk) {
json += chunk;
});
req.on('end', function() {
var data = JSON.parse(json);
if (data.ref === 'refs/heads/master') {
// The spawned process invokes Grunt, which will fail if run in a "detached"
// state *without* I/O redirection.
spawn('./deploy.sh', [], {
detached: true,
stdio: 'ignore'
});
}
res.end();
});
req.on('error', function() {
res.end();
});
}).listen(1337, '0.0.0.0');
console.log('Server running at http://0.0.0.0:1337/');
|
Fix bug involving datatype mixup
|
/*global $*/
const m = require('mithril');
const ItemsCount = module.exports = {};
ItemsCount.view = function (ctrl, args) {
const ITEMS_PER_PAGE = args.possibleItemsPerPage;
let currentItemsPerPage = parseInt(args.itemsPerPage());
let getItemsCountSelect = function () {
let selectConfig = {
config: () => { $('select').material_select(); }, // for materialize-css
onchange: m.withAttr('value', args.itemsPerPage)
};
return [
m('select', selectConfig, ITEMS_PER_PAGE.map(function (count) {
return count === currentItemsPerPage ?
m('option', {value: count, selected: true}, count) :
m('option', {value: count}, count);
})),
m('label', 'Items per Page')
];
};
return m('div', {className: 'row right-align'}, [
m('div', {id: 'itemsCount', className: 'input-field col s1 offset-s11'},
getItemsCountSelect()
)
]);
};
|
/*global $*/
const m = require('mithril');
const ItemsCount = module.exports = {};
ItemsCount.view = function (ctrl, args) {
const ITEMS_PER_PAGE = args.possibleItemsPerPage;
let getItemsCountSelect = function () {
let selectConfig = {
config: () => { $('select').material_select(); }, // for materialize-css
onchange: m.withAttr('value', args.itemsPerPage)
};
return [
m('select', selectConfig, ITEMS_PER_PAGE.map(function (count) {
return count === args.itemsPerPage() ?
m('option', {value: count, selected: true}, count) :
m('option', {value: count}, count);
})),
m('label', 'Items per Page')
];
};
return m('div', {className: 'row right-align'}, [
m('div', {id: 'itemsCount', className: 'input-field col s1 offset-s11'},
getItemsCountSelect()
)
]);
};
|
Add Note_count field to BasePost
|
package gotumblr
type BasePost struct {
Blog_name string
Id int64
Post_url string
PostType string `json:"type"`
Timestamp int64
Date string
Format string
Reblog_key string
Tags []string
Bookmarklet bool
Mobile bool
Source_url string
Source_title string
Liked bool
State string
Total_Posts int64
Note_count int64
Notes []Note
}
type Note struct {
Type string
Timestamp int64
Blog_name string
Blog_uuid string
Blog_url string
Followed bool
Avatar_shape string
Post_id string
Reblog_parent_blog_name string
}
|
package gotumblr
type BasePost struct {
Blog_name string
Id int64
Post_url string
PostType string `json:"type"`
Timestamp int64
Date string
Format string
Reblog_key string
Tags []string
Bookmarklet bool
Mobile bool
Source_url string
Source_title string
Liked bool
State string
Total_Posts int64
Notes []Note
}
type Note struct {
Type string
Timestamp int64
Blog_name string
Blog_uuid string
Blog_url string
Followed bool
Avatar_shape string
Post_id string
Reblog_parent_blog_name string
}
|
Include restricted fields in Elasticsearch mapping [WEB-2399]
|
<?php
namespace App\Models;
trait Transformable
{
public function transform(array $requestedFields = null)
{
$transformer = app('Resources')->getTransformerForModel(get_called_class());
// WEB-1953: Set $isRestricted to false here; index all fields
return (new $transformer(null, false, false))->transform($this);
}
/**
* Jury-rig a connection to the transformer class.
*
* @return array
*/
protected function transformMapping()
{
$transformerClass = app('Resources')->getTransformerForModel(get_called_class());
// include `is_restricted` fields
$fields = (new $transformerClass(null, null, false))->getMappedFields();
// TODO: Fix references to transformMapping to use keys instead of 'name'
foreach ($fields as $fieldName => $fieldMapping) {
$fields[$fieldName]['name'] = $fieldName;
}
return $fields;
}
}
|
<?php
namespace App\Models;
trait Transformable
{
public function transform(array $requestedFields = null)
{
$transformer = app('Resources')->getTransformerForModel(get_called_class());
// WEB-1953: Set $isRestricted to false here; index all fields
return (new $transformer(null, false, false))->transform($this);
}
/**
* Jury-rig a connection to the transformer class.
*
* @return array
*/
protected function transformMapping()
{
$transformerClass = app('Resources')->getTransformerForModel(get_called_class());
$fields = (new $transformerClass())->getMappedFields();
// TODO: Fix references to transformMapping to use keys instead of 'name'
foreach ($fields as $fieldName => $fieldMapping) {
$fields[$fieldName]['name'] = $fieldName;
}
return $fields;
}
}
|
Fix a broken export test
Former-commit-id: 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
Add link of an author to the credit section
|
<?php
if(!defined('MEDIAWIKI')) die;
$dir = __DIR__;
$ext = 'HideUnwanted';
$wgExtensionCredits['other'][] = array(
'path' => __FILE__,
'name' => $ext,
'version' => '0.1',
'author' => '[https://github.com/uta uta]',
'url' => 'https://github.com/uta/HideUnwanted',
'descriptionmsg' => 'hide-unwanted-desc',
'license-name' => 'MIT-License',
);
$wgAutoloadClasses["${ext}Hooks"] = "$dir/classes/${ext}Hooks.php";
$wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php";
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = "${ext}Hooks::hide";
$wgMessagesDirs[$ext] = "$dir/i18n";
$wgHideUnwantedFooters = array();
$wgHideUnwantedHeaders = array();
$wgHideUnwantedTabs = array();
|
<?php
if(!defined('MEDIAWIKI')) die;
$dir = __DIR__;
$ext = 'HideUnwanted';
$wgExtensionCredits['other'][] = array(
'path' => __FILE__,
'name' => $ext,
'version' => '0.1',
'author' => 'uta',
'url' => 'https://github.com/uta/HideUnwanted',
'descriptionmsg' => 'hide-unwanted-desc',
'license-name' => 'MIT-License',
);
$wgAutoloadClasses["${ext}Hooks"] = "$dir/classes/${ext}Hooks.php";
$wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php";
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = "${ext}Hooks::hide";
$wgMessagesDirs[$ext] = "$dir/i18n";
$wgHideUnwantedFooters = array();
$wgHideUnwantedHeaders = array();
$wgHideUnwantedTabs = array();
|
Add suppression of tested code stdout in tests
Add `buffer = True` option to unittest main method call, which
suppresses any printing the code being tested has. This makes for
cleaner test suite output.
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connection = boto.connect_s3()
# Create a bucket to test on existing bucket
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
# Create test file
open(test_dir + '/' + test_file, 'w').close()
return
def tearDown(self):
connection = boto.connect_s3()
# Remove all files uploaded to s3
bucket = connection.get_bucket(existing_bucket)
for s3_file in bucket.list():
bucket.delete_key(s3_file.key)
# Remove bucket created to test on existing bucket
bucket = connection.delete_bucket(existing_bucket)
# Remove test file
os.remove(test_dir + '/' + test_file)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
def testNewFileUploadToExistingBucket(self):
result = commit.commit_to_s3(existing_bucket, test_dir)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main(buffer = True)
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
# Constants - TODO move to config file
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
connection = boto.connect_s3()
# Create a bucket to test on existing bucket
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
# Create test file
open(test_dir + '/' + test_file, 'w').close()
return
def tearDown(self):
connection = boto.connect_s3()
# Remove all files uploaded to s3
bucket = connection.get_bucket(existing_bucket)
for s3_file in bucket.list():
bucket.delete_key(s3_file.key)
# Remove bucket created to test on existing bucket
bucket = connection.delete_bucket(existing_bucket)
# Remove test file
os.remove(test_dir + '/' + test_file)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
def testNewFileUploadToExistingBucket(self):
result = commit.commit_to_s3(existing_bucket, test_dir)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main()
|
Move the selector matcher to OnceExit
|
const { getRulesMatcher, getReset, createResetRule } = require("./lib");
function contains(array, item) {
return array.indexOf(item) !== -1;
}
module.exports = (opts = {}) => {
opts.rulesMatcher = opts.rulesMatcher || "bem";
opts.reset = opts.reset || "initial";
const rulesMatcher = getRulesMatcher(opts.rulesMatcher);
const reset = getReset(opts.reset);
return {
postcssPlugin: "postcss-autoreset",
prepare() {
return {
OnceExit(root) {
const matchedSelectors = [];
root.walkRules(rule => {
const { selector } = rule;
if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) {
return;
}
if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) {
matchedSelectors.push(selector);
}
});
if (!matchedSelectors.length) {
return;
}
root.prepend(createResetRule(matchedSelectors, reset));
},
};
},
};
};
module.exports.postcss = true;
|
const { getRulesMatcher, getReset, createResetRule } = require("./lib");
function contains(array, item) {
return array.indexOf(item) !== -1;
}
module.exports = (opts = {}) => {
opts.rulesMatcher = opts.rulesMatcher || "bem";
opts.reset = opts.reset || "initial";
const rulesMatcher = getRulesMatcher(opts.rulesMatcher);
const reset = getReset(opts.reset);
return {
postcssPlugin: "postcss-autoreset",
prepare() {
const matchedSelectors = [];
return {
Rule(rule) {
const { selector } = rule;
if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) {
return;
}
if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) {
matchedSelectors.push(selector);
}
},
OnceExit(root) {
if (!matchedSelectors.length) {
return;
}
root.prepend(createResetRule(matchedSelectors, reset));
},
};
},
};
};
module.exports.postcss = true;
|
tests: Test slicing a range that does not start at zero.
|
# test builtin range type
# print
print(range(4))
# bool
print(bool(range(0)))
print(bool(range(10)))
# len
print(len(range(0)))
print(len(range(4)))
print(len(range(1, 4)))
print(len(range(1, 4, 2)))
print(len(range(1, 4, -1)))
print(len(range(4, 1, -1)))
print(len(range(4, 1, -2)))
# subscr
print(range(4)[0])
print(range(4)[1])
print(range(4)[-1])
# slice
print(range(4)[0:])
print(range(4)[1:])
print(range(4)[1:2])
print(range(4)[1:3])
print(range(4)[1::2])
print(range(4)[1:-2:2])
print(range(1,4)[:])
print(range(1,4)[0:])
print(range(1,4)[1:])
print(range(1,4)[:-1])
print(range(7,-2,-4)[:])
# attrs
print(range(1, 2, 3).start)
print(range(1, 2, 3).stop)
print(range(1, 2, 3).step)
# bad unary op
try:
-range(1)
except TypeError:
print("TypeError")
# bad subscription (can't store)
try:
range(1)[0] = 1
except TypeError:
print("TypeError")
|
# test builtin range type
# print
print(range(4))
# bool
print(bool(range(0)))
print(bool(range(10)))
# len
print(len(range(0)))
print(len(range(4)))
print(len(range(1, 4)))
print(len(range(1, 4, 2)))
print(len(range(1, 4, -1)))
print(len(range(4, 1, -1)))
print(len(range(4, 1, -2)))
# subscr
print(range(4)[0])
print(range(4)[1])
print(range(4)[-1])
# slice
print(range(4)[0:])
print(range(4)[1:])
print(range(4)[1:2])
print(range(4)[1:3])
print(range(4)[1::2])
print(range(4)[1:-2:2])
# attrs
print(range(1, 2, 3).start)
print(range(1, 2, 3).stop)
print(range(1, 2, 3).step)
# bad unary op
try:
-range(1)
except TypeError:
print("TypeError")
# bad subscription (can't store)
try:
range(1)[0] = 1
except TypeError:
print("TypeError")
|
Hide settigns login if oscar hasn't been tapped
|
// @flow
import * as React from 'react'
import {StyleSheet, ScrollView} from 'react-native'
import {TableView} from 'react-native-tableview-simple'
import {connect} from 'react-redux'
import {type ReduxState} from '../../flux'
import type {TopLevelViewPropsType} from '../types'
import CredentialsLoginSection from './sections/login-credentials'
import OddsAndEndsSection from './sections/odds-and-ends'
import SupportSection from './sections/support'
type ReduxStateProps = {
loadEasterEggStatus: boolean,
}
const styles = StyleSheet.create({
container: {
paddingVertical: 20,
},
})
function SettingsView(props: TopLevelViewPropsType) {
return (
<ScrollView
contentContainerStyle={styles.container}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
>
<TableView>
{props.loadEasterEggStatus ? <CredentialsLoginSection /> : null}
<SupportSection navigation={props.navigation} />
<OddsAndEndsSection navigation={props.navigation} />
</TableView>
</ScrollView>
)
}
SettingsView.navigationOptions = {
title: 'Settings',
}
function mapStateToProps(state) {
return {
loadEasterEggStatus: state.settings.easterEggEnabled
? state.settings.easterEggEnabled
: false,
}
}
export default connect(mapStateToProps)(SettingsView)
|
// @flow
import * as React from 'react'
import {StyleSheet, ScrollView} from 'react-native'
import {TableView} from 'react-native-tableview-simple'
import type {TopLevelViewPropsType} from '../types'
import CredentialsLoginSection from './sections/login-credentials'
import OddsAndEndsSection from './sections/odds-and-ends'
import SupportSection from './sections/support'
const styles = StyleSheet.create({
container: {
paddingVertical: 20,
},
})
export default function SettingsView(props: TopLevelViewPropsType) {
return (
<ScrollView
contentContainerStyle={styles.container}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
>
<TableView>
<CredentialsLoginSection />
<SupportSection navigation={props.navigation} />
<OddsAndEndsSection navigation={props.navigation} />
</TableView>
</ScrollView>
)
}
SettingsView.navigationOptions = {
title: 'Settings',
}
|
Replace execfile() with exec() since it does not work with Python 3
Signed-off-by: Christophe Vu-Brugier <1930e27f67e1e10d51770b88cb06d386f1aa46ae@yahoo.fr>
|
#! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, Inc
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''
from distutils.core import setup
__version__ = ''
exec(open('targetcli/version.py').read())
setup(
name = 'targetcli-fb',
version = __version__,
description = 'An administration shell for RTS storage targets.',
license = 'Apache 2.0',
maintainer = 'Andy Grover',
maintainer_email = 'agrover@redhat.com',
url = 'http://github.com/agrover/targetcli-fb',
packages = ['targetcli'],
scripts = ['scripts/targetcli'],
)
|
#! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, Inc
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''
from distutils.core import setup
__version__ = ''
execfile('targetcli/version.py')
setup(
name = 'targetcli-fb',
version = __version__,
description = 'An administration shell for RTS storage targets.',
license = 'Apache 2.0',
maintainer = 'Andy Grover',
maintainer_email = 'agrover@redhat.com',
url = 'http://github.com/agrover/targetcli-fb',
packages = ['targetcli'],
scripts = ['scripts/targetcli'],
)
|
Fix count of array rank
15 was on my local computer.
|
<?php
namespace Chay22\RecSelMeter\Tests;
use Chay22\RecSelMeter\Config;
class ConfigTests extends \PHPUnit_Framework_TestCase
{
public $config;
/**
* Tests against old created + established store
*/
function __construct()
{
$this->config = new Config;
}
public function testNew()
{
$config = new Config;
$config->newRank(['kaskus test' => 100]);
$this->assertArrayHasKey('kaskus test', $config->data()['rank']);
$this->assertCount(1, $config->data()['rank']);
}
public function testAdd()
{
$config = new Config;
$config->addRank(['kaskus test' => 100]);
$this->assertArrayHasKey('kaskus test', $config->data()['rank']);
$this->assertCount(11, $config->data()['rank']);
}
public function testSet()
{
$config = new Config;
$config->setStoreActive([7 => 3]);
$this->assertEquals(3, $config->data()['storeActive'][7]);
}
}
|
<?php
namespace Chay22\RecSelMeter\Tests;
use Chay22\RecSelMeter\Config;
class ConfigTests extends \PHPUnit_Framework_TestCase
{
public $config;
/**
* Tests against old created + established store
*/
function __construct()
{
$this->config = new Config;
}
public function testNew()
{
$config = new Config;
$config->newRank(['kaskus test' => 100]);
$this->assertArrayHasKey('kaskus test', $config->data()['rank']);
$this->assertCount(1, $config->data()['rank']);
}
public function testAdd()
{
$config = new Config;
$config->addRank(['kaskus test' => 100]);
$this->assertArrayHasKey('kaskus test', $config->data()['rank']);
$this->assertCount(15, $config->data()['rank']);
}
public function testSet()
{
$config = new Config;
$config->setStoreActive([7 => 3]);
$this->assertEquals(3, $config->data()['storeActive'][7]);
}
}
|
Use colons in routes instead of brackets
|
module.exports = function(string, data) {
return string.replace(/\:([^\:\/]*)/g, function(original, match) {
var result = data;
var parts = match.split('.');
var i = -1;
while(++i < parts.length - 1) {
if(typeof result[parts[i]] === 'object') {
result = result[parts[i]];
}
else {
throw Error('failed to interpolate ' + parts.join('.') + ' at ' + parts.slice(0, i+1).join('.'));
}
}
if(typeof result[parts[i]] === 'number' || typeof result[parts[i]] === 'string') {
result = result[parts[i]];
}
else {
throw Error('failed to interpolate ' + parts.join('.') + ' at ' + parts.slice(0, i+1).join('.'));
}
return result;
});
};
|
module.exports = function(string, data) {
return string.replace(/{([^{}]*)}/g, function(original, match) {
var result = data;
var parts = match.split('.');
var i = -1;
while(++i < parts.length - 1) {
if(typeof result[parts[i]] === 'object') {
result = result[parts[i]];
}
else {
throw Error('failed to interpolate ' + parts.join('.') + ' at ' + parts.slice(0, i+1).join('.'));
}
}
if(typeof result[parts[i]] === 'number' || typeof result[parts[i]] === 'string') {
result = result[parts[i]];
}
else {
throw Error('failed to interpolate ' + parts.join('.') + ' at ' + parts.slice(0, i+1).join('.'));
}
return result;
});
};
|
Fix for alert box error
|
module.exports = new function() {
var webdriver = require("selenium-webdriver");
webdriver.WebDriver.prototype.waitJqueryReady = function() {
var self = this;
return self.flow_.execute(function() {
self.switchTo().alert().then(
function() {
return true;
},
function() {
self.executeScript("return typeof jQuery != String(undefined) ? (!jQuery.active === jQuery.isReady) : null;").then(function(isReady) {
switch (isReady) {
case true:
return true
break;
case false:
self.waitJqueryReady();
break;
case null:
self.controlFlow().timeout(30*1000)
break;
}
});
}
);
}, "WebDriver.waitJqueryReady()");
}
return webdriver;
}
|
module.exports = new function() {
var webdriver = require("selenium-webdriver");
webdriver.WebDriver.prototype.waitJqueryReady = function() {
var self = this;
return self.flow_.execute(function() {
self.executeScript("return typeof jQuery != String(undefined) ? (!jQuery.active === jQuery.isReady) : null;").then(function(isReady) {
switch (isReady) {
case true:
return true
break;
case false:
self.waitJqueryReady();
break;
case null:
self.controlFlow().timeout(30*1000)
break;
}
})
}, "WebDriver.waitJqueryReady()");
}
return webdriver;
}
|
Add proxy fix as in lr this will run with reverse proxy
|
import os, logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from raven.contrib.flask import Sentry
from lrutils import dateformat
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
app.jinja_env.filters['dateformat'] = dateformat
if app.config.get('BASIC_AUTH_USERNAME'):
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
@app.context_processor
def asset_path_context_processor():
return {
'asset_path': '/static/build/',
'landregistry_asset_path': '/static/build/'
}
@app.context_processor
def address_processor():
from lrutils import build_address
def process_address_json(address_json):
return build_address(address_json)
return dict(formatted=process_address_json)
|
import os, logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from raven.contrib.flask import Sentry
from lrutils import dateformat
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.jinja_env.filters['dateformat'] = dateformat
if app.config.get('BASIC_AUTH_USERNAME'):
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
app.logger.debug("\nConfiguration\n%s\n" % app.config)
@app.context_processor
def asset_path_context_processor():
return {
'asset_path': '/static/build/',
'landregistry_asset_path': '/static/build/'
}
@app.context_processor
def address_processor():
from lrutils import build_address
def process_address_json(address_json):
return build_address(address_json)
return dict(formatted=process_address_json)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.