text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update test helper file to handle hd images | import APIConstants from '../constants/APIConstants'
import randomInt from '../../app/helpers/random-int'
const fixture = require('../fixture-data')
import isSameDay from '../../app/helpers/is-same-day'
import daysBetween from './days-between'
var images = Array.apply(null, Array(7))
images.forEach((item, i) => (images[i] = `images/img_${i + 1}`))
images = images.reverse()
function getByDate(date) {
return getByDateCall(date).then(data => {
if (APIConstants.TEST_FAILURE) throw new Error('Error')
else return data
})
}
function getByDateCall(date) {
var today = new Date()
var day = Math.abs(daysBetween(today, date) % 7)
fixture.hdurl = `${images[day]}_hd.jpg`
fixture.url = `${images[day]}.jpg`
fixture.date = date
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, APIConstants.API_DELAY)
})
return p
}
module.exports = getByDate
| import APIConstants from '../constants/APIConstants'
import randomInt from '../../app/helpers/random-int'
const fixture = require('../fixture-data')
import isSameDay from '../../app/helpers/is-same-day'
import daysBetween from './days-between'
var images = Array.apply(null, Array(7))
images.forEach((item, i) => (images[i] = `images/img_${i + 1}.jpg`))
images = images.reverse()
function getByDate(date) {
return getByDateCall(date).then(data => {
if (APIConstants.TEST_FAILURE) throw new Error('Error')
else return data
})
}
function getByDateCall(date) {
var today = new Date()
var day = Math.abs(daysBetween(today, date) % 7)
fixture.hdurl = images[day]
fixture.url = images[day]
fixture.date = date
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, APIConstants.API_DELAY)
})
return p
}
module.exports = getByDate
|
Remove apparently superfluous call to fill_recommended_bugs_cache. | import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
| import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
mysite.profile.tasks.fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
|
Revert "Revert "Use composed annotation for readability""
This reverts commit c82beaa8e9380ec257a4bb296f981cde865ff6d1. | package ee.tuleva.onboarding.auth.session;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
public class GenericSessionStore implements Serializable {
@Serial private static final long serialVersionUID = -648103071415508424L;
private final Map<String, Object> sessionAttributes = new HashMap<>();
public <T extends Serializable> void save(T sessionAttribute) {
sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) sessionAttributes.get(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
}
| package ee.tuleva.onboarding.auth.session;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GenericSessionStore implements Serializable {
@Serial private static final long serialVersionUID = -648103071415508424L;
private final Map<String, Object> sessionAttributes = new HashMap<>();
public <T extends Serializable> void save(T sessionAttribute) {
sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) sessionAttributes.get(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
}
|
Add a test to make sure screenshots are added to exceptions | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.remote.server.rest;
import org.junit.Test;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import java.util.Optional;
public class ResponsesTest {
@Test
public void shouldAddScreenshotIfPresent() {
Response response = Responses.failure(
new SessionId("cheese"),
new RuntimeException("boo"),
Optional.of("hello"));
System.out.println("response = " + response);
}
} | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.remote.server.rest;
import static org.junit.Assert.*;
import org.junit.Test;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import java.util.Optional;
public class ResponsesTest {
@Test
public void shouldAddScreenshotIfPresent() {
Response response = Responses.failure(
new SessionId("cheese"),
new RuntimeException("boo"),
Optional.of("hello"));
System.out.println("response = " + response);
}
} |
Change Install command to accept variadic input. | package core
import (
"io"
"os/exec"
"strings"
"github.com/kr/pty"
)
type Command struct {
command string
args []string
}
func NewCommand(command string, args ...string) Command {
return Command{command, args}
}
// Install is a command executer for install commands.
func (c Command) Install(input ...string) {
for _, a := range input {
args := append(c.args, a)
cmd := exec.Command(c.command, args...)
out := NewPrinter("homebrew")
f, err := pty.Start(cmd)
if err != nil {
panic(err)
}
io.Copy(out, f)
}
}
// List is a command executer for collecting command output.
func (c Command) List() ([]string, error) {
cmd := exec.Command(c.command, c.args...)
out, err := cmd.Output()
if err != nil {
return nil, err
}
return strings.Fields(string(out)), nil
}
func IsInstalled(command string) bool {
_, err := exec.LookPath(command)
if err != nil {
return false
}
return true
}
| package core
import (
"io"
"os/exec"
"strings"
"github.com/kr/pty"
)
type Command struct {
command string
args []string
}
func NewCommand(command string, args ...string) Command {
return Command{command, args}
}
// Install is a command executer for install commands.
func (c Command) Install(input []string) {
for _, a := range input {
args := append(c.args, a)
cmd := exec.Command(c.command, args...)
out := NewPrinter("homebrew")
f, err := pty.Start(cmd)
if err != nil {
panic(err)
}
io.Copy(out, f)
}
}
// List is a command executer for collecting command output.
func (c Command) List() ([]string, error) {
cmd := exec.Command(c.command, c.args...)
out, err := cmd.Output()
if err != nil {
return nil, err
}
return strings.Fields(string(out)), nil
}
func IsInstalled(command string) bool {
_, err := exec.LookPath(command)
if err != nil {
return false
}
return true
}
|
Fix namespace in import of ProfilerInterface | <?php
/**
* @author @fabfuel <fabian@fabfuel.de>
* @created 14.11.14, 06:57
*/
namespace Fabfuel\Prophiler\Adapter;
use Fabfuel\Prophiler\ProfilerInterface;
abstract class AdapterAbstract
{
/**
* @var ProfilerInterface
*/
protected $profiler;
public function __construct(ProfilerInterface $profiler)
{
$this->profiler = $profiler;
}
/**
* @return ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* @param ProfilerInterface $profiler
*/
public function setProfiler(ProfilerInterface $profiler)
{
$this->profiler = $profiler;
}
}
| <?php
/**
* @author @fabfuel <fabian@fabfuel.de>
* @created 14.11.14, 06:57
*/
namespace Fabfuel\Prophiler\Adapter;
use Mongo\Profiler\ProfilerInterface;
abstract class AdapterAbstract
{
/**
* @var ProfilerInterface
*/
protected $profiler;
public function __construct(ProfilerInterface $profiler)
{
$this->profiler = $profiler;
}
/**
* @return ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* @param ProfilerInterface $profiler
*/
public function setProfiler(ProfilerInterface $profiler)
{
$this->profiler = $profiler;
}
}
|
Fix buglet in the destroy path. | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
|
Convert README.md to rst for pypi using pandoc.
Closes #11
Thanks for the tips/help Marc :) | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import pypandoc
readme = pypandoc.convert('README.md', 'rst')
setup(name='chevron',
version='0.7.1',
license='MIT',
description='Mustache templating language renderer',
long_description=readme,
author='noah morrison',
author_email='noah@morrison.ph',
url='https://github.com/noahmorrison/chevron',
packages=['chevron'],
entry_points={
'console_scripts': ['chevron=chevron:cli_main']
},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Text Processing :: Markup'
]
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='chevron',
version='0.7.1',
license='MIT',
description='Mustache templating language renderer',
author='noah morrison',
author_email='noah@morrison.ph',
url='https://github.com/noahmorrison/chevron',
packages=['chevron'],
entry_points={
'console_scripts': ['chevron=chevron:cli_main']
},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Text Processing :: Markup'
]
)
|
Update bold init for imports | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# pylint: disable=unused-import
"""
Pre-processing fMRI - BOLD signal workflows
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: fmriprep.workflows.bold.base
.. automodule:: fmriprep.workflows.bold.util
.. automodule:: fmriprep.workflows.bold.hmc
.. automodule:: fmriprep.workflows.bold.stc
.. automodule:: fmriprep.workflows.bold.t2s
.. automodule:: fmriprep.workflows.bold.registration
.. automodule:: fmriprep.workflows.bold.resampling
.. automodule:: fmriprep.workflows.bold.confounds
"""
from .base import init_func_preproc_wf
from .util import init_bold_reference_wf
from .hmc import init_bold_hmc_wf
from .stc import init_bold_stc_wf
from .t2s import init_bold_t2s_wf
from .registration import init_bold_reg_wf
from .resampling import (
init_bold_mni_trans_wf,
init_bold_surf_wf,
init_bold_preproc_trans_wf,
)
from .confounds import (
init_bold_confs_wf,
init_ica_aroma_wf,
)
| # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# pylint: disable=unused-import
"""
Pre-processing fMRI - BOLD signal workflows
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: fmriprep.workflows.bold.base
.. automodule:: fmriprep.workflows.bold.util
.. automodule:: fmriprep.workflows.bold.hmc
.. automodule:: fmriprep.workflows.bold.stc
.. automodule:: fmriprep.workflows.bold.registration
.. automodule:: fmriprep.workflows.bold.resampling
.. automodule:: fmriprep.workflows.bold.confounds
"""
from .base import init_func_preproc_wf
from .util import init_bold_reference_wf
from .hmc import init_bold_hmc_wf
from .stc import init_bold_stc_wf
from .registration import init_bold_reg_wf
from .resampling import (
init_bold_mni_trans_wf,
init_bold_surf_wf,
init_bold_preproc_trans_wf,
)
from .confounds import (
init_bold_confs_wf,
init_ica_aroma_wf,
)
|
Change syntax to template strings. | $(`<section class="min-chat">
<header class="min-chat__header">
<b class="min-chat__header__title">
<img src="http://i.imgur.com/RKJMsl8.png" class="min-chat__icon" >
Czatrepajr</b>
<button id="min-chat-switch" class="min-chat__header__switch" title="Wyłącz">↓</button>
</header>
<div id="min-chat-content">
<div class="min-chat__notify min-chat__notify--left min-chat__notify--hidden"></div>
<div class="min-chat__notify min-chat__notify--join min-chat__notify--hidden"></div>
<div class="min-chat__content"></div>
<div class="min-chat__fieldset">
<input type="text" id="chat-input" class="min-chat__fieldset__input" spellcheck="true">
</div>
</div>
</section>`).appendTo('body');
| $('<section class="min-chat"> \
<header class="min-chat__header"> \
<b class="min-chat__header__title">\
<img src="http://i.imgur.com/RKJMsl8.png" class="min-chat__icon" >\
Czatrepajr</b> \
<button id="min-chat-switch" class="min-chat__header__switch">Wyłącz</button> \
</header> \
<div id="min-chat-content"> \
<div class="min-chat__notify min-chat__notify--left min-chat__notify--hidden"></div> \
<div class="min-chat__notify min-chat__notify--join min-chat__notify--hidden"></div> \
<div class="min-chat__content"></div> \
<div class="min-chat__fieldset"> \
<input type="text" id="chat-input" class="min-chat__fieldset__input" spellcheck="true"> \
</div> \
</div> \
</section>').appendTo('body');
|
Migrate content repo to @isaacphysics | 'use strict';
define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() {
/* Services */
angular.module('scooter.services', [])
.constant('Repo', {
owner: "isaacphysics",
name: "rutherford-content"
})
.constant('ApiServer', "https://staging.isaacphysics.org/api/any/api")
.service('LoginChecker', require("app/services/LoginChecker"))
.factory('FileLoader', require("app/services/FileLoader"))
.factory('FigureUploader', require("app/services/FigureUploader"))
.service('SnippetLoader', require("app/services/SnippetLoader"))
.factory('TagLoader', require("app/services/TagLoader"))
.factory('IdLoader', require("app/services/IdLoader"))
}); | 'use strict';
define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() {
/* Services */
angular.module('scooter.services', [])
.constant('Repo', {
owner: "ucam-cl-dtg",
name: "rutherford-content"
})
.constant('ApiServer', "https://staging.isaacphysics.org/api/any/api")
.service('LoginChecker', require("app/services/LoginChecker"))
.factory('FileLoader', require("app/services/FileLoader"))
.factory('FigureUploader', require("app/services/FigureUploader"))
.service('SnippetLoader', require("app/services/SnippetLoader"))
.factory('TagLoader', require("app/services/TagLoader"))
.factory('IdLoader', require("app/services/IdLoader"))
}); |
Update network timeout for web3 calls | import axios from 'axios';
import { Manager as Web3RequestManager } from 'web3-core-requestmanager';
class HttpRequestManager {
constructor(host, options) {
options = options || {};
this.host = host;
const config = {
timeout: options.timeout || 10000,
headers: { 'Content-Type': 'application/json' }
};
if (options.headers) {
options.headers.forEach(header => {
config.headers[header.name] = header.value;
});
}
this.request = axios.create(config);
return new Web3RequestManager(this);
}
send(payload, callback) {
this.request
.post(this.host, payload)
.then(result => {
callback(null, result.data);
})
.catch(err => {
callback(err);
});
}
disconnect() {}
}
export default HttpRequestManager;
| import axios from 'axios';
import { Manager as Web3RequestManager } from 'web3-core-requestmanager';
class HttpRequestManager {
constructor(host, options) {
options = options || {};
this.host = host;
const config = {
timeout: options.timeout || 5000,
headers: { 'Content-Type': 'application/json' }
};
if (options.headers) {
options.headers.forEach(header => {
config.headers[header.name] = header.value;
});
}
this.request = axios.create(config);
return new Web3RequestManager(this);
}
send(payload, callback) {
this.request
.post(this.host, payload)
.then(result => {
callback(null, result.data);
})
.catch(err => {
callback(err);
});
}
disconnect() {}
}
export default HttpRequestManager;
|
Put back in the serialization context | package org.menacheri.convert.flex;
import flex.messaging.io.SerializationContext;
/**
* This class provides threadlocal contexts on demand to the serializer and
* deserializer class. This context object is necessary for blazeds to do
* serialization.
*
* @author Abraham Menacherry
*
*/
public class SerializationContextProvider {
public SerializationContext get()
{
// Threadlocal SerializationContent
SerializationContext serializationContext = SerializationContext
.getSerializationContext();
serializationContext.enableSmallMessages = true;
serializationContext.instantiateTypes = true;
// use _remoteClass field
serializationContext.supportRemoteClass = true;
// false Legacy Flex 1.5 behavior was to return a java.util.Collection
// for Array, New Flex 2+ behavior is to return Object[] for AS3 Array
serializationContext.legacyCollection = false;
// false Legacy flash.xml.XMLDocument Type
serializationContext.legacyMap = false;
// true New E4X XML Type
serializationContext.legacyXMLDocument = false;
// determines whether the constructed Document is name-space aware
serializationContext.legacyXMLNamespaces = false;
serializationContext.legacyThrowable = false;
serializationContext.legacyBigNumbers = false;
serializationContext.restoreReferences = false;
serializationContext.logPropertyErrors = false;
serializationContext.ignorePropertyErrors = true;
return serializationContext;
}
}
| package org.menacheri.convert.flex;
import flex.messaging.io.SerializationContext;
/**
* This class provides threadlocal contexts on demand to the serializer and
* deserializer class. This context object is necessary for blazeds to do
* serialization.
*
* @author Abraham Menacherry
*
*/
public class SerializationContextProvider {
public SerializationContext get()
{
// Threadlocal SerializationContent
SerializationContext serializationContext = SerializationContext
.getSerializationContext();
serializationContext.enableSmallMessages = true;
serializationContext.instantiateTypes = true;
// use _remoteClass field
serializationContext.supportRemoteClass = true;
// false Legacy Flex 1.5 behavior was to return a java.util.Collection
// for Array, New Flex 2+ behavior is to return Object[] for AS3 Array
serializationContext.legacyCollection = false;
// false Legacy flash.xml.XMLDocument Type
serializationContext.legacyMap = false;
// true New E4X XML Type
serializationContext.legacyXMLDocument = false;
// determines whether the constructed Document is name-space aware
//serializationContext.legacyXMLNamespaces = false;
serializationContext.legacyThrowable = false;
serializationContext.legacyBigNumbers = false;
serializationContext.restoreReferences = false;
serializationContext.logPropertyErrors = false;
serializationContext.ignorePropertyErrors = true;
return serializationContext;
}
}
|
Fix list not loading on second open
Closes #3369 | import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
// Block loading on all items until the first load comes in
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
// Search debounced
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
// If one of the other active properties changes, update the query params and load the new items
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
// Whenever the filters change or another list is loaded, load the items
yield fork(takeLatest, [actions.INITIAL_LIST_LOAD, actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
| import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
yield fork(takeLatest, [actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
|
Add meta tag to display app banner | <?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
use kartik\widgets\AlertBlock;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta name="Vanish" content="app-id=992815164, affiliate-data=myAffiliateData, app-argument=evote://">
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= $this->title ? Html::encode(Yii::$app->name." | $this->title") : (Yii::$app->name.' | Home') ?></title>
<?php $this->head() ?>
</head>
<body>
<?php
echo AlertBlock::widget([
'useSessionFlash' => true,
'type' => AlertBlock::TYPE_GROWL,
'delay' => false, // Don't automatically disappear.
]);
?>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
| <?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
use kartik\widgets\AlertBlock;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= $this->title ? Html::encode(Yii::$app->name." | $this->title") : (Yii::$app->name.' | Home') ?></title>
<?php $this->head() ?>
</head>
<body>
<?php
echo AlertBlock::widget([
'useSessionFlash' => true,
'type' => AlertBlock::TYPE_GROWL,
'delay' => false, // Don't automatically disappear.
]);
?>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
|
Change type for private blog settings
refs #5614 and #5503
- update private blog type, including update to settings.edit
- switch order of populate settings & update fixtures + populate all settings
Private blog settings should not be returned by public endpoints
therefore they need a type which is not `blog` or `theme`.
`core` doesn't suit either, as those settings don't usually have UI
To resolve this, I created a new type `private` which can be used
for any setting which has a UI but should not be public data | import AuthenticatedRoute from 'ghost/routes/authenticated';
import CurrentUserSettings from 'ghost/mixins/current-user-settings';
import styleBody from 'ghost/mixins/style-body';
export default AuthenticatedRoute.extend(styleBody, CurrentUserSettings, {
titleToken: 'Settings - General',
classNames: ['settings-view-general'],
beforeModel: function (transition) {
this._super(transition);
return this.get('session.user')
.then(this.transitionAuthor())
.then(this.transitionEditor());
},
model: function () {
return this.store.find('setting', {type: 'blog,theme,private'}).then(function (records) {
return records.get('firstObject');
});
},
actions: {
save: function () {
this.get('controller').send('save');
}
}
});
| import AuthenticatedRoute from 'ghost/routes/authenticated';
import CurrentUserSettings from 'ghost/mixins/current-user-settings';
import styleBody from 'ghost/mixins/style-body';
export default AuthenticatedRoute.extend(styleBody, CurrentUserSettings, {
titleToken: 'Settings - General',
classNames: ['settings-view-general'],
beforeModel: function (transition) {
this._super(transition);
return this.get('session.user')
.then(this.transitionAuthor())
.then(this.transitionEditor());
},
model: function () {
return this.store.find('setting', {type: 'blog,theme'}).then(function (records) {
return records.get('firstObject');
});
},
actions: {
save: function () {
this.get('controller').send('save');
}
}
});
|
Print stack trace upon error | package devopsdistilled.operp.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import devopsdistilled.operp.server.context.AppContext;
public class ServerApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(
AppContext.class);
Properties hibernateProperties = new Properties();
URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader()
.getResource("server/hibernate.properties");
File hibernatePropertiesFile = new File(
hibernatePropertiesFileUrl.getFile());
try {
InputStream in = new FileInputStream(hibernatePropertiesFile);
hibernateProperties.load(in);
String hbm2dllKey = "hibernate.hbm2ddl.auto";
String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey);
if (hbm2ddlValue.equalsIgnoreCase("create"))
hibernateProperties.setProperty(hbm2dllKey, "update");
in.close();
OutputStream out = new FileOutputStream(hibernatePropertiesFile);
hibernateProperties.store(out, null);
} catch (IOException e) {
System.err.println("hibernate.properties file not found!");
e.printStackTrace();
}
System.out.println(context);
}
}
| package devopsdistilled.operp.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import devopsdistilled.operp.server.context.AppContext;
public class ServerApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(
AppContext.class);
Properties hibernateProperties = new Properties();
URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader()
.getResource("server/hibernate.properties");
File hibernatePropertiesFile = new File(
hibernatePropertiesFileUrl.getFile());
try {
InputStream in = new FileInputStream(hibernatePropertiesFile);
hibernateProperties.load(in);
String hbm2dllKey = "hibernate.hbm2ddl.auto";
String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey);
if (hbm2ddlValue.equalsIgnoreCase("create"))
hibernateProperties.setProperty(hbm2dllKey, "update");
in.close();
OutputStream out = new FileOutputStream(hibernatePropertiesFile);
hibernateProperties.store(out, null);
} catch (IOException e) {
System.err.println("hibernate.properties file not found!");
}
System.out.println(context);
}
}
|
Add is_geolocated property for admin purpuse | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
"""
Should return a string for the address as Google Maps format
"""
raise NotImplementedError
def is_geolocated(self):
"""
Usefull for example in the admin in order to easily identify non geolocated object
"""
return self.geom is not None
is_geolocated.boolean = True
class Meta:
abstract = True
def update_geolocation(sender, instance, **kwargs):
"""
This signal receiver update the instance but does not save it
Should be used with pre_save signal
"""
g = geocoders.GoogleV3()
try:
place, (lat, lng) = g.geocode(instance.get_location_as_string())
instance.geom = Point(lng, lat)
except:
instance.geom = None | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
"""
Should return a string for the address as Google Maps format
"""
raise NotImplementedError
class Meta:
abstract = True
def update_geolocation(sender, instance, **kwargs):
"""
This signal receiver update the instance but does not save it
Should be used with pre_save signal
"""
g = geocoders.GoogleV3()
try:
place, (lat, lng) = g.geocode(instance.get_location_as_string())
instance.geom = Point(lng, lat)
except:
instance.geom = None |
Update label data to point at correct spots | import pandas as pd
import subprocess
import sys
import os
source = sys.argv[1]
dest = sys.argv[2]
labels = sys.argv[3]
df = pd.read_csv(labels)
df = df.fillna('EMPTY')
subprocess.call(['mkdir', '-p', dest])
for subjects in list(set(df.Subject)):
subject_list = subjects.split(', ')
for subject in subject_list:
print(dest)
print(subject)
subprocess.call(['mkdir', '-p', os.path.join(dest, subject)])
folders = [file.split('/')[-2] for file in df.SourceFile]
filenames = [file.split('/')[-1] for file in df.SourceFile]
for folder, filename, subjects in zip(folders, filenames, df.Subject):
subject_list = subjects.split(', ')
for subject in subject_list:
subprocess.call(['mv', os.path.join(source, folder, filename), os.path.join(dest, subject, filename)]) | import pandas as pd
import subprocess
import sys
import os
source = sys.argv[1]
dest = sys.argv[2]
labels = sys.argv[3]
df = pd.read_csv(labels)
df = df.fillna('EMPTY')
subprocess.call(['mkdir', '-p', dest])
for subjects in list(set(df.Subject)):
subject_list = subjects.split(', ')
for subject in subject_list:
print(dest)
print(subject)
subprocess.call(['mkdir', '-p', os.path.join(dest, subject)])
folders = [file.split('/')[-2] for file in df.SourceFile]
filenames = [file.split('/')[-1] for file in df.SourceFile]
for folder, filename, subjects in zip(folders, filenames, df.Subject):
subject_list = subjects.split(', ')
for subject in subject_list:
subprocess.call(['cp', os.path.join(source, folder, filename), os.path.join(dest, subject, filename)]) |
Remove entitymanagerawaretrait as it's extending abstractservicelocatoraware | <?php
namespace InfinityBase\Mapper;
use Doctrine\ORM\EntityRepository;
use InfinityBase\ServiceManager\AbstractServiceLocatorAware;
abstract class AbstractMapper extends AbstractServiceLocatorAware
{
/**
* @var EntityRepository
*/
private $repository;
/**
* Get the accounts repository
*
* @return EntityRepository
*/
private function getRepository()
{
if (null === $this->repository) {
$this->repository = $this->getEntityManager()
->getRepository($this->getModuleNamespace() . '\Entity\\' . $this->getEntityName());
}
return $this->repository;
}
} | <?php
namespace InfinityBase\Mapper;
use Doctrine\ORM\EntityRepository;
use InfinityBase\ServiceManager\AbstractServiceLocatorAware;
abstract class AbstractMapper extends AbstractServiceLocatorAware
{
use EntityManagerAwareTrait;
/**
* @var EntityRepository
*/
private $repository;
/**
* Get the accounts repository
*
* @return EntityRepository
*/
private function getRepository()
{
if (null === $this->repository) {
$this->repository = $this->getEntityManager()
->getRepository($this->getModuleNamespace() . '\Entity\\' . $this->getEntityName());
}
return $this->repository;
}
} |
Change 'username' destination to the 'username' attribute instead of user, since that's what is used in the code. | # -*- coding: utf-8 -*-
"""Utility module for command line argument parsing"""
from argparse import ArgumentParser, FileType
def parent_parser():
"""Create command line argument parser with common PostgreSQL options
:return: the created parser
"""
parser = ArgumentParser(add_help=False)
parser.add_argument('dbname', help='database name')
group = parser.add_argument_group('Connection options')
group.add_argument('-H', '--host', help="database server host or "
"socket directory (default %(default)s)")
group.add_argument('-p', '--port', type=int, help="database server port "
"number (default %(default)s)")
group.add_argument('-U', '--username', dest='username',
help="database user name (default %(default)s)")
group.add_argument('-W', '--password', action="store_true",
help="force password prompt")
parser.add_argument('-o', '--output', type=FileType('w'),
help="output file name (default stdout)")
parser.add_argument('--version', action='version', version='%(prog)s 0.4')
return parser
| # -*- coding: utf-8 -*-
"""Utility module for command line argument parsing"""
from argparse import ArgumentParser, FileType
def parent_parser():
"""Create command line argument parser with common PostgreSQL options
:return: the created parser
"""
parser = ArgumentParser(add_help=False)
parser.add_argument('dbname', help='database name')
group = parser.add_argument_group('Connection options')
group.add_argument('-H', '--host', help="database server host or "
"socket directory (default %(default)s)")
group.add_argument('-p', '--port', type=int, help="database server port "
"number (default %(default)s)")
group.add_argument('-U', '--username', dest='user',
help="database user name (default %(default)s)")
group.add_argument('-W', '--password', action="store_true",
help="force password prompt")
parser.add_argument('-o', '--output', type=FileType('w'),
help="output file name (default stdout)")
parser.add_argument('--version', action='version', version='%(prog)s 0.4')
return parser
|
Modify add() to save one extra get() call to HashMap. | package chart_parser;
import java.util.HashMap;
import cat_combination.SuperCategory;
public class CategoryEquivalence {
/*
* keys are triples of (position, span, SuperCategory); value becomes the *last*
* SuperCategory in the linked list of equivalents
*/
// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
private HashMap<EquivKey, SuperCategory> equiv;
public CategoryEquivalence(int initCapacity) {
equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
}
/*
* returns true if equivalent category not already there, false otherwise
*/
public boolean add(int position, int span, SuperCategory superCat) {
EquivKey equivKey = new EquivKey(position, span, superCat);
SuperCategory previousValue = equiv.put(equivKey, superCat);
// put() returns the previous value, or null if there was no mapping for the key
if (previousValue != null) {
previousValue.next = superCat;
return false;
} else {
return true;
}
}
public void clear() {
equiv.clear();
}
}
| package chart_parser;
import java.util.HashMap;
import cat_combination.SuperCategory;
public class CategoryEquivalence {
/*
* keys are triples of (position, span, SuperCategory); value becomes the *last*
* SuperCategory in the linked list of equivalents
*/
// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
private HashMap<EquivKey, SuperCategory> equiv;
public CategoryEquivalence(int initCapacity) {
equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
}
/*
* returns true if equivalent category not already there, false otherwise
*/
public boolean add(int position, int span, SuperCategory superCat) {
EquivKey equivKey = new EquivKey(position, span, superCat);
SuperCategory value = equiv.get(equivKey);
equiv.put(equivKey, superCat);
// overrides the previous value (if there was one)
if (value != null) {
value.next = superCat;
return false;
} else {
return true;
}
}
public void clear() {
equiv.clear();
}
}
|
Make EOF LineFeed run last | <?php
/*
* This file is part of the PHP CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class EndOfFileLineFeedFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{
// [Structure] A file must always ends with a linefeed character
$content = rtrim($content);
if (strlen($content)) {
return $content."\n";
}
return $content;
}
public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}
public function getPriority()
{
// must run last to be sure the file is properly formatted before it runs
return -50;
}
public function supports(\SplFileInfo $file)
{
return true;
}
public function getName()
{
return 'eof_ending';
}
public function getDescription()
{
return 'A file must always ends with an empty line feed.';
}
}
| <?php
/*
* This file is part of the PHP CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class EndOfFileLineFeedFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{
// [Structure] A file must always ends with a linefeed character
$content = rtrim($content);
if (strlen($content)) {
return $content."\n";
}
return $content;
}
public function getLevel()
{
return FixerInterface::ALL_LEVEL;
}
public function getPriority()
{
return 0;
}
public function supports(\SplFileInfo $file)
{
return true;
}
public function getName()
{
return 'eof_ending';
}
public function getDescription()
{
return 'A file must always ends with an empty line feed.';
}
}
|
Hide stderr output when calling get to get version | #
# Copyright 2015 Yasser Gonzalez Fernandez
#
# 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
#
"""Calculation of optimal configuration processes.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version="0.5.1"):
try:
# Get version from the git repo, if installed in editable mode.
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
git_dir = os.path.join(src_dir, ".git")
git_args = ("git", "--work-tree", src_dir, "--git-dir",
git_dir, "describe", "--tags", "--always")
output = subprocess.check_output(git_args, stderr=subprocess.DEVNULL)
version = output.decode("utf-8").strip()
if version.rfind("-") >= 0:
version = version[:version.rfind("-")] # strip SHA1 hash
version = version.replace("-", ".post") # PEP 440 compatible
except Exception:
pass # fallback to the hardcoded version
return version
__version__ = _get_version()
| #
# Copyright 2015 Yasser Gonzalez Fernandez
#
# 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
#
"""Calculation of optimal configuration processes.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version="0.5.1"):
try:
# Get version from the git repo, if installed in editable mode.
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
git_dir = os.path.join(src_dir, ".git")
git_args = ("git", "--work-tree", src_dir, "--git-dir",
git_dir, "describe", "--tags", "--always")
output = subprocess.check_output(git_args)
version = output.decode("utf-8").strip()
if version.rfind("-") >= 0:
version = version[:version.rfind("-")] # strip SHA1 hash
version = version.replace("-", ".post") # PEP 440 compatible
except Exception:
pass # fallback to the hardcoded version
return version
__version__ = _get_version()
|
Update collections.Callable typecheck to collections.abc.Callable | # -*- coding: utf-8 -*-
import warnings
from collections.abc import Callable
from django.conf import settings
from django.utils.module_loading import import_string
def su_login_callback(user):
if hasattr(settings, 'SU_LOGIN'):
warnings.warn(
"SU_LOGIN is deprecated, use SU_LOGIN_CALLBACK",
DeprecationWarning,
)
func = getattr(settings, 'SU_LOGIN_CALLBACK', None)
if func is not None:
if not isinstance(func, Callable):
func = import_string(func)
return func(user)
return user.has_perm('auth.change_user')
def custom_login_action(request, user):
func = getattr(settings, 'SU_CUSTOM_LOGIN_ACTION', None)
if func is None:
return False
if not isinstance(func, Callable):
func = import_string(func)
func(request, user)
return True
| # -*- coding: utf-8 -*-
import warnings
import collections
from django.conf import settings
from django.utils.module_loading import import_string
def su_login_callback(user):
if hasattr(settings, 'SU_LOGIN'):
warnings.warn(
"SU_LOGIN is deprecated, use SU_LOGIN_CALLBACK",
DeprecationWarning,
)
func = getattr(settings, 'SU_LOGIN_CALLBACK', None)
if func is not None:
if not isinstance(func, collections.Callable):
func = import_string(func)
return func(user)
return user.has_perm('auth.change_user')
def custom_login_action(request, user):
func = getattr(settings, 'SU_CUSTOM_LOGIN_ACTION', None)
if func is None:
return False
if not isinstance(func, collections.Callable):
func = import_string(func)
func(request, user)
return True
|
Make departures a plain array
The ArrayProxy was a remnant of the previous departureFetcher | import Ember from 'ember';
import DepartureFetcher from 'bus-detective/utils/departure-fetcher';
let { run, computed } = Ember;
const MAXIMUM_DURATION_IN_HOURS = 12;
export default Ember.Component.extend({
stop: null,
departures: null,
fetcher: null,
canLoadMore: computed.lt('fetcher.duration', MAXIMUM_DURATION_IN_HOURS),
hasFetched: computed.alias('fetcher.hasFetched'),
init() {
this._super(...arguments);
this.set('fetcher', DepartureFetcher.create({ stopId: this.get('stop.id') }));
this.get('fetcher').on('didFetch', run.bind(this, 'updateDepartures'))
},
didInsertElement() {
this.get('fetcher').startFetching();
},
willDestroyElement() {
this.get('fetcher').stopFetching();
},
updateDepartures(departures) {
this.set('departures', departures);
this.sendAction('onLoad', departures);
},
actions: {
loadMore() {
this.get('fetcher').increaseDuration();
}
}
});
| import Ember from 'ember';
import DepartureFetcher from 'bus-detective/utils/departure-fetcher';
let { run, computed } = Ember;
const MAXIMUM_DURATION_IN_HOURS = 12;
export default Ember.Component.extend({
stop: null,
departures: null,
fetcher: null,
canLoadMore: computed.lt('fetcher.duration', MAXIMUM_DURATION_IN_HOURS),
hasFetched: computed.alias('fetcher.hasFetched'),
init() {
this._super(...arguments);
this.set('departures', Ember.ArrayProxy.create({ content: [] }));
this.set('fetcher', DepartureFetcher.create({ stopId: this.get('stop.id') }));
this.get('fetcher').on('didFetch', run.bind(this, 'updateDepartures'))
},
didInsertElement() {
this.get('fetcher').startFetching();
},
willDestroyElement() {
this.get('fetcher').stopFetching();
},
updateDepartures(departures) {
this.get('departures').clear().pushObjects(departures);
this.sendAction('onLoad', this.get('departures'))
},
actions: {
loadMore() {
this.get('fetcher').increaseDuration();
}
}
});
|
Update long description and url | from setuptools import setup
config = {
'name': 'timew-report',
'version': '0.0.0',
'description': 'An interface for TimeWarrior report data',
'long_description': '\n' + open('README.md').read(),
'url': 'https://github.com/lauft/timew-report.git',
'author': 'Thomas Lauf',
'author_email': 'Thomas.Lauf@tngtech.com',
'license': 'MIT License',
'classifiers': [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
'keywords': 'timewarrior taskwarrior time-tracking',
'packages': ['timewreport'],
'install_requires': ['python-dateutil'],
}
setup(**config)
| from setuptools import setup
config = {
'name': 'timew-report',
'version': '0.0.0',
'description': 'An interface for TimeWarrior report data',
'author': 'Thomas Lauf',
'author_email': 'Thomas.Lauf@tngtech.com',
'license': 'MIT License',
'classifiers': [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
'keywords': 'timewarrior taskwarrior time-tracking',
'packages': ['timewreport'],
'install_requires': ['python-dateutil'],
}
setup(**config)
|
Improve error message for missing classes | const parse = require("./parser");
const { getClass, getFormattedId } = require("./objects");
const interpret = require("./virtualMachine");
function main({ runtime, data, system, log }) {
const program = parse(data);
// Set the System global
program.variables[0].setValue(system);
// Replace class hashes with actual JavaScript classes from the runtime
program.classes = program.classes.map(hash => {
const resolved = runtime[hash];
if (resolved == null && log) {
const klass = getClass(hash);
console.warn(
`Class missing from runtime: ${hash}`,
klass == null
? `(formatted ID: ${getFormattedId(hash)})`
: `expected ${klass.name}`
);
}
return resolved;
});
// Bind toplevel handlers.
program.bindings.forEach(binding => {
const handler = () => {
return interpret(binding.commandOffset, program, { log });
};
// For now we only know how to handle System handlers.
if (binding.variableOffset === 0) {
const obj = program.variables[binding.variableOffset].getValue();
const method = program.methods[binding.methodOffset];
obj[method.name](handler);
} else {
console.warn(
"Not Implemented: Not binding to non-system events",
binding
);
}
});
system._start();
}
module.exports = main;
| const parse = require("./parser");
const { getClass } = require("./objects");
const interpret = require("./virtualMachine");
function main({ runtime, data, system, log }) {
const program = parse(data);
// Set the System global
program.variables[0].setValue(system);
// Replace class hashes with actual JavaScript classes from the runtime
program.classes = program.classes.map(hash => {
const resolved = runtime[hash];
if (resolved == null && log) {
const klass = getClass(hash);
console.warn(
`Class missing from runtime: ${hash} expected ${klass.name}`
);
}
return resolved;
});
// Bind toplevel handlers.
program.bindings.forEach(binding => {
const handler = () => {
return interpret(binding.commandOffset, program, { log });
};
// For now we only know how to handle System handlers.
if (binding.variableOffset === 0) {
const obj = program.variables[binding.variableOffset].getValue();
const method = program.methods[binding.methodOffset];
obj[method.name](handler);
} else {
console.warn(
"Not Implemented: Not binding to non-system events",
binding
);
}
});
system._start();
}
module.exports = main;
|
Remove Linux/android@5.1 from automated tests | var args = require('yargs').argv;
module.exports = {
extraScripts: args.dom === 'shadow' ? ['test/enable-shadow-dom.js'] : [],
registerHooks: function(context) {
// The Good
var crossPlatforms = [
'Windows 10/chrome@55',
'Windows 10/firefox@50'
];
// The Bad
var otherPlatforms = [
'OS X 10.11/iphone@9.3',
'OS X 10.11/ipad@9.3',
'Windows 10/microsoftedge@13',
'Windows 10/internet explorer@11',
'OS X 10.11/safari@10.0'
];
// run SauceLabs tests for pushes, except cases when branch contains 'quick/'
if (process.env.TRAVIS_EVENT_TYPE === 'push' && process.env.TRAVIS_BRANCH.indexOf('quick/') === -1) {
// crossPlatforms are not tested here, but in Selenium WebDriver (see .travis.yml)
context.options.plugins.sauce.browsers = otherPlatforms;
// Run SauceLabs for daily builds, triggered by cron
} else if (process.env.TRAVIS_EVENT_TYPE === 'cron') {
context.options.plugins.sauce.browsers = crossPlatforms.concat(otherPlatforms);
}
}
};
| var args = require('yargs').argv;
module.exports = {
extraScripts: args.dom === 'shadow' ? ['test/enable-shadow-dom.js'] : [],
registerHooks: function(context) {
// The Good
var crossPlatforms = [
'Windows 10/chrome@55',
'Windows 10/firefox@50'
];
// The Bad
var otherPlatforms = [
'OS X 10.11/iphone@9.3',
'OS X 10.11/ipad@9.3',
'Linux/android@5.1',
'Windows 10/microsoftedge@13',
'Windows 10/internet explorer@11',
'OS X 10.11/safari@10.0'
];
// run SauceLabs tests for pushes, except cases when branch contains 'quick/'
if (process.env.TRAVIS_EVENT_TYPE === 'push' && process.env.TRAVIS_BRANCH.indexOf('quick/') === -1) {
// crossPlatforms are not tested here, but in Selenium WebDriver (see .travis.yml)
context.options.plugins.sauce.browsers = otherPlatforms;
// Run SauceLabs for daily builds, triggered by cron
} else if (process.env.TRAVIS_EVENT_TYPE === 'cron') {
context.options.plugins.sauce.browsers = crossPlatforms.concat(otherPlatforms);
}
}
};
|
feat: Allow changing password of any user from command line | <?php
namespace App\Console\Commands\Admin;
use App\Console\Commands\Traits\AskForPassword;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Contracts\Hashing\Hasher as Hash;
class ChangePasswordCommand extends Command
{
use AskForPassword;
protected $signature = "koel:admin:change-password
{email? : The user's email. If empty, will get the default admin user.}";
protected $description = "Change a user's password";
private $hash;
public function __construct(Hash $hash)
{
parent::__construct();
$this->hash = $hash;
}
public function handle(): void
{
$email = $this->argument('email');
/** @var User|null $user */
$user = $email ? User::where('email', $email)->first() : User::where('is_admin', true)->first();
if (!$user) {
$this->error('The user account cannot be found.');
return;
}
$this->comment("Changing the user's password (ID: {$user->id}, email: {$user->email})");
$user->password = $this->hash->make($this->askForPassword());
$user->save();
$this->comment('Alrighty, the new password has been saved. Enjoy! 👌');
}
}
| <?php
namespace App\Console\Commands\Admin;
use App\Console\Commands\Traits\AskForPassword;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Contracts\Hashing\Hasher as Hash;
class ChangePasswordCommand extends Command
{
use AskForPassword;
protected $name = 'koel:admin:change-password';
protected $description = "Change the default admin's password";
private $hash;
public function __construct(Hash $hash)
{
parent::__construct();
$this->hash = $hash;
}
public function handle(): void
{
/** @var User|null $user */
$user = User::where('is_admin', true)->first();
if (!$user) {
$this->error('An admin account cannot be found. Have you set up Koel yet?');
return;
}
$this->comment("Changing the default admin's password (ID: {$user->id}, email: {$user->email})");
$user->password = $this->hash->make($this->askForPassword());
$user->save();
$this->comment('Alrighty, your new password has been saved. Enjoy! 👌');
}
}
|
Remove conditional sql-select on new user creation
Only create a user profile if a new user is actually
created. | import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
class UserProfile(models.Model):
user = models.OneToOneField(User)
secret_key = models.CharField(max_length=32, blank=False,
help_text='Secret key for feed and API access')
class Meta:
db_table = 'comics_user_profile'
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.generate_new_secret_key()
def __unicode__(self):
return u'User profile for %s' % self.user
def generate_new_secret_key(self):
self.secret_key = uuid.uuid4().hex
| import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
UserProfile.objects.get_or_create(user=instance)
class UserProfile(models.Model):
user = models.OneToOneField(User)
secret_key = models.CharField(max_length=32, blank=False,
help_text='Secret key for feed and API access')
class Meta:
db_table = 'comics_user_profile'
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.generate_new_secret_key()
def __unicode__(self):
return u'User profile for %s' % self.user
def generate_new_secret_key(self):
self.secret_key = uuid.uuid4().hex
|
Update WSDL integration test for 0.6.7
The generated soap.scala file is now named soap12.scala. | package org.scalaxb.maven.it;
import org.junit.Test;
public class ITP03WSDL extends AbstractIT {
private String[] expected = new String[] {
"generated/stockquote.scala",
"generated/xmlprotocol.scala",
"scalaxb/httpclients_dispatch.scala",
"scalaxb/scalaxb.scala",
"scalaxb/soap12.scala",
"soapenvelope12/soapenvelope12.scala",
"soapenvelope12/soapenvelope12_xmlprotocol.scala"
};
@Test
public void filesAreGeneratedInCorrectLocation() {
assertFilesGenerated("itp03-wsdl", expected);
}
}
| package org.scalaxb.maven.it;
import org.junit.Test;
public class ITP03WSDL extends AbstractIT {
private String[] expected = new String[] {
"generated/stockquote.scala",
"generated/xmlprotocol.scala",
"scalaxb/httpclients_dispatch.scala",
"scalaxb/scalaxb.scala",
"scalaxb/soap.scala",
"soapenvelope12/soapenvelope12.scala",
"soapenvelope12/soapenvelope12_xmlprotocol.scala"
};
@Test
public void filesAreGeneratedInCorrectLocation() {
assertFilesGenerated("itp03-wsdl", expected);
}
}
|
Set kCurrentContext::$ps_vesion = 'ps3' to support dynamic enums in mrss feeds
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@63256 6b8eccd3-e8c5-4e7d-8186-e12b5326b719 | <?php
$start = microtime(true);
set_time_limit(0);
require_once(dirname(__FILE__).'/../../alpha/config/sfrootdir.php');
// check cache before loading anything
require_once("../lib/KalturaResponseCacher.php");
$cache = new KalturaResponseCacher();
$cache->checkOrStart();
require_once("../bootstrap.php");
KalturaLog::setContext("syndicationFeedRenderer");
KalturaLog::debug(">------------------------------------- syndicationFeedRenderer -------------------------------------");
KalturaLog::info("syndicationFeedRenderer-start ");
kCurrentContext::$ps_vesion = 'ps3';
$feedId = $_GET['feedId'];
$entryId = @$_GET['entryId'];
try
{
$syndicationFeedRenderer = new KalturaSyndicationFeedRenderer($feedId);
$syndicationFeedRenderer->addFlavorParamsAttachedFilter();
if (isset($entryId))
$syndicationFeedRenderer->addEntryAttachedFilter($entryId);
$syndicationFeedRenderer->execute();
}
catch(Exception $ex)
{
header('KalturaSyndication: '.$ex->getMessage());
die;
}
$end = microtime(true);
KalturaLog::info("syndicationFeedRenderer-end [".($end - $start)."]");
KalturaLog::debug("<------------------------------------- syndicationFeedRenderer -------------------------------------");
$cache->end();
?> | <?php
$start = microtime(true);
set_time_limit(0);
require_once(dirname(__FILE__).'/../../alpha/config/sfrootdir.php');
// check cache before loading anything
require_once("../lib/KalturaResponseCacher.php");
$cache = new KalturaResponseCacher();
$cache->checkOrStart();
require_once("../bootstrap.php");
KalturaLog::setContext("syndicationFeedRenderer");
KalturaLog::debug(">------------------------------------- syndicationFeedRenderer -------------------------------------");
KalturaLog::info("syndicationFeedRenderer-start ");
$feedId = $_GET['feedId'];
$entryId = @$_GET['entryId'];
try
{
$syndicationFeedRenderer = new KalturaSyndicationFeedRenderer($feedId);
$syndicationFeedRenderer->addFlavorParamsAttachedFilter();
if (isset($entryId))
$syndicationFeedRenderer->addEntryAttachedFilter($entryId);
$syndicationFeedRenderer->execute();
}
catch(Exception $ex)
{
header('KalturaSyndication: '.$ex->getMessage());
die;
}
$end = microtime(true);
KalturaLog::info("syndicationFeedRenderer-end [".($end - $start)."]");
KalturaLog::debug("<------------------------------------- syndicationFeedRenderer -------------------------------------");
$cache->end();
?> |
Fix some texts (again lol) | import React from 'react'
const WelcomeMessage = () => (
<div className="welcome-message-container">
<div className="logo">
<img src="images/logo.svg" />
</div>
<div className="welcome-message-text text">Peut-être avez-vous déjà entendu ce type de réflexions :</div>
<div className="welcome-message-text text">"Il a bien une tête de gaucho, lui !" ou "Il a pas une dégaine à voter Mitterand..."</div>
<div className="welcome-message-text text"><i>Gauche ou Droite ?</i> a pour objectif de vérifier ces affirmations.</div>
<div className="welcome-message-text text">Le bord politique d'un député se reconnaît-il au premier coup d'oeil ? Nos amis de l'assemblée sont-ils victimes de délit de faciès ?</div>
<div className="welcome-message-text text">À vous de nous le dire !</div>
</div>
)
export default WelcomeMessage
| import React from 'react'
const WelcomeMessage = () => (
<div className="welcome-message-container">
<div className="logo">
<img src="images/logo.svg" />
</div>
<div className="welcome-message-text text">Avez-vous déjà entendu des réflexions de ce genre :</div>
<div className="welcome-message-text text">"Il a bien une tête de gaucho, lui !" ou "Il a pas une dégaine à voter Mitterand..."</div>
<div className="welcome-message-text text"><i>Gauche ou Droite ?</i> a pour objectif de tester cette afirmation.</div>
<div className="welcome-message-text text">Le bord politique d'un député se reconnaît-il au premier coup d'oeil ? Nos amis de l'assemblée sont-ils victimes de délit de faciès ?</div>
<div className="welcome-message-text text">À vous de nous le dire !</div>
</div>
)
export default WelcomeMessage
|
Improve initial check for `data-models` dir | 'use strict';
const path = require('path');
const assert = require('assert');
const fs = require('fs');
module.exports = {
name: require('./package').name,
included() {
const app = this._findHost();
const addonConfig = this.app.project.config(app.env)['orbit'] || {};
const collections = addonConfig.collections || {};
const modelsDir = collections.models || 'data-models';
let modelsPath;
if (
app.project.pkg['ember-addon'] &&
app.project.pkg['ember-addon'].configPath
) {
modelsPath = path.join('tests', 'dummy', 'app', modelsDir);
} else {
modelsPath = path.join('app', modelsDir);
}
const modelsDirectory = path.join(app.project.root, modelsPath);
assert(
fs.existsSync(modelsDirectory),
`[ember-orbit] The models directory is missing: "${modelsDirectory}". You can run 'ember g ember-orbit' to initialize ember-orbit and create this directory.`
);
this._super.included.apply(this, arguments);
}
};
| 'use strict';
const path = require('path');
const assert = require('assert');
const fs = require('fs');
module.exports = {
name: require('./package').name,
included() {
const app = this._findHost();
const addonConfig = this.app.project.config(app.env)['orbit'] || {};
const collections = addonConfig.collections || {};
let modelsPath;
if (collections.models) {
modelsPath = path.join('app', collections.models);
} else if (
app.project.pkg['ember-addon'] &&
app.project.pkg['ember-addon'].configPath
) {
modelsPath = path.join('tests', 'dummy', 'app', 'data-models');
} else {
modelsPath = path.join('app', 'data-models');
}
const modelsDirectory = path.join(app.project.root, modelsPath);
assert(
fs.existsSync(modelsDirectory),
`You need to create models directory: "${modelsDirectory}"`
);
this._super.included.apply(this, arguments);
}
};
|
Update CodeArtifact per 2020-11-05 changes | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 25.0.0
from . import AWSObject
from troposphere import Tags
class Domain(AWSObject):
resource_type = "AWS::CodeArtifact::Domain"
props = {
'DomainName': (basestring, True),
'EncryptionKey': (basestring, False),
'PermissionsPolicyDocument': (dict, False),
'Tags': (Tags, False),
}
class Repository(AWSObject):
resource_type = "AWS::CodeArtifact::Repository"
props = {
'Description': (basestring, False),
'DomainName': (basestring, True),
'DomainOwner': (basestring, False),
'ExternalConnections': ([basestring], False),
'PermissionsPolicyDocument': (dict, False),
'RepositoryName': (basestring, True),
'Tags': (Tags, False),
'Upstreams': ([basestring], False),
}
| # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 18.7.0
from . import AWSObject
class Domain(AWSObject):
resource_type = "AWS::CodeArtifact::Domain"
props = {
'DomainName': (basestring, True),
'PermissionsPolicyDocument': (dict, False),
}
class Repository(AWSObject):
resource_type = "AWS::CodeArtifact::Repository"
props = {
'Description': (basestring, False),
'DomainName': (basestring, True),
'DomainOwner': (basestring, False),
'ExternalConnections': ([basestring], False),
'PermissionsPolicyDocument': (dict, False),
'RepositoryName': (basestring, True),
'Upstreams': ([basestring], False),
}
|
Stop adding translation function to builtins
In unittests __init__ translation function is still being added to
builtins, this is not required anymore as it is not being installed.
Change-Id: I19da395b72622a6db348f5a6dd569c7747eaa40d | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
:mod:`ironic.tests.unit` -- ironic unit tests
=====================================================
.. automodule:: ironic.tests.unit
:platform: Unix
"""
# TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR
import eventlet
eventlet.monkey_patch(os=False)
| # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
:mod:`ironic.tests.unit` -- ironic unit tests
=====================================================
.. automodule:: ironic.tests.unit
:platform: Unix
"""
# TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR
import eventlet
eventlet.monkey_patch(os=False)
# See http://code.google.com/p/python-nose/issues/detail?id=373
# The code below enables nosetests to work with i18n _() blocks
import six.moves.builtins as __builtin__
setattr(__builtin__, '_', lambda x: x)
|
Change flag names to lower case | package main
import (
"flag"
"fmt"
)
const CompareAndSwapUsage = `usage: etcdctl [etcd flags] compareAndSwap <key> <value> [testAndSet flags]
either prevvalue or previndex needs to be given
special flags: --ttl to set a key with ttl
--prevvalue to set the previous value
--previndex to set the previous index`
var (
compareAndSwapFlag = flag.NewFlagSet("testAndSet", flag.ExitOnError)
compareAndSwapTtl = compareAndSwapFlag.Uint64("ttl", 0, "ttl of the key")
compareAndSwapPvalue = compareAndSwapFlag.String("prevvalue", "", "previous value")
compareAndSwapPindex = compareAndSwapFlag.Uint64("previndex", 0, "previous index")
)
func init() {
// The minimum number of arguments is 3 because
// there needs to be either pvalue or pindex
registerCommand("compareAndSwap", CompareAndSwapUsage, 3, 6, compareAndSwap)
}
func compareAndSwap(args []string) error {
key := args[0]
value := args[1]
compareAndSwapFlag.Parse(args[2:])
resp, err := client.CompareAndSwap(key, value,
*compareAndSwapTtl, *compareAndSwapPvalue, *compareAndSwapPindex)
if debug {
fmt.Println(<-curlChan)
}
if err != nil {
return err
}
output(resp)
return nil
}
| package main
import (
"flag"
"fmt"
)
const CompareAndSwapUsage = `usage: etcdctl [etcd flags] compareAndSwap <key> <value> [testAndSet flags]
either prevValue or prevIndex needs to be given
special flags: --ttl to set a key with ttl
--prevValue to set the previous value
--prevIndex to set the previous index`
var (
compareAndSwapFlag = flag.NewFlagSet("testAndSet", flag.ExitOnError)
compareAndSwapTtl = compareAndSwapFlag.Uint64("ttl", 0, "ttl of the key")
compareAndSwapPvalue = compareAndSwapFlag.String("prevValue", "", "previous value")
compareAndSwapPindex = compareAndSwapFlag.Uint64("prevIndex", 0, "previous index")
)
func init() {
// The minimum number of arguments is 3 because
// there needs to be either pvalue or pindex
registerCommand("compareAndSwap", CompareAndSwapUsage, 3, 6, compareAndSwap)
}
func compareAndSwap(args []string) error {
key := args[0]
value := args[1]
compareAndSwapFlag.Parse(args[2:])
resp, err := client.CompareAndSwap(key, value,
*compareAndSwapTtl, *compareAndSwapPvalue, *compareAndSwapPindex)
if debug {
fmt.Println(<-curlChan)
}
if err != nil {
return err
}
output(resp)
return nil
}
|
Remove menu test that display menu | define([
'modules/MainMenu/src/MainMenuModel',
'modules/MainMenu/src/MainMenuController',
'modules/MainMenu/src/MainMenuView',
'modules/Harmonizer/src/HarmonizerController',
'modules/Harmonizer/src/HarmonizerView',
], function(MainMenuModel, MainMenuController, MainMenuView, HarmonizerController, HarmonizerView) {
return {
run: function() {
test("MainMenuController", function(assert) {
var menu = new MainMenuModel();
var menuView = new MainMenuView(menu, document.getElementsByTagName('body')[0]);
var mmc = new MainMenuController(menu, menuView);
assert.ok(mmc instanceof MainMenuController);
/*$.subscribe('MainMenuView-ready', function(el) {
var hv = new HarmonizerView($('#main_menu_second_level')[0]);
var hc = new HarmonizerController(undefined,hv);
menu.addMenu({title:'Harmonizer', view: hv});
});*/
});
}
};
}); | define([
'modules/MainMenu/src/MainMenuModel',
'modules/MainMenu/src/MainMenuController',
'modules/MainMenu/src/MainMenuView',
'modules/Harmonizer/src/HarmonizerController',
'modules/Harmonizer/src/HarmonizerView',
], function(MainMenuModel, MainMenuController, MainMenuView, HarmonizerController, HarmonizerView) {
return {
run: function() {
test("MainMenuController", function(assert) {
var menu = new MainMenuModel();
var menuView = new MainMenuView(menu, document.getElementsByTagName('body')[0]);
var mmc = new MainMenuController(menu, menuView);
assert.ok(mmc instanceof MainMenuController);
$.subscribe('MainMenuView-ready', function(el) {
var hv = new HarmonizerView($('#main_menu_second_level')[0]);
var hc = new HarmonizerController(undefined,hv);
menu.addMenu({title:'Harmonizer', view: hv});
});
});
}
};
}); |
Add package comment and TODO | // Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package merkle provides Merkle tree interfaces and implementation.
package merkle
// TODO(pavelkalinnikov): Remove this root package. The only interface provided
// here does not have to exist, and can be [re-]defined on the user side, such
// as in compact or proof package.
// LogHasher provides the hash functions needed to compute dense merkle trees.
type LogHasher interface {
// EmptyRoot supports returning a special case for the root of an empty tree.
EmptyRoot() []byte
// HashLeaf computes the hash of a leaf that exists.
HashLeaf(leaf []byte) []byte
// HashChildren computes interior nodes.
HashChildren(l, r []byte) []byte
// Size returns the number of bytes the Hash* functions will return.
Size() int
}
| // Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package merkle
// LogHasher provides the hash functions needed to compute dense merkle trees.
type LogHasher interface {
// EmptyRoot supports returning a special case for the root of an empty tree.
EmptyRoot() []byte
// HashLeaf computes the hash of a leaf that exists.
HashLeaf(leaf []byte) []byte
// HashChildren computes interior nodes.
HashChildren(l, r []byte) []byte
// Size returns the number of bytes the Hash* functions will return.
Size() int
}
|
Add Netware parser test to all test suite
git-svn-id: 8e7fc3cb9b5e494b5390f56e4b66b18dc2b2e92b@394701 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Created on Apr 5, 2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.apache.commons.net.ftp.parser;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @author scohen
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class AllTests {
public static Test suite() {
TestSuite suite =
new TestSuite("Test for org.apache.commons.net.ftp.parser");
//$JUnit-BEGIN$
suite.addTest(FTPTimestampParserImplTest.suite());
suite.addTest(OS2FTPEntryParserTest.suite());
suite.addTest(VMSFTPEntryParserTest.suite());
suite.addTest(UnixFTPEntryParserTest.suite());
suite.addTestSuite(DefaultFTPFileEntryParserFactoryTest.class);
suite.addTest(EnterpriseUnixFTPEntryParserTest.suite());
suite.addTest(OS400FTPEntryParserTest.suite());
suite.addTest(NTFTPEntryParserTest.suite());
suite.addTest(MVSFTPEntryParserTest.suite());
suite.addTest(NetwareFTPEntryParserTest.suite());
//$JUnit-END$
return suite;
}
}
| /*
* Created on Apr 5, 2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.apache.commons.net.ftp.parser;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @author scohen
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class AllTests {
public static Test suite() {
TestSuite suite =
new TestSuite("Test for org.apache.commons.net.ftp.parser");
//$JUnit-BEGIN$
suite.addTest(FTPTimestampParserImplTest.suite());
suite.addTest(OS2FTPEntryParserTest.suite());
suite.addTest(VMSFTPEntryParserTest.suite());
suite.addTest(UnixFTPEntryParserTest.suite());
suite.addTestSuite(DefaultFTPFileEntryParserFactoryTest.class);
suite.addTest(EnterpriseUnixFTPEntryParserTest.suite());
suite.addTest(OS400FTPEntryParserTest.suite());
suite.addTest(NTFTPEntryParserTest.suite());
suite.addTest(MVSFTPEntryParserTest.suite());
//$JUnit-END$
return suite;
}
}
|
Remove ipdb to get rid of spam warnings. | import requests
import mc_config
import psycopg2
import psycopg2.extras
import time
def get_solr_location():
##TODO -- get this from the yaml file
return 'http://localhost:8983'
def get_solr_collection_url_prefix():
return get_solr_location() + '/solr/collection1'
def solr_request( path, params):
url = get_solr_collection_url_prefix() + '/' + path
print 'url: {}'.format( url )
params['wt'] = 'json'
r = requests.get( url, params=params, headers = { 'Accept': 'application/json'})
print 'request url '
print r.url
data = r.json()
return data
def dataimport_command( command, params={}):
params['command'] = command
return solr_request( 'dataimport', params )
def dataimport_status():
return dataimport_command( 'status' )
def dataimport_delta_import():
params = {
'commit': 'true',
'clean': 'false',
}
##Note: We're using the delta import through full import approach
return dataimport_command( 'full-import', params )
def dataimport_full_import():
params = {
'commit': 'true',
'clean': 'true',
}
##Note: We're using the delta import through full import approach
return dataimport_command( 'full-import', params )
def dataimport_reload_config():
return dataimport_command( 'reload' )
| import requests
import ipdb
import mc_config
import psycopg2
import psycopg2.extras
import time
def get_solr_location():
##TODO -- get this from the yaml file
return 'http://localhost:8983'
def get_solr_collection_url_prefix():
return get_solr_location() + '/solr/collection1'
def solr_request( path, params):
url = get_solr_collection_url_prefix() + '/' + path
print 'url: {}'.format( url )
params['wt'] = 'json'
r = requests.get( url, params=params, headers = { 'Accept': 'application/json'})
print 'request url '
print r.url
data = r.json()
return data
def dataimport_command( command, params={}):
params['command'] = command
return solr_request( 'dataimport', params )
def dataimport_status():
return dataimport_command( 'status' )
def dataimport_delta_import():
params = {
'commit': 'true',
'clean': 'false',
}
##Note: We're using the delta import through full import approach
return dataimport_command( 'full-import', params )
def dataimport_full_import():
params = {
'commit': 'true',
'clean': 'true',
}
##Note: We're using the delta import through full import approach
return dataimport_command( 'full-import', params )
def dataimport_reload_config():
return dataimport_command( 'reload' )
|
Use global assert in lib | var assert = require('assert'),
fs = require('fs'),
glob = require('glob'),
path = require('path'),
wrench = require('wrench');
var counter = 0;
try { fs.mkdirSync('/tmp/lumbar-test', 0755); } catch (err) {}
exports.testDir = function(testName, configFile) {
var outdir = '/tmp/lumbar-test/' + testName + '-' + path.basename(configFile) + '-' + Date.now() + '-' + (counter++);
console.log('Creating test directory ' + outdir + ' for ' + configFile);
fs.mkdirSync(outdir, 0755);
return outdir;
};
exports.assertExpected = function(outdir, expectedDir, configFile) {
var expectedFiles = glob.globSync(expectedDir + '/**/*.*').map(function(fileName) { return fileName.substring(expectedDir.length); }),
generatedFiles = glob.globSync(outdir + '/**/*.*').map(function(fileName) { return fileName.substring(outdir.length); });
assert.deepEqual(generatedFiles, expectedFiles, configFile + ': file list matches' + JSON.stringify(expectedFiles) + JSON.stringify(generatedFiles));
generatedFiles.forEach(function(fileName) {
var generatedContent = fs.readFileSync(outdir + fileName, 'utf8'),
expectedContent = fs.readFileSync(expectedDir + fileName, 'utf8');
assert.equal(generatedContent, expectedContent, configFile + ':' + fileName + ': content matches');
});
};
| var fs = require('fs'),
glob = require('glob'),
path = require('path'),
wrench = require('wrench');
var counter = 0;
try { fs.mkdirSync('/tmp/lumbar-test', 0755); } catch (err) {}
exports.testDir = function(testName, configFile) {
var outdir = '/tmp/lumbar-test/' + testName + '-' + path.basename(configFile) + '-' + Date.now() + '-' + (counter++);
console.log('Creating test directory ' + outdir + ' for ' + configFile);
fs.mkdirSync(outdir, 0755);
return outdir;
};
exports.assertExpected = function(outdir, expectedDir, configFile, assert) {
var expectedFiles = glob.globSync(expectedDir + '/**/*.*').map(function(fileName) { return fileName.substring(expectedDir.length); }),
generatedFiles = glob.globSync(outdir + '/**/*.*').map(function(fileName) { return fileName.substring(outdir.length); });
assert.deepEqual(generatedFiles, expectedFiles, configFile + ': file list matches' + JSON.stringify(expectedFiles) + JSON.stringify(generatedFiles));
generatedFiles.forEach(function(fileName) {
var generatedContent = fs.readFileSync(outdir + fileName, 'utf8'),
expectedContent = fs.readFileSync(expectedDir + fileName, 'utf8');
assert.equal(generatedContent, expectedContent, configFile + ':' + fileName + ': content matches');
});
};
|
Fix problem related to the teacheradmin form, exclude owner | # Copyright 2012 Rooter Analysis S.L.
#
# 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 django.forms import ModelForm
from django.forms.util import ErrorDict
from moocng.courses.models import Course
class CourseForm(ModelForm):
class Meta:
model = Course
exclude = ('slug', 'teachers', 'owner',)
def get_pretty_errors(self):
errors = ErrorDict()
for k, v in self.errors.items():
name = self.fields[k].label
errors[name] = v
return errors
| # Copyright 2012 Rooter Analysis S.L.
#
# 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 django.forms import ModelForm
from django.forms.util import ErrorDict
from moocng.courses.models import Course
class CourseForm(ModelForm):
class Meta:
model = Course
exclude = ('slug', 'teachers',)
def get_pretty_errors(self):
errors = ErrorDict()
for k, v in self.errors.items():
name = self.fields[k].label
errors[name] = v
return errors
|
Update to remove requirement for unused 'lexicons' dir | from setuptools import setup, find_packages
package = 'bsdetector'
version = '0.1'
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
# class PostDevelopCommand(develop):
# """Post-installation for development mode."""
# def run(self):
# # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION
# develop.run(self)
class PostInstallCommand(install):
"""Post-installation for installation mode."""
def run(self):
# PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION
import nltk
nltk.download('punkt')
install.run(self)
print(find_packages('bsdetector'))
setup(name=package,
version=version,
packages=['bsdetector', 'additional_resources'],
install_requires=['decorator', 'requests', 'textstat', 'vaderSentiment',
'pattern', 'nltk', 'pytest'],
package_dir={'bsdetector': 'bsdetector'},
# data_files=[('bsdetector', ['bsdetector/lexicon.json'])],
package_data={'bsdetector': ['*.json']},
description="Detects biased statements in online media documents",
url='url',
cmdclass={
# 'develop': PostDevelopCommand,
'install': PostInstallCommand,
}
)
| from setuptools import setup, find_packages
package = 'bsdetector'
version = '0.1'
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
# class PostDevelopCommand(develop):
# """Post-installation for development mode."""
# def run(self):
# # PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION
# develop.run(self)
class PostInstallCommand(install):
"""Post-installation for installation mode."""
def run(self):
# PUT YOUR POST-INSTALL SCRIPT HERE or CALL A FUNCTION
import nltk
nltk.download('punkt')
install.run(self)
print(find_packages('bsdetector'))
setup(name=package,
version=version,
packages=['bsdetector', 'lexicons', 'additional_resources'],
install_requires=['decorator', 'requests', 'textstat', 'vaderSentiment',
'pattern', 'nltk', 'pytest'],
package_dir={'bsdetector': 'bsdetector'},
# data_files=[('bsdetector', ['bsdetector/lexicon.json'])],
package_data={'bsdetector': ['*.json']},
description="Detects biased statements in online media documents",
url='url',
cmdclass={
# 'develop': PostDevelopCommand,
'install': PostInstallCommand,
}
)
|
Disable seccomp in docker to use EasySandbox.😵 | <?php
/**
* Copyright 2017 Liming Jin
*
* 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.
*/
/**
* Created by Liming
* Date: 2016/11/4
* Time: 16:10
*/
namespace Judge;
class CppJudge extends Judger {
protected $filename = 'main.cpp';
/**
* 测试命令行
* @return string
*/
protected function command() {
return sprintf(
'docker run -v %s:/mnt/main.cpp:ro -i --rm --net none --security-opt seccomp=unconfined liming/cpp -t %d -m %d < %s 2>/dev/null',
$this->filename,
$this->time_limit,
$this->memory_limit,
$this->test_case
);
}
}
| <?php
/**
* Copyright 2017 Liming Jin
*
* 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.
*/
/**
* Created by Liming
* Date: 2016/11/4
* Time: 16:10
*/
namespace Judge;
class CppJudge extends Judger {
protected $filename = 'main.cpp';
/**
* 测试命令行
* @return string
*/
protected function command() {
return sprintf(
'docker run -v %s:/mnt/main.cpp:ro -i --rm --net none liming/cpp -t %d -m %d < %s 2>/dev/null',
$this->filename,
$this->time_limit,
$this->memory_limit,
$this->test_case
);
}
}
|
Add enrollment_code to U2F client | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.client.fido.u2f;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterRequestMessage;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterStatus;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
/**
* Еhe endpoint allows to start and finish U2F registration process
*
* @author Yuriy Movchan
* @version August 9, 2017
*/
public interface RegistrationRequestService {
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId);
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId, @QueryParam("enrollment_code") String enrollmentCode);
@POST
@Produces({"application/json"})
public RegisterStatus finishRegistration(@FormParam("username") String userName, @FormParam("tokenResponse") String registerResponseString);
} | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.client.fido.u2f;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterRequestMessage;
import org.xdi.oxauth.model.fido.u2f.protocol.RegisterStatus;
import javax.ws.rs.*;
/**
* Еhe endpoint allows to start and finish U2F registration process
*
* @author Yuriy Movchan
* @version August 9, 2017
*/
public interface RegistrationRequestService {
@GET
@Produces({"application/json"})
public RegisterRequestMessage startRegistration(@QueryParam("username") String userName, @QueryParam("application") String appId, @QueryParam("session_id") String sessionId);
@POST
@Produces({"application/json"})
public RegisterStatus finishRegistration(@FormParam("username") String userName, @FormParam("tokenResponse") String registerResponseString);
} |
Allow modifying settings path through env var. | 'use strict';
const { app } = require('electron');
const fs = require('fs');
const path = require('path');
const { NEGATIVE_SETTINGS_PATH } = process.env;
module.exports = {
init(callback) {
const testSettingsFilePath = NEGATIVE_SETTINGS_PATH && path.resolve(__dirname, NEGATIVE_SETTINGS_PATH);
this.settingsFilePath = path.join(app.getPath('userData'), 'settings.json');
fs.readFile(testSettingsFilePath || this.settingsFilePath, (err, result) => {
if (err) {
this.settings = {};
} else {
try {
this.settings = JSON.parse(result);
} catch (e) {
process.stderr.write(e);
this.settings = {};
}
}
callback();
});
},
get(key) {
return this.settings[key];
},
set(key, value) {
this.settings[key] = value;
},
save(callback) {
fs.writeFile(this.settingsFilePath, JSON.stringify(this.settings), callback);
}
};
| 'use strict';
const { app } = require('electron');
const fs = require('fs');
const path = require('path');
module.exports = {
init(callback) {
this.settingsFilePath = path.join(app.getPath('userData'), 'settings.json');
fs.readFile(this.settingsFilePath, (err, result) => {
if (err) {
this.settings = {};
} else {
try {
this.settings = JSON.parse(result);
} catch (e) {
process.stderr.write(e);
this.settings = {};
}
}
callback();
});
},
get(key) {
return this.settings[key];
},
set(key, value) {
this.settings[key] = value;
},
save(callback) {
fs.writeFile(this.settingsFilePath, JSON.stringify(this.settings), callback);
}
};
|
Fix native unit for the digital information quantity | <?php
/*
* This file is part of Conversion.
*
* (c) 2013 Christoffer Niska
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crisu83\Conversion\Quantity\DigitalInformation;
use Crisu83\Conversion\Quantity\Quantity;
/**
* Class DigitalInformation
* @package Crisu83\Conversion\Quantity\DigitalInformation
*/
class DigitalInformation extends Quantity
{
/**
* @var string native unit name
*/
protected static $native = Unit::KILOBYTE;
/**
* @var array conversion map (unit => native unit)
*/
protected static $conversionMap = array(
Unit::BIT => 0.00012207,
Unit::BYTE => 0.000976563,
Unit::KILOBIT => 0.125,
Unit::KILOBYTE => 1,
Unit::MEGABIT => 128,
Unit::MEGABYTE => 1024,
Unit::GIGABIT => 131072,
Unit::GIGABYTE => 1.049e+6,
Unit::TERABIT => 1.342e+8,
Unit::TERABYTE => 1.074e+9,
Unit::PETABIT => 1.374e+11,
Unit::PETABYTE => 1.1e+12,
);
} | <?php
/*
* This file is part of Conversion.
*
* (c) 2013 Christoffer Niska
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crisu83\Conversion\Quantity\DigitalInformation;
use Crisu83\Conversion\Quantity\Quantity;
/**
* Class DigitalInformation
* @package Crisu83\Conversion\Quantity\DigitalInformation
*/
class DigitalInformation extends Quantity
{
/**
* @var string native unit name
*/
protected static $native = Unit::BYTE;
/**
* @var array conversion map (unit => native unit)
*/
protected static $conversionMap = array(
Unit::BIT => 0.00012207,
Unit::BYTE => 0.000976563,
Unit::KILOBIT => 0.125,
Unit::KILOBYTE => 1,
Unit::MEGABIT => 128,
Unit::MEGABYTE => 1024,
Unit::GIGABIT => 131072,
Unit::GIGABYTE => 1.049e+6,
Unit::TERABIT => 1.342e+8,
Unit::TERABYTE => 1.074e+9,
Unit::PETABIT => 1.374e+11,
Unit::PETABYTE => 1.1e+12,
);
} |
Fix concurrency write to websocket channels | package hub
import (
"sync"
"github.com/gorilla/websocket"
)
var mutex sync.Mutex
type WSClient struct {
ID string
Channel string
Conn *websocket.Conn
}
var (
pool map[string]map[string]*WSClient
)
func init() {
pool = map[string]map[string]*WSClient{}
}
func Add(ID, channel string, conn *websocket.Conn) *WSClient {
mutex.Lock()
defer mutex.Unlock()
c := &WSClient{ID: ID, Channel: channel, Conn: conn}
if pool[c.Channel] == nil {
pool[c.Channel] = map[string]*WSClient{}
}
pool[c.Channel][c.ID] = c
return c
}
func Remove(channel, ID string) {
mutex.Lock()
defer mutex.Unlock()
delete(pool[channel], ID)
}
func Send(channel string, message *Message) (err error) {
mutex.Lock()
defer mutex.Unlock()
for ID := range pool[channel] {
err = pool[channel][ID].Conn.WriteJSON(message)
}
return
}
| package hub
import (
"sync"
"github.com/gorilla/websocket"
)
var mutex sync.Mutex
type WSClient struct {
ID string
Channel string
Conn *websocket.Conn
}
var (
pool map[string]map[string]*WSClient
)
func init() {
pool = map[string]map[string]*WSClient{}
}
func Add(ID, channel string, conn *websocket.Conn) *WSClient {
mutex.Lock()
defer mutex.Unlock()
c := &WSClient{ID: ID, Channel: channel, Conn: conn}
if pool[c.Channel] == nil {
pool[c.Channel] = map[string]*WSClient{}
}
pool[c.Channel][c.ID] = c
return c
}
func Remove(channel, ID string) {
mutex.Lock()
defer mutex.Unlock()
delete(pool[channel], ID)
}
func Send(channel string, message *Message) (err error) {
for ID := range pool[channel] {
err = pool[channel][ID].Conn.WriteJSON(message)
}
return
}
|
badges: Include style for all badges
Not only global badges. | def badge(badge):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badge', badge=badge,
cached=True)
def badges(badges):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badges', badges=badges,
cached=True)
def badge_styles():
'''
Render a <style>-block with dyamic badge styles
'''
from adhocracy.lib.templating import render_def
from adhocracy.model import Badge
badges = Badge.all_q().all()
return render_def('/badge/tiles.html', 'badge_styles', badges=badges,
cached=True)
| def badge(badge):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badge', badge=badge,
cached=True)
def badges(badges):
from adhocracy.lib.templating import render_def
return render_def('/badge/tiles.html', 'badges', badges=badges,
cached=True)
def badge_styles():
'''
Render a <style>-block with dyamic badge styles
'''
from adhocracy.lib.templating import render_def
from adhocracy.model import Badge
badges = Badge.all()
return render_def('/badge/tiles.html', 'badge_styles', badges=badges,
cached=True)
|
Return correct status code to shell when tests fail.
When tests fail (due to e.g. missing feedparser), then the exit code of tests/runtests.py is 0, which is treated by shell as
success. Patch by Arfrever Frehtes Taifersar Arahesis. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
return unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
sys.exit(not main().wasSuccessful())
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
main()
|
Add missing fields key to validation exception | <?php
namespace Flugg\Responder\Exceptions\Http;
use Illuminate\Contracts\Validation\Validator;
/**
* An exception thrown whan validation fails. This exception replaces Laravel's
* [\Illuminate\Validation\ValidationException].
*
* @package flugger/laravel-responder
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
class ValidationFailedException extends HttpException
{
/**
* An HTTP status code.
*
* @var int
*/
protected $status = 422;
/**
* An error code.
*
* @var string|null
*/
protected $errorCode = 'validation_failed';
/**
* A validator for fetching validation messages.
*
* @var \Illuminate\Contracts\Validation\Validator
*/
protected $validator;
/**
* Construct the exception class.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
*/
public function __construct(Validator $validator)
{
$this->validator = $validator;
parent::__construct();
}
/**
* Retrieve the error data.
*
* @return array|null
*/
public function data()
{
return ['fields' => $this->validator->getMessageBag()->toArray()];
}
} | <?php
namespace Flugg\Responder\Exceptions\Http;
use Illuminate\Contracts\Validation\Validator;
/**
* An exception thrown whan validation fails. This exception replaces Laravel's
* [\Illuminate\Validation\ValidationException].
*
* @package flugger/laravel-responder
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
class ValidationFailedException extends HttpException
{
/**
* An HTTP status code.
*
* @var int
*/
protected $status = 422;
/**
* An error code.
*
* @var string|null
*/
protected $errorCode = 'validation_failed';
/**
* A validator for fetching validation messages.
*
* @var \Illuminate\Contracts\Validation\Validator
*/
protected $validator;
/**
* Construct the exception class.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
*/
public function __construct(Validator $validator)
{
$this->validator = $validator;
parent::__construct();
}
/**
* Retrieve the error data.
*
* @return array|null
*/
public function data()
{
return [$this->validator->getMessageBag()->toArray()];
}
} |
Make code compatible with older nodes | import http from 'http';
function generateTestCode(hasError, hasWait) {
var code;
if (hasError) {
if (hasWait) {
code = 'setTimeout(function () { throw new Error(); }, 2000);';
} else {
code = 'throw new Error();';
}
} else {
code = '';
}
return code;
}
function createTestServer(port = process.env.PORT || 4000) {
var server = http.createServer((req, res) => {
var hasError = req.url.indexOf('/error') !== -1;
var hasWait = req.url.indexOf('wait') !== -1;
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<html>
<body>
<script>
${generateTestCode(hasError, hasWait)}
document.write('test');
</script>
</body>
</html>
`);
}).listen(port);
return server;
}
export default createTestServer;
| import http from 'http';
function generateTestCode(hasError, hasWait) {
let code;
if (hasError) {
if (hasWait) {
code = 'setTimeout(function () { throw new Error(); }, 2000);';
} else {
code = 'throw new Error();';
}
} else {
code = '';
}
return code;
}
function createTestServer(port = process.env.PORT || 4000) {
const server = http.createServer((req, res) => {
const hasError = req.url.indexOf('/error') !== -1;
const hasWait = req.url.indexOf('wait') !== -1;
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<html>
<body>
<script>
${generateTestCode(hasError, hasWait)}
document.write('test');
</script>
</body>
</html>
`);
}).listen(port);
return server;
}
export default createTestServer;
|
Use a correct algorithm to determine the length of word to use | import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(re.findall(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
quotient, remainder = divmod(password_length, number_of_words)
word_length = quotient + (1 if remainder else 0)
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
| import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(w.group() for w in re.finditer(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
word_length = (password_length + 1) // number_of_words
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
Add a sanity check when reading translation json data
closes MAT-200
flag=none
test plan:
- the build succeeds
- muck with one of the packages/translations/lib/canvas-rce/*.json
files so it's no longer valid json
- run `yarn installTranslations` from canvas-rce directory
> expect to see an error message telling you what went wrong.
Change-Id: Ie46bd4c5eb0ec2b4c2b30c737efbd16d417dc9d4
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/265468
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
Reviewed-by: Guilherme Baron <2bd19d74e693a9c19d383f14059425669349e568@instructure.com>
QA-Review: Guilherme Baron <2bd19d74e693a9c19d383f14059425669349e568@instructure.com>
Product-Review: Ed Schiebel <0ca8a83847a5889cf05cb219c0ab09f6b646243b@instructure.com> | /*
* Copyright (C) 2021 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const fs = require('fs')
const path = require('path')
/**
* This returns the contents of the translations for the given package and locale
*/
async function readTRanslationFile(packageName, locale) {
const filePath = path.resolve(__dirname, `../lib/${packageName}/${locale}.json`)
const jsonData = await fs.promises.readFile(filePath, {encoding: 'utf8'})
// sanity check
try {
JSON.parse(jsonData)
} catch (ex) {
console.log(ex)
throw new Error(`Failed parsing content from ${filePath}`)
}
return jsonData
}
module.exports = readTRanslationFile
| /*
* Copyright (C) 2021 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const fs = require('fs')
const path = require('path')
/**
* This returns the contents of the translations for the given package and locale
*/
async function getTranslationList(packageName, locale) {
const jsonData = await fs.promises.readFile(
path.resolve(__dirname, `../lib/${packageName}/${locale}.json`),
{encoding: 'utf8'}
)
return jsonData
}
module.exports = getTranslationList
|
Add back button in forgot password page | @extends("layouts/guest-layout")
@section("content")
@if (Session::get("error") || Session::get("status"))
<div class="alert alert-danger" role="alert">
[[ Session::get("error") ]]
[[ Session::get("status") ]]
</div>
@endif
[[ Form::open(array('class' => 'form-signin', 'role' => 'form')) ]]
<!-- TODO: i18n -->
<h1 class="form-signin-heading">[[Lang::get('users.title_request')]]</h1>
<div class="form-group [[ $errors->first('username') ? 'has-error' : '' ]]">
[[ Form::text("username", Input::old("username"), array('class' => 'form-control', 'placeholder' => Lang::get('keywords.email_address'), 'required', 'autofocus')) ]]
</div>
<div class="checkbox">
</div>
<div class="form-group">
[[ Form::submit(Lang::get('keywords.reset_password'), array('class' => 'btn btn-lg btn-primary btn-block')) ]]
<a class="btn btn-lg btn-default btn-block" href="[[ URL::route("/")]]">[[Lang::get('keywords.back')]]</a>
</div>
[[ Form::close() ]]
@stop
| @extends("layouts/guest-layout")
@section("content")
@if (Session::get("error") || Session::get("status"))
<div class="alert alert-danger" role="alert">
[[ Session::get("error") ]]
[[ Session::get("status") ]]
</div>
@endif
[[ Form::open(array('class' => 'form-signin', 'role' => 'form')) ]]
<!-- TODO: i18n -->
<h1 class="form-signin-heading">[[Lang::get('users.title_request')]]</h1>
<div class="form-group [[ $errors->first('username') ? 'has-error' : '' ]]">
[[ Form::text("username", Input::old("username"), array('class' => 'form-control', 'placeholder' => Lang::get('keywords.email_address'), 'required', 'autofocus')) ]]
</div>
<div class="checkbox">
</div>
<div class="form-group">
[[ Form::submit(Lang::get('keywords.reset_password'), array('class' => 'btn btn-lg btn-primary btn-block')) ]]
</div>
[[ Form::close() ]]
@stop
|
Tweak date format to show month with letters | 'use strict';
const dateFormat = require('dateformat');
const settings = require('./../settings.js');
const propertyKey = settings.get('propertyKey');
const maxResults = settings.get('maxResults');
const wrap = function(item, index) {
return {
id: item.id,
selected: index === 0,
score: dateFormat(new Date(item.dateAdded), 'dd mmm yy'),
title: item.title,
wrappedUrl: item.url,
url: item.url,
favicon: item.favicon
};
};
module.exports = {
filter: function(bookmarks) {
return bookmarks.sort(function(bookmark1, bookmark2) {
return bookmark2.dateAdded - bookmark1.dateAdded;
}).slice(0, maxResults).map(wrap);
}
};
| 'use strict';
const dateFormat = require('dateformat');
const settings = require('./../settings.js');
const propertyKey = settings.get('propertyKey');
const maxResults = settings.get('maxResults');
const wrap = function(item, index) {
return {
id: item.id,
selected: index === 0,
score: dateFormat(new Date(item.dateAdded), 'shortDate'),
title: item.title,
wrappedUrl: item.url,
url: item.url,
favicon: item.favicon
};
};
module.exports = {
filter: function(bookmarks) {
return bookmarks.sort(function(bookmark1, bookmark2) {
return bookmark2.dateAdded - bookmark1.dateAdded;
}).slice(0, maxResults).map(wrap);
}
};
|
Put error stack in new line when logging | const fs = require('fs-extra')
const chalk = require('chalk')
exports.log = (message, err) => {
// Regular errors
if (message instanceof Error) {
console.error(err && err.stack)
return
}
// Ability to add custom message to error
if (err instanceof Error) {
console.error(chalk.bold(message) + "\n", err.stack)
return
}
// The usual loggings
console.log(message)
}
exports.exists = path => {
try {
fs.statSync(path)
return true
} catch (err) {
return false
}
}
exports.isSite = () => {
const pkgPath = process.cwd() + '/package.json'
if (!exports.exists(pkgPath) || !exports.exists(process.cwd() + '/.env')) {
return false
}
// Load the package.json
const package = require(pkgPath)
// Check if muffin has been added to dependencies
if (!package.dependencies || !package.dependencies.muffin) {
return false
}
return true
}
| const fs = require('fs-extra')
const chalk = require('chalk')
exports.log = (message, err) => {
// Regular errors
if (message instanceof Error) {
console.error(err && err.stack)
return
}
// Ability to add custom message to error
if (err instanceof Error) {
console.error(chalk.bold(message), err.stack)
return
}
// The usual loggings
console.log(message)
}
exports.exists = path => {
try {
fs.statSync(path)
return true
} catch (err) {
return false
}
}
exports.isSite = () => {
const pkgPath = process.cwd() + '/package.json'
if (!exports.exists(pkgPath) || !exports.exists(process.cwd() + '/.env')) {
return false
}
// Load the package.json
const package = require(pkgPath)
// Check if muffin has been added to dependencies
if (!package.dependencies || !package.dependencies.muffin) {
return false
}
return true
}
|
Remove extra new line at end of file | <?php
/**
* @title Index File
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @link http://ph7cms.com
* @package PH7 / Install
* @version 1.3
*/
define('PH7', 1);
ob_start();
header('Content-Type: text/html; charset=utf-8');
require 'constants.php';
include PH7_ROOT_INSTALL . 'inc/log.inc.php';
require 'requirements.php';
include_once PH7_ROOT_INSTALL . 'inc/fns/misc.php';
require_once PH7_ROOT_INSTALL . 'library/Smarty/Smarty.class.php';
require_once PH7_ROOT_INSTALL . 'inc/loader.inc.php';
require PH7_ROOT_INSTALL . 'inc/init.inc.php';
ob_end_flush();
| <?php
/**
* @title Index File
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @link http://ph7cms.com
* @package PH7 / Install
* @version 1.3
*/
define('PH7', 1);
ob_start();
header('Content-Type: text/html; charset=utf-8');
require 'constants.php';
include PH7_ROOT_INSTALL . 'inc/log.inc.php';
require 'requirements.php';
include_once PH7_ROOT_INSTALL . 'inc/fns/misc.php';
require_once PH7_ROOT_INSTALL . 'library/Smarty/Smarty.class.php';
require_once PH7_ROOT_INSTALL . 'inc/loader.inc.php';
require PH7_ROOT_INSTALL . 'inc/init.inc.php';
ob_end_flush();
|
Fix for pre-logged in Overview | // not sure how far to take this
// could make every mode extend methods like go, hide, show
// not a fan, not enough modes to bother yet
// naming is consistent enough to do this the dumb way
osmly.mode = (function() {
var mode = {now: false, last:false};
mode.set = function(theMode) {
if (mode.now == theMode) return false;
if (mode.now) osmly[mode.now].stop();
osmly[theMode].go();
change(theMode);
};
function change(changeTo) {
mode.last = mode.now;
mode.now = changeTo;
}
mode.import = function() { mode.set('import'); };
mode.qa = function() { mode.set('qa'); };
mode.overview = function() { mode.set('overview'); };
mode.toLast = function() {
if (mode.last) {
mode.set(mode.last);
} else {
osmly[mode.now].stop();
mode.now = false;
}
};
// convenience
return mode;
}());
| // not sure how far to take this
// could make every mode extend methods like go, hide, show
// not a fan, not enough modes to bother yet
// naming is consistent enough to do this the dumb way
osmly.mode = (function() {
var mode = {now: false, last:false};
mode.set = function(theMode) {
if (mode.now == theMode) return false;
if (mode.now) osmly[mode.now].stop();
osmly[theMode].go();
change(theMode);
};
function change(changeTo) {
mode.last = mode.now;
mode.now = changeTo;
}
mode.import = function() { mode.set('import'); };
mode.qa = function() { mode.set('qa'); };
mode.overview = function() { mode.set('overview'); };
mode.toLast = function() {
if (mode.last) {
mode.set(mode.last);
} else {
osmly[mode.now].stop();
}
};
// convenience
return mode;
}());
|
Fix path to partials + layouts | // Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
grunt.config('watch', {
options: {
spawn: false
},
// svg: {
// files: 'src/icons/*.svg',
// tasks: ['svgstore'],
// },
assemble: {
files: ['src/*.hbs', 'src/partials/*.hbs', 'src/layouts/*.hbs'],
tasks: ['assemble:dev'],
},
scss: {
files: 'src/scss/**/*.scss',
tasks: ['sass', 'autoprefixer:dev', 'bs-inject'],
},
js: {
files: ['src/scripts/main.js'],
tasks: ['concat'],
}
});
};
| // Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
grunt.config('watch', {
options: {
spawn: false
},
// svg: {
// files: 'src/icons/*.svg',
// tasks: ['svgstore'],
// },
assemble: {
files: ['src/*.hbs', 'src/inc/*.hbs', 'src/tpl/*.hbs'],
tasks: ['assemble:dev'],
},
scss: {
files: 'src/scss/**/*.scss',
tasks: ['sass', 'autoprefixer:dev', 'bs-inject'],
},
js: {
files: ['src/scripts/main.js'],
tasks: ['concat'],
}
});
};
|
Remove default options that shouldn't be part of this PR | /*
Copyright 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var DEFAULTS = {
};
class SdkConfig {
static get() {
return global.mxReactSdkConfig;
}
static put(cfg) {
var defaultKeys = Object.keys(DEFAULTS);
for (var i = 0; i < defaultKeys.length; ++i) {
if (cfg[defaultKeys[i]] === undefined) {
cfg[defaultKeys[i]] = DEFAULTS[defaultKeys[i]];
}
}
global.mxReactSdkConfig = cfg;
}
static unset() {
global.mxReactSdkConfig = undefined;
}
}
module.exports = SdkConfig;
| /*
Copyright 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var DEFAULTS = {
// URL to a page we show in an iframe to configure integrations
integrations_ui_url: "https://scalar.vector.im/",
// Base URL to the REST interface of the integrations server
integrations_rest_url: "https://scalar.vector.im/api",
};
class SdkConfig {
static get() {
return global.mxReactSdkConfig;
}
static put(cfg) {
var defaultKeys = Object.keys(DEFAULTS);
for (var i = 0; i < defaultKeys.length; ++i) {
if (cfg[defaultKeys[i]] === undefined) {
cfg[defaultKeys[i]] = DEFAULTS[defaultKeys[i]];
}
}
global.mxReactSdkConfig = cfg;
}
static unset() {
global.mxReactSdkConfig = undefined;
}
}
module.exports = SdkConfig;
|
Bring test_frame_of_test_null_file up to date with new signature of frame_of_test(). | from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), NotImplementedError,
NotImplementedError(), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
| from os import chdir, getcwd
from os.path import dirname, basename
from unittest import TestCase
from nose.tools import eq_
from noseprogressive.utils import human_path, frame_of_test
class UtilsTests(TestCase):
"""Tests for independent little bits and pieces"""
def test_human_path(self):
chdir(dirname(__file__))
eq_(human_path(__file__, getcwd()), basename(__file__))
def test_frame_of_test_null_file(self):
"""Make sure frame_of_test() doesn't crash when test_file is None."""
try:
frame_of_test((None, None, None), [('file', 333)])
except AttributeError:
self.fail('frame_of_test() raised AttributeError.')
|
Handle case where pip is not found | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Idiotproof setup
def check_pyyaml():
try:
import yaml
except ModuleNotFoundError:
print("Couldn't import PyYAML. Installing it for you...")
try:
import pip
pip.main(["install", "--user", "pyyaml"])
except ModuleNotFoundError:
print("Couldn't install it for you, because you don't have pip.")
def main():
from server.tsuserver import TsuServer3
server = TsuServer3()
server.start()
if __name__ == '__main__':
check_pyyaml()
main()
| #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from server.tsuserver import TsuServer3
# Idiotproof setup
def check_pyyaml():
try:
import yaml
except ModuleNotFoundError:
print("Couldn't import PyYAML. Installing it for you...")
import pip
pip.main(["install", "--user", "pyyaml"])
def main():
server = TsuServer3()
server.start()
if __name__ == '__main__':
check_pyyaml()
main()
|
Add new style of tags to mapper array | <?php
namespace Fastly\Cdn\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
class CacheTags extends AbstractHelper
{
/**
* Replaces long Magento Cache tags with a shorter version
*
* @param string
* @return string
*/
public function convertCacheTags($tags)
{
$fastlyTags = array(
// <= 2.1.*
'catalog_product_' => 'p',
'catalog_category_' => 'c',
'cms_page' => 'cpg',
'cms_block' => 'cb',
// > 2.2.*
'cat_p_' => 'p',
'cat_c_' => 'c',
'cms_p' => 'cpg',
'cms_b' => 'cb',
'brands_brand_' => 'b'
);
return str_replace(array_keys($fastlyTags), $fastlyTags, $tags);
}
} | <?php
namespace Fastly\Cdn\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
class CacheTags extends AbstractHelper
{
/**
* Replaces long Magento Cache tags with a shorter version
*
* @param string
* @return string
*/
public function convertCacheTags($tags)
{
$fastlyTags = array(
'catalog_product_' => 'p',
'catalog_category_' => 'c',
'cms_page' => 'cpg',
'cms_block' => 'cb',
'brands_brand_' => 'b'
);
return str_replace(array_keys($fastlyTags), $fastlyTags, $tags);
}
} |
Upgrade requests library to version 2.1.1
Upgrade the `requests` library to match the version provided by Ubuntu
Trusty, version 2.1.1.
This is to prevent a conflict on Ubuntu Trusty between system Python
libraries and Pip libraries.
Specifically, Pip relies on the `IncompleteRead` module that is exported
by `requests.compat`. Version 2.4.3 of the `requests` library removed
that exported module[1].
When `ghtools` is installed, Pip would upgrade `requests` to version
2.4.3 (the latest available), thereby causing Pip to break because the
`requests` module installed by Pip (in
`/usr/lib/python2.7/dist-packages/`) takes precendence over the system
version of that module.
This was causing the following Puppet error on our ci-slave-4 box in Vagrant
using Ubuntu Trusty:
==> ci-slave-4: Error: Could not prefetch package provider 'pip': [nil, nil, [(provider=pip)], nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
When I tried to run `pip` on the Vagrant box, I got the following error:
vagrant@ci-slave-4:~$ pip
Traceback (most recent call last):
File "/usr/bin/pip", line 9, in <module>
load_entry_point('pip==1.5.4', 'console_scripts', 'pip')()
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 351, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2363, in load_entry_point
return ep.load()
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2088, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 11, in <module>
from pip.vcs import git, mercurial, subversion, bazaar # noqa
File "/usr/lib/python2.7/dist-packages/pip/vcs/mercurial.py", line 9, in <module>
from pip.download import path_to_url
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 25, in <module>
from requests.compat import IncompleteRead
ImportError: cannot import name IncompleteRead
vagrant@ci-slave-4:~$
By installing requiring the exact same version of `requests` as the one
provided by the system under Ubuntu Trusty, Pip no longer needs to
install the `requests` module and `ghtools` will use the system module.
This is also tested under Precise and does not break Pip.
I verified the version of `requests` installed on Ubuntu Trusty prior to
installing `ghtools`:
vagrant@jumpbox-2:~/ghtools$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> print requests.__version__
2.2.1
>>>
When installing `ghtools`, Pip detects the existing system version and
will not install its own:
vagrant@jumpbox-2:~/ghtools$ sudo pip install .
Unpacking /home/vagrant/ghtools
Running setup.py (path:/tmp/user/0/pip-0GLR1h-build/setup.py) egg_info for package from file:///home/vagrant/ghtools
Requirement already satisfied (use --upgrade to upgrade): requests==2.2.1 in /usr/lib/python2.7/dist-packages (from ghtools==0.21.0)
[...]
For more context, please see this bug report (though the bug is not in
python-pip):
https://bugs.launchpad.net/ubuntu/+source/python-pip/+bug/1306991
[1]: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=766419 | import os
from setuptools import setup, find_packages
from ghtools import __version__
requirements = [
'requests==2.2.1',
'argh==0.23.0'
]
python_scripts = [
'browse',
'list-members',
'login',
'migrate-project',
'migrate-wiki',
'migrate-teams',
'org',
'repo',
'status',
]
HERE = os.path.dirname(__file__)
try:
long_description = open(os.path.join(HERE, 'README.rst')).read()
except:
long_description = None
setup(
name='ghtools',
version=__version__,
packages=find_packages(exclude=['test*']),
# metadata for upload to PyPI
author='Nick Stenning',
author_email='nick@whiteink.com',
maintainer='Government Digital Service',
url='https://github.com/alphagov/ghtools',
description='ghtools: tools for interacting with the GitHub API',
long_description=long_description,
license='MIT',
keywords='sysadmin git github api',
install_requires=requirements,
entry_points={
'console_scripts': [
'gh-{0}=ghtools.command.{1}:main'.format(s, s.replace('-', '_')) for s in python_scripts
]
}
)
| import os
from setuptools import setup, find_packages
from ghtools import __version__
requirements = [
'requests==1.1.0',
'argh==0.23.0'
]
python_scripts = [
'browse',
'list-members',
'login',
'migrate-project',
'migrate-wiki',
'migrate-teams',
'org',
'repo',
'status',
]
HERE = os.path.dirname(__file__)
try:
long_description = open(os.path.join(HERE, 'README.rst')).read()
except:
long_description = None
setup(
name='ghtools',
version=__version__,
packages=find_packages(exclude=['test*']),
# metadata for upload to PyPI
author='Nick Stenning',
author_email='nick@whiteink.com',
maintainer='Government Digital Service',
url='https://github.com/alphagov/ghtools',
description='ghtools: tools for interacting with the GitHub API',
long_description=long_description,
license='MIT',
keywords='sysadmin git github api',
install_requires=requirements,
entry_points={
'console_scripts': [
'gh-{0}=ghtools.command.{1}:main'.format(s, s.replace('-', '_')) for s in python_scripts
]
}
)
|
Handle int and string quantity validation | import React from 'react';
import PropTypes from 'prop-types';
class Quantity extends React.Component {
render() {
return (
<div className="container__row figure -left -center">
<div className="figure__media">
<div className="quantity">{this.props.quantity}</div>
</div>
<div className="figure__body">
{this.props.noun && this.props.verb ?
<h4 className="reportback-noun-verb">{this.props.noun} {this.props.verb}</h4>
: null}
</div>
</div>
);
}
}
Quantity.propTypes = {
noun: PropTypes.string,
quantity: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
verb: PropTypes.string,
};
Quantity.defaultProps = {
noun: 'things',
quantity: 0,
verb: 'done',
};
export default Quantity;
| import React from 'react';
import PropTypes from 'prop-types';
class Quantity extends React.Component {
render() {
return (
<div className="container__row figure -left -center">
<div className="figure__media">
<div className="quantity">{this.props.quantity}</div>
</div>
<div className="figure__body">
{this.props.noun && this.props.verb ?
<h4 className="reportback-noun-verb">{this.props.noun} {this.props.verb}</h4>
: null}
</div>
</div>
);
}
}
Quantity.propTypes = {
noun: PropTypes.string,
quantity: PropTypes.string,
verb: PropTypes.string,
};
Quantity.defaultProps = {
noun: 'things',
quantity: 0,
verb: 'done',
};
export default Quantity;
|
Make ordering consistent with keysmith | #!/usr/bin/env python
# coding: utf-8
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from __future__ import absolute_import
from setuptools import setup, find_packages
import backlog
with open('README.rst') as readme_file:
README = readme_file.read()
setup(
name='backlog',
version=backlog.__version__,
description=backlog.__doc__,
long_description=README,
author='David Tucker',
author_email='david.michael.tucker@gmail.com',
license='LGPLv2+',
url='https://github.com/dmtucker/backlog',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
include_package_data=True,
entry_points={'console_scripts': ['backlog=backlog.__main__:main']},
keywords='notes backlog todo lists',
classifiers=[
'License :: OSI Approved :: '
'GNU Lesser General Public License v2 or later (LGPLv2+)',
'Intended Audience :: End Users/Desktop',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Development Status :: 4 - Beta',
],
)
| #!/usr/bin/env python
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
import backlog
with open('README.rst') as readme_file:
README = readme_file.read()
setup(
name='backlog',
version=backlog.__version__,
description=backlog.__doc__,
long_description=README,
license='LGPLv2+',
url='https://github.com/dmtucker/backlog',
author='David Tucker',
author_email='david.michael.tucker@gmail.com',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: '
'GNU Lesser General Public License v2 or later (LGPLv2+)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='notes backlog todo lists',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
entry_points={'console_scripts': ['backlog=backlog.__main__:main']},
)
|
Fix JavaScript timer to never leak resources
Stop() might have leaked the firing goroutine. | // +build js
package ninchat
import (
"github.com/gopherjs/gopherjs/js"
)
type duration int64
const (
second duration = 1000
millisecond = 1
)
type timeTime int64
func timeNow() timeTime {
return timeTime(js.Global.Get("Date").New().Call("getTime").Int64())
}
func timeAdd(t timeTime, d duration) timeTime {
return t + timeTime(d)
}
func timeSub(t1, t2 timeTime) duration {
return duration(t1 - t2)
}
type timer struct {
C chan struct{}
id *js.Object
}
func newTimer(timeout duration) (t *timer) {
t = &timer{
C: make(chan struct{}, 1),
}
if timeout >= 0 {
t.Reset(timeout)
}
return
}
func (timer *timer) Active() bool {
return timer.id != nil
}
func (timer *timer) Reset(timeout duration) {
timer.Stop()
timer.id = js.Global.Call("setTimeout", func() {
timer.id = nil
timer.C <- struct{}{}
}, timeout)
}
func (timer *timer) Stop() {
if timer.id != nil {
js.Global.Call("clearTimeout", timer.id)
timer.id = nil
}
}
| // +build js
package ninchat
import (
"github.com/gopherjs/gopherjs/js"
)
type duration int64
const (
second duration = 1000
millisecond = 1
)
type timeTime int64
func timeNow() timeTime {
return timeTime(js.Global.Get("Date").New().Call("getTime").Int64())
}
func timeAdd(t timeTime, d duration) timeTime {
return t + timeTime(d)
}
func timeSub(t1, t2 timeTime) duration {
return duration(t1 - t2)
}
type timer struct {
C chan struct{}
id *js.Object
}
func newTimer(timeout duration) (t *timer) {
t = &timer{
C: make(chan struct{}),
}
if timeout >= 0 {
t.Reset(timeout)
}
return
}
func (timer *timer) Active() bool {
return timer.id != nil
}
func (timer *timer) Reset(timeout duration) {
timer.Stop()
timer.id = js.Global.Call("setTimeout", func() {
timer.id = nil
go func() {
timer.C <- struct{}{}
}()
}, timeout)
}
func (timer *timer) Stop() {
if timer.id != nil {
js.Global.Call("clearTimeout", timer.id)
timer.id = nil
}
}
|
Return when the article is not found and avoid render the template | package main
import (
"html/template"
"log"
"net/http"
)
type Blog struct {
Articles map[string]*Article
}
func (b *Blog) getArticle(slug string) *Article {
if article := b.Articles[slug]; article != nil {
return article
}
return nil
}
func (b *Blog) articleHandler(w http.ResponseWriter, r *http.Request) {
slug := r.URL.Path[len("/articles/"):]
article := b.getArticle(slug)
if article == nil {
http.NotFound(w, r)
return
}
template, _ := template.ParseFiles("layouts/article.html")
template.Execute(w, article)
}
func main() {
blog := Blog{Articles: LoadArticles()}
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
http.HandleFunc("/articles/", blog.articleHandler)
log.Println("Listening...")
http.ListenAndServe(":3001", nil)
}
| package main
import (
"html/template"
"log"
"net/http"
)
type Blog struct {
Articles map[string]*Article
}
func (b *Blog) getArticle(slug string) *Article {
if article := b.Articles[slug]; article != nil {
return article
}
return nil
}
func (b *Blog) articleHandler(w http.ResponseWriter, r *http.Request) {
slug := r.URL.Path[len("/articles/"):]
article := b.getArticle(slug)
if article == nil {
http.NotFound(w, r)
}
template, _ := template.ParseFiles("layouts/article.html")
template.Execute(w, article)
}
func main() {
blog := Blog{Articles: LoadArticles()}
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
http.HandleFunc("/articles/", blog.articleHandler)
log.Println("Listening...")
http.ListenAndServe(":3001", nil)
}
|
meta: Use array instead of slice in VerifyPadding. | package meta
import (
"errors"
"io"
)
// VerifyPadding verifies that the padding metadata block only contains 0 bits.
// The provided io.Reader should limit the amount of data that can be read to
// header.Length bytes.
func VerifyPadding(r io.Reader) (err error) {
// Verify up to 4 kb of padding each iteration.
var buf [4096]byte
for {
n, err := r.Read(buf[:])
if err != nil {
if err == io.EOF {
break
}
return err
}
if !isAllZero(buf[:n]) {
return errors.New("meta.VerifyPadding: invalid padding; must contain only zeroes")
}
}
return nil
}
// isAllZero returns true if the value of each byte in the provided slice is 0,
// and false otherwise.
func isAllZero(buf []byte) bool {
for _, b := range buf {
if b != 0 {
return false
}
}
return true
}
| package meta
import (
"errors"
"io"
)
// VerifyPadding verifies that the padding metadata block only contains 0 bits.
// The provided io.Reader should limit the amount of data that can be read to
// header.Length bytes.
func VerifyPadding(r io.Reader) (err error) {
// Verify up to 4 kb of padding each iteration.
buf := make([]byte, 4096)
for {
n, err := r.Read(buf)
if err != nil {
if err == io.EOF {
break
}
return err
}
if !isAllZero(buf[:n]) {
return errors.New("meta.VerifyPadding: invalid padding; must contain only zeroes")
}
}
return nil
}
/// ### [ note ] ###
/// - Might trigger unnecessary errors.
/// ### [/ note ] ###
// isAllZero returns true if the value of each byte in the provided slice is 0,
// and false otherwise.
func isAllZero(buf []byte) bool {
for _, b := range buf {
if b != 0 {
return false
}
}
return true
}
|
Refactor Foreach Into Array Reduce
This was a foreach doing exactly what array_reduce did before. So just
tidying this up. | <?php
namespace Consolidare;
use Consolidare\Mergeable\Mergeable;
use Consolidare\Mergeable\MergeableFactory;
use Consolidare\MergeStrategy\MergeStrategy;
use Consolidare\Record\RecordFactory;
class Merge
{
private $mergeable = [];
public function data($input)
{
return $this->mergeable(MergeableFactory::create($input));
}
public function mergeable(Mergeable $data)
{
$this->mergeable[] = $data;
return $this;
}
public function merge(MergeStrategy $strategy = NULL)
{
if (!$strategy) {
$strategy = new MergeStrategy();
}
return array_reduce($this->mergeable, function ($record, $data) use ($strategy) {
return RecordFactory::create(
$strategy,
$record,
$data
);
});
}
}
| <?php
namespace Consolidare;
use Consolidare\Mergeable\Mergeable;
use Consolidare\Mergeable\MergeableFactory;
use Consolidare\MergeStrategy\MergeStrategy;
use Consolidare\Record\RecordFactory;
class Merge
{
private $mergeable = [];
public function data($input)
{
return $this->mergeable(MergeableFactory::create($input));
}
public function mergeable(Mergeable $data)
{
$this->mergeable[] = $data;
return $this;
}
public function merge(MergeStrategy $strategy = NULL)
{
if (!$strategy) {
$strategy = new MergeStrategy();
}
$record = NULL;
foreach ($this->mergeable as $data) {
$record = RecordFactory::create(
$strategy,
$record,
$data
);
}
return $record;
}
}
|
Bump to 0.0.2a for attr. graph feature
Add new subpackages to the setup package list. | from setuptools import setup
import os
setup(
name = "merky",
version = "0.0.2a",
author = "Ethan Rowe",
author_email = "ethan@the-rowes.com",
description = ("JSON-oriented merkle tree utilities"),
license = "MIT",
url = "https://github.com/ethanrowe/python-merky",
packages = ["merky",
"merky.cases",
"merky.test",
"merky.test.usecases",
],
long_description = """
Merky - compute merkle trees for JSON-friendly data.
""",
test_suite = "nose.collector",
install_requires = [
'six >= 1.5',
],
setup_requires = [
'nose',
'mock >= 1.0.1',
],
tests_require = [
'nose',
'mock >= 1.0.1',
],
)
| from setuptools import setup
import os
setup(
name = "merky",
version = "0.0.1a",
author = "Ethan Rowe",
author_email = "ethan@the-rowes.com",
description = ("JSON-oriented merkle tree utilities"),
license = "MIT",
url = "https://github.com/ethanrowe/python-merky",
packages = ["merky",
"merky.test",
],
long_description = """
Merky - compute merkle trees for JSON-friendly data.
""",
test_suite = "nose.collector",
install_requires = [
'six >= 1.5',
],
setup_requires = [
'nose',
'mock >= 1.0.1',
],
tests_require = [
'nose',
'mock >= 1.0.1',
],
)
|
[snomed] Fix permission level of SNOMED component create requests | /*
* Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.datastore.request;
import com.b2international.snowowl.core.authorization.BranchAccessControl;
import com.b2international.snowowl.identity.domain.Permission;
/**
* @since 6.5
*/
public interface SnomedComponentCreateRequest extends SnomedComponentRequest<String>, BranchAccessControl {
String getModuleId();
Boolean isActive();
@Override
default String getOperation() {
return Permission.EDIT;
}
}
| /*
* Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.datastore.request;
import com.b2international.snowowl.core.authorization.BranchAccessControl;
import com.b2international.snowowl.identity.domain.Permission;
/**
* @since 6.5
*/
public interface SnomedComponentCreateRequest extends SnomedComponentRequest<String>, BranchAccessControl {
String getModuleId();
Boolean isActive();
@Override
default String getOperation() {
return Permission.BROWSE;
}
}
|
Add package path to correctly resolve the config | <?php namespace StudioIgnis\Evt\Laravel;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
public function boot()
{
$this->package('studioignis/evt', 'evt', realpath(__DIR__.'/../../'));
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('StudioIgnis\Evt\Support\Container', function ($app)
{
return new Container($app);
});
$this->app->bindShared('StudioIgnis\Evt\Dispatcher', function ($app)
{
return $app->make($app['config']['evt::dispatcher'], [
$app['StudioIgnis\Evt\Support\Container']
]);
});
}
}
| <?php namespace StudioIgnis\Evt\Laravel;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
public function boot()
{
$this->package('studioignis/evt', 'evt');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('StudioIgnis\Evt\Support\Container', function ($app)
{
return new Container($app);
});
$this->app->bindShared('StudioIgnis\Evt\Dispatcher', function ($app)
{
return $app->make($app['config']['evt::dispatcher'], [
$app['StudioIgnis\Evt\Support\Container']
]);
});
}
}
|
Add fib.elf to integration tests. | from epiphany.sim import Epiphany
import os.path
import pytest
elf_dir = os.path.join('epiphany', 'test', 'c')
@pytest.mark.parametrize("elf_file,expected", [('nothing.elf', 176),
('fib.elf', 441),
])
def test_compiled_c(elf_file, expected, capsys):
"""Test an ELF file that has been compiled from a C function.
This test checks that the correct number of instructions have been executed.
"""
elf_filename = os.path.join(elf_dir, elf_file)
epiphany = Epiphany()
with open(elf_filename, 'rb') as elf:
epiphany.init_state(elf, elf_filename, '', [], False, is_test=True)
epiphany.max_insts = 10000
epiphany.run()
out, err = capsys.readouterr()
expected_text = 'Instructions Executed = ' + str(expected)
assert expected_text in out
assert err == ''
assert not epiphany.state.running
| from epiphany.sim import Epiphany
import os.path
import pytest
elf_dir = os.path.join('epiphany', 'test', 'c')
@pytest.mark.parametrize("elf_file,expected", [('nothing.elf', 176),
])
def test_compiled_c(elf_file, expected, capsys):
"""Test an ELF file that has been compiled from a C function.
This test checks that the correct number of instructions have been executed.
"""
elf_filename = os.path.join(elf_dir, elf_file)
epiphany = Epiphany()
with open(elf_filename, 'rb') as elf:
epiphany.init_state(elf, elf_filename, '', [], False, is_test=True)
epiphany.max_insts = 10000
epiphany.run()
out, err = capsys.readouterr()
expected_text = 'Instructions Executed = ' + str(expected)
assert expected_text in out
assert err == ''
assert not epiphany.state.running
|
Update ping command test case | <?php
namespace Loct\Pinger\Command;
use \Symfony\Component\Console\Application;
use \Symfony\Component\Console\Tester\CommandTester;
use \PHPUnit_Framework_TestCase;
class PingCommandTest extends PHPUnit_Framework_TestCase
{
public function testExecuteIsSucces()
{
$hosts = [
'127.0.0.1',
'google.com',
'192.168.0.123'
];
$notifier = $this->getMockBuilder('Loct\Pinger\Notifier\NotifierInterface')
->getMock();
$notifier->expects($this->once())
->method('notify');
$application = new Application();
$application->add(new PingCommand($hosts, $notifier));
$command = $application->find('ping');
$commandTester = new CommandTester($command);
$commandTester->execute(['command' => $command->getName()]);
$display = $commandTester->getDisplay();
$this->assertRegExp('/Finished ping-ing all hosts/', $display);
foreach ($hosts as $host) {
$this->assertRegExp("/{$hosts[0]}/", $display);
}
}
}
| <?php
namespace Loct\Pinger\Command;
use \Symfony\Component\Console\Application;
use \Symfony\Component\Console\Tester\CommandTester;
use \PHPUnit_Framework_TestCase;
class PingCommandTest extends PHPUnit_Framework_TestCase
{
public function testExecuteIsSucces()
{
$hosts = [
'127.0.0.1',
'google.com'
];
$notifier = $this->getMockBuilder('Loct\Pinger\Notifier\NotifierInterface')
->getMock();
$notifier->expects($this->once())
->method('notify');
$application = new Application();
$application->add(new PingCommand($hosts, $notifier));
$command = $application->find('ping');
$commandTester = new CommandTester($command);
$commandTester->execute(['command' => $command->getName()]);
$display = $commandTester->getDisplay();
$this->assertRegExp('/Finished ping-ing all hosts/', $display);
foreach ($hosts as $host) {
$this->assertRegExp("/{$hosts[0]}: /", $display);
}
}
}
|
Add hint how to analyse webpack bundle. | /* @flow weak */
'use strict';
var webpack = require('webpack');
var gutil = require('gulp-util');
module.exports = function(webpackConfig) {
return function(callback) {
webpack(webpackConfig, function(fatalError, stats) {
var jsonStats = stats.toJson();
// We can save jsonStats to be analyzed with
// http://webpack.github.io/analyse or
// https://github.com/robertknight/webpack-bundle-size-analyzer.
// var fs = require('fs');
// fs.writeFileSync('./bundle-stats.json', JSON.stringify(jsonStats));
var buildError = fatalError || jsonStats.errors[0] || jsonStats.warnings[0];
if (buildError)
throw new gutil.PluginError('webpack', buildError);
gutil.log('[webpack]', stats.toString({
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}));
callback();
});
};
};
| /* @flow weak */
'use strict';
var webpack = require('webpack');
var gutil = require('gulp-util');
module.exports = function(webpackConfig) {
return function(callback) {
webpack(webpackConfig, function(fatalError, stats) {
var jsonStats = stats.toJson();
var buildError = fatalError || jsonStats.errors[0] || jsonStats.warnings[0];
if (buildError)
throw new gutil.PluginError('webpack', buildError);
gutil.log('[webpack]', stats.toString({
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}));
callback();
});
};
};
|
Fix typo in addLocation action | import { gotError } from './general';
import { createNewLocation, listLocations } from '../api/locations';
export function addLocation( params ) {
return function( dispatch, getState ) {
if ( ! params.name || ! params.address ) return dispatch( gotError( 'Locations must have a name and an address' ) );
createNewLocation( getState().auth.token, params )
.then( () => dispatch( fetchLibrary() ) )
.catch( ( err ) => dispatch( gotError( err ) ) );
const location = Object.assign( { _id: 'new-location_' + Date.now(), isLoading: true }, params );
dispatch( gotNewLocation( location ) );
}
}
export function gotNewLocation( location ) {
return { type: 'LIBRARY_GOT_NEW_LOCATION', location }
}
export function hideAddLocation() {
return { type: 'LIBRARY_HIDE_ADD_LOCATION' };
}
export function showAddLocation() {
return { type: 'LIBRARY_SHOW_ADD_LOCATION' };
}
export function fetchLibrary() {
return function( dispatch, getState ) {
listLocations( getState().auth.token )
.then( ( locations ) => {
dispatch( gotLibrary( locations ) );
} )
.catch( ( err ) => {
dispatch( gotError( err ) );
} );
}
}
export function gotLibrary( library ) {
return { type: 'LIBRARY_GOT_LOCATIONS', library };
}
| import { gotError } from './general';
import { createNewLocation, listLocations } from '../api/locations';
export function addLocation( params ) {
return function( dispatch, getState ) {
if ( ! params.user || ! params.address ) return dispatch( gotError( 'Locations must have a name and an address' ) );
createNewLocation( getState().auth.token, params )
.then( () => dispatch( fetchLibrary() ) )
.catch( ( err ) => dispatch( gotError( err ) ) );
const location = Object.assign( { _id: 'new-location_' + Date.now(), isLoading: true }, params );
dispatch( gotNewLocation( location ) );
}
}
export function gotNewLocation( location ) {
return { type: 'LIBRARY_GOT_NEW_LOCATION', location }
}
export function hideAddLocation() {
return { type: 'LIBRARY_HIDE_ADD_LOCATION' };
}
export function showAddLocation() {
return { type: 'LIBRARY_SHOW_ADD_LOCATION' };
}
export function fetchLibrary() {
return function( dispatch, getState ) {
listLocations( getState().auth.token )
.then( ( locations ) => {
dispatch( gotLibrary( locations ) );
} )
.catch( ( err ) => {
dispatch( gotError( err ) );
} );
}
}
export function gotLibrary( library ) {
return { type: 'LIBRARY_GOT_LOCATIONS', library };
}
|
Add show_statistics to public API
PiperOrigin-RevId: 322842576 | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"show_statistics",
"Visualizer",
]
| # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"Visualizer",
]
|
Load version from version file | # -*- coding: utf-8 -*-
# Standard Libs
import datetime
import os
import sys
# Add flask_hal to the Path
root = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
)
)
sys.path.append(os.path.join(root, 'flask_hal'))
# First Party Libs
import flask_hal # noqa
# Project details
project = u'Flask-HAL'
copyright = u'{0}, SOON_ London Ltd'.format(datetime.datetime.utcnow().year)
version = open('./../VERSION.txt').read().strip()
release = version
# Sphinx Config
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.todo',
'sphinx.ext.napoleon']
exclude_patterns = []
# Theme
sys.path.append(os.path.abspath('_themes'))
html_theme_path = ['_themes', ]
html_static_path = ['_static', ]
html_theme = 'kr'
html_sidebars = {
'index': ['sidebar_intro.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html'],
'**': ['sidebar_intro.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html']
}
| # -*- coding: utf-8 -*-
# Standard Libs
import datetime
import os
import sys
# Add flask_hal to the Path
root = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
)
)
sys.path.append(os.path.join(root, 'flask_hal'))
# First Party Libs
import flask_hal # noqa
# Project details
project = u'Flask-HAL'
copyright = u'{0}, SOON_ London Ltd'.format(datetime.datetime.utcnow().year)
version = '2015.10.8'
release = version
# Sphinx Config
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.todo',
'sphinx.ext.napoleon']
exclude_patterns = []
# Theme
sys.path.append(os.path.abspath('_themes'))
html_theme_path = ['_themes', ]
html_static_path = ['_static', ]
html_theme = 'kr'
html_sidebars = {
'index': ['sidebar_intro.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html'],
'**': ['sidebar_intro.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html']
}
|
Change print statement about config | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
|
Add accidentally removed charset header | package fi.tekislauta.webserver;
import com.google.gson.Gson;
import fi.tekislauta.db.Database;
import fi.tekislauta.models.Board;
import fi.tekislauta.models.Post;
import fi.tekislauta.models.Resolvable;
import static spark.Spark.*;
import static spark.Spark.get;
public class Webserver {
private final int port;
private final Gson gson;
private final Database db;
public Webserver(int port) {
this.port = port;
this.gson = new Gson();
this.db = new Database();
}
public void listen() {
port(this.port);
// spark starts listening when first method listener is added, I think ~cx
get("/api/boards/:abbreviation", (req, res) -> {
res.header("Content-Type","application/json; charset=utf-8");
Board b = new Board();
db.resolve(b, req.params("abbreviation"));
return gson.toJson(b);
});
}
}
| package fi.tekislauta.webserver;
import com.google.gson.Gson;
import fi.tekislauta.db.Database;
import fi.tekislauta.models.Board;
import fi.tekislauta.models.Post;
import fi.tekislauta.models.Resolvable;
import static spark.Spark.*;
import static spark.Spark.get;
public class Webserver {
private final int port;
private final Gson gson;
private final Database db;
public Webserver(int port) {
this.port = port;
this.gson = new Gson();
this.db = new Database();
}
public void listen() {
port(this.port);
// spark starts listening when first method listener is added, I think ~cx
get("/api/boards/:abbreviation", (req, res) -> {
res.header("Content-Type","application/json");
Board b = new Board();
db.resolve(b, req.params("abbreviation"));
return gson.toJson(b);
});
}
}
|
Update Service Provider for L5.4 | <?php namespace Sseffa\VideoApi;
use Illuminate\Support\ServiceProvider;
/**
* Class VideoApiServiceProvider
* @package Sseffa\VideoApi
* @author Sefa Karagöz
*/
class VideoApiServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('video-api', function ()
{
return new VideoApi();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array("video-api");
}
}
| <?php namespace Sseffa\VideoApi;
use Illuminate\Support\ServiceProvider;
/**
* Class VideoApiServiceProvider
* @package Sseffa\VideoApi
* @author Sefa Karagöz
*/
class VideoApiServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['video-api'] = $this->app->share(function ()
{
return new VideoApi();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array("video-api");
}
}
|
Fix bug that was causing this to not even work at all | # project
from checks import AgentCheck
VM_COUNTS = {
'pgpgin': 'pages.in',
'pgpgout': 'pages.out',
'pswpin': 'pages.swapped_in',
'pswpout': 'pages.swapped_out',
'pgfault': 'pages.faults',
'pgmajfault': 'pages.major_faults'
}
class MoreLinuxVMCheck(AgentCheck):
def check(self, instance):
tags = instance.get('tags', [])
enabled_metrics = instance.get('enabled_metrics', list(VM_COUNTS.keys()))
with open('/proc/vmstat', 'r') as vm_info:
content = [line.strip().split() for line in vm_info.readlines()]
for line in content:
if line[0] in enabled_metrics:
self.monotonic_count("system.linux.vm.{0}".format(VM_COUNTS[line[0]]), int(line[1]), tags=tags)
| # project
from checks import AgentCheck
VM_COUNTS = {
'pgpgin': 'pages.in',
'pgpgout': 'pages.out',
'pswpin': 'pages.swapped_in',
'pswpout': 'pages.swapped_out',
'pgfault': 'pages.faults',
'pgmajfault': 'pages.major_faults'
}
class MoreLinuxVMCheck(AgentCheck):
def check(self, instance):
tags = instance.get('tags', [])
enabled_metrics = instance.get('enabled_metrics', list(VM_COUNTS.keys()))
with open('/proc/vmstat', 'r') as vm_info:
content = [line.strip().split() for line in vm_info.readlines()]
for line in content:
if line[0] in VM_COUNTS:
self.monotonic_count("system.linux.vm.{0}".format(VM_COUNTS[line[0]]), int(line[1]), tags=tags)
|
Check for new audio data as fast as possible from javascript (may eat CPU) | setTimeout( function() {
var util = require( "util" );
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
});
var audioEngineImpl = require( "../Debug/NodeCoreAudio" );
console.log( audioEngineImpl );
var audioEngine = audioEngineImpl.createAudioEngine( function(uSampleFrames, inputBuffer, outputBuffer) {
console.log( "aw shit, we got some samples" );
});
// Make sure the audio engine is still active
if( audioEngine.isActive() ) console.log( "active" );
else console.log( "not active" );
// Declare our processing function
function processAudio( numSamples, incomingSamples ) {
for( var iSample = 0; iSample < numSamples; ++iSample ) {
incomingSamples[iSample] = iSample/numSamples;
}
return incomingSamples;
}
// Start polling the audio engine for data as fast as we can
setInterval( function() {
audioEngine.processIfNewData( processAudio );
}, 0 );
}, 0); | setTimeout( function() {
var util = require( "util" );
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
});
var audioEngineImpl = require( "../Debug/NodeCoreAudio" );
console.log( audioEngineImpl );
var audioEngine = audioEngineImpl.createAudioEngine( function(uSampleFrames, inputBuffer, outputBuffer) {
console.log( "aw shit, we got some samples" );
});
// Make sure the audio engine is still active
if( audioEngine.isActive() ) console.log( "active" );
else console.log( "not active" );
// Declare our processing function
function processAudio( numSamples, incomingSamples ) {
for( var iSample = 0; iSample < numSamples; ++iSample ) {
incomingSamples[iSample] = iSample/numSamples;
}
return incomingSamples;
}
// Start polling the audio engine for data every 2 milliseconds
setInterval( function() {
audioEngine.processIfNewData( processAudio );
}, 2 );
}, 15000); |
Fix diagnostics output for clang-cl
Summary:
clang-cl is sensible and emits diagnostics to stderr, unlike cl.exe.
Override WindowsCompiler's override for this.
Reviewed By: ilya-klyuchnikov
fbshipit-source-id: a251903b5d | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx.toolchain;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.util.ProcessExecutor;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import java.util.Optional;
/** Subclass of WindowsCompiler with overrides specific for clang-cl. */
public class ClangClCompiler extends WindowsCompiler {
public ClangClCompiler(Tool tool) {
super(tool);
}
@Override
public ImmutableList<String> getFlagsForReproducibleBuild(
String altCompilationDir, Path currentCellPath) {
return ImmutableList.of(
"/Brepro", "-Xclang", "-fdebug-compilation-dir", "-Xclang", altCompilationDir);
}
@Override
public Optional<String> getStderr(ProcessExecutor.Result result) {
// clang-cl is sensible
return result.getStderr();
}
}
| /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx.toolchain;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
/** Subclass of WindowsCompiler with overrides specific for clang-cl. */
public class ClangClCompiler extends WindowsCompiler {
public ClangClCompiler(Tool tool) {
super(tool);
}
@Override
public ImmutableList<String> getFlagsForReproducibleBuild(
String altCompilationDir, Path currentCellPath) {
return ImmutableList.of(
"/Brepro", "-Xclang", "-fdebug-compilation-dir", "-Xclang", altCompilationDir);
}
}
|
Fix getMigrations method signature for migrations command | <?php
/*
* This file is part of the Active Collab Bootstrap project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\Bootstrap\Command\DevCommand\Migrations;
use ActiveCollab\Bootstrap\Command\DevCommand\DevCommand;
use ActiveCollab\DatabaseMigrations\MigrationsInterface;
use RuntimeException;
/**
* @package ActiveCollab\Bootstrap\Command\DevCommand\Migrations
*/
abstract class Command extends DevCommand
{
/**
* {@inheritdoc}
*/
public function getCommandNamePrefix()
{
return parent::getCommandNamePrefix() . 'migrations:';
}
/**
* Return migrations instance.
*
* @return MigrationsInterface
*/
public function &getMigrations()
{
$migrations = $this->getContainer()->get('migrations');
if ($migrations instanceof MigrationsInterface) {
return $migrations;
} else {
throw new RuntimeException('Failed to get migrations utility from DI container');
}
}
}
| <?php
/*
* This file is part of the Active Collab Bootstrap project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\Bootstrap\Command\DevCommand\Migrations;
use ActiveCollab\Bootstrap\Command\DevCommand\DevCommand;
use ActiveCollab\DatabaseMigrations\MigrationsInterface;
/**
* @package ActiveCollab\Bootstrap\Command\DevCommand\Migrations
*/
abstract class Command extends DevCommand
{
/**
* {@inheritdoc}
*/
public function getCommandNamePrefix()
{
return parent::getCommandNamePrefix() . 'migrations:';
}
/**
* Return migrations instance.
*
* @return MigrationsInterface
*/
public function getMigrations()
{
return $this->getContainer()->get('migrations');
}
}
|
Add API endpoints to serve data in JSON format. | #!/usr/bin/env python
import json, os, requests
from awsauth import S3Auth
from datetime import datetime
from pytz import timezone
from flask import Flask, render_template, url_for, jsonify
from models import app, db, FoodMenu, FoodServices
MIXPANEL_TOKEN = os.environ.get('MIXPANEL_TOKEN')
@app.route('/')
def renderMenu():
nowWaterloo = datetime.now(timezone('America/Toronto'))
foodMenu = FoodMenu.query.order_by(FoodMenu.id.desc()).first().result
menu = json.loads(foodMenu)['response']['data']
serviceInfo = FoodServices.query.order_by(FoodServices.id.desc()).first().result
locations = json.loads(serviceInfo)['response']['data']
return render_template('index.html', menu=menu, locations=locations, nowWaterloo=nowWaterloo, mixpanelToken=MIXPANEL_TOKEN)
@app.route('/foodmenu')
def foodmenu():
foodMenu = FoodMenu.query.order_by(FoodMenu.id.desc()).first().result
menu = json.loads(foodMenu)['response']['data']
return jsonify(menu)
@app.route('/foodservices')
def foodservices():
serviceInfo = FoodServices.query.order_by(FoodServices.id.desc()).first().result
locations = json.loads(serviceInfo)['response']['data']
return jsonify(locations)
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| #!/usr/bin/env python
import json, os, requests
from awsauth import S3Auth
from datetime import datetime
from pytz import timezone
from flask import Flask, render_template, url_for
from models import app, db, FoodMenu, FoodServices
MIXPANEL_TOKEN = os.environ.get('MIXPANEL_TOKEN')
@app.route('/')
def renderMenu():
nowWaterloo = datetime.now(timezone('America/Toronto'))
foodMenu = FoodMenu.query.order_by(FoodMenu.id.desc()).first().result
menu = json.loads(foodMenu)['response']['data']
serviceInfo = FoodServices.query.order_by(FoodServices.id.desc()).first().result
locations = json.loads(serviceInfo)['response']['data']
return render_template('index.html', menu=menu, locations=locations, nowWaterloo=nowWaterloo, mixpanelToken=MIXPANEL_TOKEN)
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Set default email from name and address | <?php
/*
* This file is part of CSBill package.
*
* (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
class Version042 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql('ALTER TABLE security_token CHANGE payment_name gateway_name VARCHAR(255) NOT NULL');
$this->addSql('UPDATE app_config set setting_value = "info@csbill.org" WHERE setting_key = "from_address"');
$this->addSql('UPDATE app_config set setting_value = "CSBill" WHERE setting_key = "from_name"');
}
public function down(Schema $schema)
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql('ALTER TABLE security_token CHANGE gateway_name payment_name VARCHAR(255) NOT NULL');
$this->addSql('UPDATE app_config set setting_value = "" WHERE setting_key = "from_address"');
$this->addSql('UPDATE app_config set setting_value = "" WHERE setting_key = "from_name"');
}
}
| <?php
/*
* This file is part of CSBill package.
*
* (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
class Version042 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql('ALTER TABLE security_token CHANGE payment_name gateway_name VARCHAR(255) NOT NULL;');
}
public function down(Schema $schema)
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
}
}
|
Set Promise test exit code based on failure count
Previously, the exit was always zero, which is not very useful as part
of a continuous integration system.
Change-Id: I3fd5e9061f605950c48240419c2a093c74005144 | #!/usr/bin/env node
// Tests Shaka's Promises polyfill using the A+ conformance tests.
// Requires node.js, the 'promises-aplus-tests' module, and the compiled Shaka
// Player library.
// Load the compiled library.
var shaka = require('./shaka-player.compiled');
shaka.polyfill.Promise.install();
// Build an adapter for the test suite.
var adapter = {
resolved: Promise.resolve,
rejected: Promise.reject,
deferred: function() {
var resolveFn, rejectFn;
var p = new Promise(function(resolve, reject) {
resolveFn = resolve;
rejectFn = reject;
});
return { promise: p, resolve: resolveFn, reject: rejectFn };
}
};
// Load the test suite and run conformance tests.
// This implementation does not support thenables, which are not used by Shaka
// Player. Tests related to thenables (2.3.3.*) are therefore ignored.
var opts = { 'grep': /^2.3.3/, 'invert': true };
var promisesAplusTests = require('promises-aplus-tests');
promisesAplusTests(adapter, opts, function(err) {
var failures = err ? err.failures : 0;
console.log('FAILURES:', failures);
process.exit(failures ? 1 : 0);
});
| #!/usr/bin/env node
// Tests Shaka's Promises polyfill using the A+ conformance tests.
// Requires node.js, the 'promises-aplus-tests' module, and the compiled Shaka
// Player library.
// Load the compiled library.
var shaka = require('./shaka-player.compiled');
shaka.polyfill.Promise.install();
// Build an adapter for the test suite.
var adapter = {
resolved: Promise.resolve,
rejected: Promise.reject,
deferred: function() {
var resolveFn, rejectFn;
var p = new Promise(function(resolve, reject) {
resolveFn = resolve;
rejectFn = reject;
});
return { promise: p, resolve: resolveFn, reject: rejectFn };
}
};
// Load the test suite and run conformance tests.
// This implementation does not support thenables, which are not used by Shaka
// Player. Tests related to thenables (2.3.3.*) are therefore ignored.
var opts = { 'grep': /^2.3.3/, 'invert': true };
var promisesAplusTests = require('promises-aplus-tests');
promisesAplusTests(adapter, opts);
|
Update minor version to 0.0.2.
Change-Id: I48cd0789ec87d0edd20e9a2980a61b54f8c6b7a6 | # Copyright 2020 Google LLC
#
# 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.
"""AI Streams Python SDK."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import setuptools
VERSION = "0.0.2"
REQUIRED_PACKAGES = []
with open("requirements.txt", "r") as f:
REQUIRED_PACKAGES = f.read().splitlines()
CONSOLE_SCRIPTS = ["aisctl = aistreams.python.cli.aisctl:main"]
setuptools.setup(
name="aistreams",
version=VERSION,
author="Google Inc.",
author_email="",
description="AI Streams Python SDK",
long_description="AI Streams Python SDK",
long_description_content_type="text/markdown",
url="",
packages=setuptools.find_packages(),
install_requires=REQUIRED_PACKAGES,
entry_points={"console_scripts": CONSOLE_SCRIPTS},
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3",
],
python_requires=">=3.6",
)
| # Copyright 2020 Google LLC
#
# 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.
"""AI Streams Python SDK."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import setuptools
VERSION = "0.0.1"
REQUIRED_PACKAGES = []
with open("requirements.txt", "r") as f:
REQUIRED_PACKAGES = f.read().splitlines()
CONSOLE_SCRIPTS = ["aisctl = aistreams.python.cli.aisctl:main"]
setuptools.setup(
name="aistreams",
version=VERSION,
author="Google Inc.",
author_email="",
description="AI Streams Python SDK",
long_description="AI Streams Python SDK",
long_description_content_type="text/markdown",
url="",
packages=setuptools.find_packages(),
install_requires=REQUIRED_PACKAGES,
entry_points={"console_scripts": CONSOLE_SCRIPTS},
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3",
],
python_requires=">=3.6",
)
|
Update Mesos bindings to 0.27.0
Summary: Won't take effect until we update the deb that's installed.
Test Plan: staging (I've been able to install the generated deb on the staging scheduler)
Reviewers: kylec, paulruan
Reviewed By: paulruan
Subscribers: changesbot
Differential Revision: https://tails.corp.dropbox.com/D173733 | from distutils.core import setup
MESOS_VERSION = '0.27.0'
UBUNTU_VERSION = '14.04'
tests_require = ['pytest>=2.5.0,<2.6.0', 'pytest-cov>=1.6,<1.7',
'pytest-xdist>=1.9,<1.10', 'unittest2>=0.5.1,<0.6.0',
'mock>=1.0.1,<1.1.0', 'flask>=0.10.1,<0.11.0']
setup(name='changes-mesos-scheduler',
scripts=['scripts/changes-mesos-scheduler'],
packages=['changes_mesos_scheduler'],
extras_require={'tests': tests_require},
dependency_links = ['http://downloads.mesosphere.io/master/ubuntu/%s/mesos-%s-py2.7-linux-x86_64.egg#egg=mesos'
% (UBUNTU_VERSION, MESOS_VERSION)],
install_requires=['statsd', 'mesos'],
package_dir={'changes_mesos_scheduler': 'changes_mesos_scheduler'})
| from distutils.core import setup
MESOS_VERSION = '0.20.0'
UBUNTU_VERSION = '14.04'
tests_require = ['pytest>=2.5.0,<2.6.0', 'pytest-cov>=1.6,<1.7',
'pytest-xdist>=1.9,<1.10', 'unittest2>=0.5.1,<0.6.0',
'mock>=1.0.1,<1.1.0', 'flask>=0.10.1,<0.11.0']
setup(name='changes-mesos-scheduler',
scripts=['scripts/changes-mesos-scheduler'],
packages=['changes_mesos_scheduler'],
extras_require={'tests': tests_require},
dependency_links = ['http://downloads.mesosphere.io/master/ubuntu/%s/mesos-%s-py2.7-linux-x86_64.egg#egg=mesos'
% (UBUNTU_VERSION, MESOS_VERSION)],
install_requires=['statsd', 'mesos'],
package_dir={'changes_mesos_scheduler': 'changes_mesos_scheduler'})
|
Add missing member and fix doc. | <?php
/*
* This file is part of the Patternseek ComponentView library.
*
* (c) 2014 Tolan Blundell <tolan@patternseek.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PatternSeek\ComponentView;
/**
* Class Response
*/
/**
* Class Response
* @package PatternSeek\ComponentView
*/
class Response
{
/**
* Currently one of "redirect" or a valid MIME type.
* @var string
*/
public $type;
/**
* @var string
*/
public $content;
/**
* @var int
*/
public $responseCode;
/**
* @param string $type
* @param string $content
* @param int|null $responseCode
*/
function __construct( $type, $content, $responseCode = null )
{
$this->type = $type;
$this->content = $content;
// Response code defaults
if (null === $responseCode) {
if( $type == "redirect" ){
$responseCode = 302;
}else{
$responseCode = 200;
}
}
$this->responseCode = $responseCode;
}
}
| <?php
/*
* This file is part of the Patternseek ComponentView library.
*
* (c) 2014 Tolan Blundell <tolan@patternseek.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PatternSeek\ComponentView;
/**
* Class Response
*/
class Response
{
/**
* Currently one of "redirect" or a valid MIME type.
* @var string
*/
public $type;
/**
* @var string
*/
public $content;
/**
* @param $type
* @param $content
* @param null $responseCode
*/
function __construct( $type, $content, $responseCode = null )
{
$this->type = $type;
$this->content = $content;
// Response code defaults
if (null === $responseCode) {
if( $type == "redirect" ){
$responseCode = 302;
}else{
$responseCode = 200;
}
}
$this->responseCode = $responseCode;
}
}
|
Add paper for neat effect on incidents | import React, { PropTypes } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import styles from './Incident.css';
import Map from './Map';
import GridTile from 'material-ui/lib/grid-list/grid-tile';
import Paper from 'material-ui/lib/paper';
const Incident = ({ incident }) => (
<ReactCSSTransitionGroup
transitionName={styles}
transitionEnterTimeout={500}
transitionLeaveTimeout={300}
transitionAppear
transitionAppearTimeout={500}
>
<div className={styles.incident}>
<Paper zDepth={2}>
<GridTile
key={incident.id}
title={incident.description}
subtitle={incident.address}
>
<Map address={incident.address} />
</GridTile>
</Paper>
</div>
</ReactCSSTransitionGroup>
);
Incident.propTypes = {
incident: PropTypes.object.isRequired
};
export default Incident;
| import React, { PropTypes } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import styles from './Incident.css';
import Map from './Map';
import GridTile from 'material-ui/lib/grid-list/grid-tile';
const Incident = ({ incident }) => (
<ReactCSSTransitionGroup
transitionName={styles}
transitionEnterTimeout={500}
transitionLeaveTimeout={300}
transitionAppear
transitionAppearTimeout={500}
>
<div className={styles.incident}>
<GridTile
key={incident.id}
title={incident.description}
subtitle={incident.address}
>
<Map address={incident.address} />
</GridTile>
</div>
</ReactCSSTransitionGroup>
);
Incident.propTypes = {
incident: PropTypes.object.isRequired
};
export default Incident;
|
Use of @component for buttons in form | @component('core::admin._buttons-form', ['model' => $model])
@endcomponent
{!! BootForm::hidden('id') !!}
<div class="row">
<div class="col-md-6">
{!! BootForm::text(__('Tag'), 'tag') !!}
</div>
<div class="col-md-6 form-group @if($errors->has('slug'))has-error @endif">
{!! Form::label(__('Slug'))->addClass('control-label')->forId('slug') !!}
<div class="input-group">
{!! Form::text('slug')->addClass('form-control')->id('slug')->data('slug', 'tag') !!}
<span class="input-group-btn">
<button class="btn btn-default btn-slug @if($errors->has('slug'))btn-danger @endif" type="button">{{ __('Generate') }}</button>
</span>
</div>
{!! $errors->first('slug', '<p class="help-block">:message</p>') !!}
</div>
</div>
| @include('core::admin._buttons-form')
{!! BootForm::hidden('id') !!}
<div class="row">
<div class="col-md-6">
{!! BootForm::text(__('Tag'), 'tag') !!}
</div>
<div class="col-md-6 form-group @if($errors->has('slug'))has-error @endif">
{!! Form::label(__('Slug'))->addClass('control-label')->forId('slug') !!}
<div class="input-group">
{!! Form::text('slug')->addClass('form-control')->id('slug')->data('slug', 'tag') !!}
<span class="input-group-btn">
<button class="btn btn-default btn-slug @if($errors->has('slug'))btn-danger @endif" type="button">{{ __('Generate') }}</button>
</span>
</div>
{!! $errors->first('slug', '<p class="help-block">:message</p>') !!}
</div>
</div>
|
Fix API Doc json generator | <?php
namespace App\Http\Controllers\Api\Doc;
use Illuminate\Http\JsonResponse;
/**
* @OA\Info(title="Hammer CRM API", version="1.0")
*/
class DocGeneratorController
{
/**
* @OA\Get(
* path="/resource.json",
* @OA\Response(response="200", description="API JSON Specification OpenAPI format")
* )
*/
public function render() : JsonResponse
{
$app_path = app_path();
$openapi = \OpenApi\Generator::scan([
$app_path.DIRECTORY_SEPARATOR.'Http'.DIRECTORY_SEPARATOR.'Controllers'.DIRECTORY_SEPARATOR.'Api',
]);
return response()->json($openapi->toJson());
}
}
| <?php
namespace App\Http\Controllers\Api\Doc;
/**
* @OA\Info(title="Hammer CRM API", version="1.0")
*/
class DocGeneratorController
{
/**
* @OA\Get(
* path="/resource.json",
* @OA\Response(response="200", description="An example resource")
* )
*/
public function render()
{
$app_path = base_path();
$openapi = OpenApi\Generator::scan([
$app_path.DIRECTORY_SEPARATOR.'Http'.DIRECTORY_SEPARATOR.'Controllers'.DIRECTORY_SEPARATOR.'Api',
]);
return response()->json($openapi->toJson());
}
}
|
Support loading classes that use system classloader | package fi.evident.apina.java.reader;
import fi.evident.apina.java.model.JavaClass;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public final class ClassReaderUtils {
private ClassReaderUtils() { }
public static JavaClass loadClass(Class<?> cl) {
try (InputStream in = openInputStreamForClassBytes(cl)) {
return ClassMetadataReader.loadMetadata(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static InputStream openInputStreamForClassBytes(Class<?> cl) throws IOException {
String resourceName = cl.getName().replace('.', '/') + ".class";
ClassLoader classLoader = cl.getClassLoader();
if (classLoader == null)
classLoader = ClassLoader.getSystemClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(resourceName);
if (inputStream != null)
return inputStream;
else
throw new FileNotFoundException(resourceName);
}
}
| package fi.evident.apina.java.reader;
import fi.evident.apina.java.model.JavaClass;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public final class ClassReaderUtils {
private ClassReaderUtils() { }
public static JavaClass loadClass(Class<?> cl) {
try (InputStream in = openInputStreamForClassBytes(cl)) {
return ClassMetadataReader.loadMetadata(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static InputStream openInputStreamForClassBytes(Class<?> cl) throws IOException {
String resourceName = cl.getName().replace('.', '/') + ".class";
InputStream inputStream = cl.getClassLoader().getResourceAsStream(resourceName);
if (inputStream != null)
return inputStream;
else
throw new FileNotFoundException(resourceName);
}
}
|
Remove a comment about the polyfill that's no longer included | /*
* jquery.requestAnimationFrame
* https://github.com/gnarf37/jquery-requestAnimationFrame
* Requires jQuery 1.8+
*
* Copyright (c) 2012 Corey Frang
* Licensed under the MIT license.
*/
// UMD factory https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function (jQuery) {
var animating;
function raf() {
if ( animating ) {
window.requestAnimationFrame( raf );
jQuery.fx.tick();
}
}
if ( window.requestAnimationFrame ) {
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !animating ) {
animating = true;
raf();
}
};
jQuery.fx.stop = function() {
animating = false;
};
}
}));
| /*
* jquery.requestAnimationFrame
* https://github.com/gnarf37/jquery-requestAnimationFrame
* Requires jQuery 1.8+
*
* Copyright (c) 2012 Corey Frang
* Licensed under the MIT license.
*/
// UMD factory https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function (jQuery) {
// requestAnimationFrame polyfill adapted from Erik Möller
// fixes from Paul Irish and Tino Zijdel
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
var animating;
function raf() {
if ( animating ) {
window.requestAnimationFrame( raf );
jQuery.fx.tick();
}
}
if ( window.requestAnimationFrame ) {
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !animating ) {
animating = true;
raf();
}
};
jQuery.fx.stop = function() {
animating = false;
};
}
}));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.