text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove code to force ENABLE_ASYNCIO to False
Forcing ENABLE_ASYNCIO to False was interfering
with testing under async drivers when the
(third-party dialect) test suite included both
SQLAlchemy and Alembic tests.
Change-Id: I2fe40049c24ba8eba0a10011849a912c03aa381e | from sqlalchemy.testing import config
from sqlalchemy.testing import emits_warning
from sqlalchemy.testing import engines
from sqlalchemy.testing import exclusions
from sqlalchemy.testing import mock
from sqlalchemy.testing import provide_metadata
from sqlalchemy.testing import skip_if
from sqlalchemy.testing import uses_deprecated
from sqlalchemy.testing.config import combinations
from sqlalchemy.testing.config import fixture
from sqlalchemy.testing.config import requirements as requires
from .assertions import assert_raises
from .assertions import assert_raises_message
from .assertions import emits_python_deprecation_warning
from .assertions import eq_
from .assertions import eq_ignore_whitespace
from .assertions import expect_raises
from .assertions import expect_raises_message
from .assertions import expect_sqlalchemy_deprecated
from .assertions import expect_sqlalchemy_deprecated_20
from .assertions import expect_warnings
from .assertions import is_
from .assertions import is_false
from .assertions import is_not_
from .assertions import is_true
from .assertions import ne_
from .fixtures import TestBase
from .util import resolve_lambda
| from sqlalchemy.testing import config
from sqlalchemy.testing import emits_warning
from sqlalchemy.testing import engines
from sqlalchemy.testing import exclusions
from sqlalchemy.testing import mock
from sqlalchemy.testing import provide_metadata
from sqlalchemy.testing import skip_if
from sqlalchemy.testing import uses_deprecated
from sqlalchemy.testing.config import combinations
from sqlalchemy.testing.config import fixture
from sqlalchemy.testing.config import requirements as requires
from .assertions import assert_raises
from .assertions import assert_raises_message
from .assertions import emits_python_deprecation_warning
from .assertions import eq_
from .assertions import eq_ignore_whitespace
from .assertions import expect_raises
from .assertions import expect_raises_message
from .assertions import expect_sqlalchemy_deprecated
from .assertions import expect_sqlalchemy_deprecated_20
from .assertions import expect_warnings
from .assertions import is_
from .assertions import is_false
from .assertions import is_not_
from .assertions import is_true
from .assertions import ne_
from .fixtures import TestBase
from .util import resolve_lambda
try:
from sqlalchemy.testing import asyncio
except ImportError:
pass
else:
asyncio.ENABLE_ASYNCIO = False
|
Change Backend references to Frontend | <?php
/*
Autoload function for Open Badges Frontend
Based on PSR-4 autoloader example from:
https://github.com/php-fig/fig-standards
With some changes and using portable constants for directory
separators instead of assuming '/'
*/
spl_autoload_register(function($class) {
// Assume all classes are under this single namespace
$prefix = 'UoMCS\\OpenBadges\\Frontend\\';
$base_dir = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR;
$len = strlen($prefix);
// Skip this autoloader if class name does not begin with prefix
if (strncmp($prefix, $class, $len) !== 0)
{
return;
}
// Relative class is the last part of full class name
// e.g. UoMCS\OpenBadges\Frontend\Client => Client
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';
if (file_exists($file))
{
require $file;
}
});
| <?php
/*
Autoload function for Open Badges Backend
Based on PSR-4 autoloader example from:
https://github.com/php-fig/fig-standards
With some changes and using portable constants for directory
separators instead of assuming '/'
*/
spl_autoload_register(function($class) {
// Assume all classes are under this single namespace
$prefix = 'UoMCS\\OpenBadges\\Backend\\';
$base_dir = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR;
$len = strlen($prefix);
// Skip this autoloader if class name does not begin with prefix
if (strncmp($prefix, $class, $len) !== 0)
{
return;
}
// Relative class is the last part of full class name
// e.g. UoMCS\OpenBadges\Backend\Utility => Utility
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';
if (file_exists($file))
{
require $file;
}
});
|
Undo workaround for broken json-table-schema release (via messytables) | from setuptools import setup, find_packages
setup(
name='myria-python',
version='1.2.5',
author='Daniel Halperin',
author_email='dhalperi@cs.washington.edu',
packages=find_packages(),
scripts=[],
url='https://github.com/uwescience/myria',
description='Python interface for Myria.',
long_description=open('README.md').read(),
setup_requires=["requests"],
# see https://stackoverflow.com/questions/18578439
install_requires=["pip >= 1.5.6", "pyOpenSSL >= 0.14", "ndg-httpsclient",
"pyasn1", "requests", "requests_toolbelt",
"messytables", "unicodecsv"],
entry_points={
'console_scripts': [
'myria_upload = myria.cmd.upload_file:main'
],
},
)
| from setuptools import setup, find_packages
setup(
name='myria-python',
version='1.2.4',
author='Daniel Halperin',
author_email='dhalperi@cs.washington.edu',
packages=find_packages(),
scripts=[],
url='https://github.com/uwescience/myria',
description='Python interface for Myria.',
long_description=open('README.md').read(),
setup_requires=["requests"],
# see https://stackoverflow.com/questions/18578439
install_requires=["pip >= 1.5.6", "pyOpenSSL >= 0.14", "ndg-httpsclient",
"pyasn1", "requests", "requests_toolbelt",
"json-table-schema<0.2",
"messytables", "unicodecsv"],
entry_points={
'console_scripts': [
'myria_upload = myria.cmd.upload_file:main'
],
},
)
|
Fix JUnit test due to default config change | package seedu.taskmanager.commons.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Funtasktic\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod() {
Config defaultConfig = new Config();
assertNotNull(defaultConfig);
assertTrue(defaultConfig.equals(defaultConfig));
}
}
| package seedu.taskmanager.commons.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Task Manager App\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod() {
Config defaultConfig = new Config();
assertNotNull(defaultConfig);
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Include id in user profile data | const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const seedUsers = {
'kumarsi': {'email': 'kumarsi@thoughtworks.com', 'id': '13319',
'username': 'kumarsi'},
'harineem': {'email': 'harineem@thoughtworks.com', 'id': '12630',
'username': 'harineem'}
}
passport.use(new LocalStrategy(
function(username, password, done) {
if (password === 'secret') {
return done(null, seedUsers[username]);
}
done(null, false);
}));
passport.serializeUser(function(user, done) {
// TODO: please read the Passport documentation on how to implement this. We're now
// just serializing the entire 'user' object. It would be more sane to serialize
// just the unique user-id, so you can retrieve the user object from the database
// in .deserializeUser().
done(null, user);
});
passport.deserializeUser(function(user, done) {
// TODO: Again, read the documentation.
done(null, user);
});
exports = module.exports = passport; | const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
if (['kumarsi', 'harineem'].includes(username) && password === 'secret') {
done(null, {'email': `${username}@thoughtworks.com`, 'username': username})
}
done(null, false);
}));
passport.serializeUser(function(user, done) {
// TODO: please read the Passport documentation on how to implement this. We're now
// just serializing the entire 'user' object. It would be more sane to serialize
// just the unique user-id, so you can retrieve the user object from the database
// in .deserializeUser().
done(null, user);
});
passport.deserializeUser(function(user, done) {
// TODO: Again, read the documentation.
done(null, user);
});
exports = module.exports = passport; |
Allow port to be specified by environment variable | package main
import (
_ "expvar"
"github.com/codegangsta/negroni"
"github.com/meatballhat/negroni-logrus"
"github.com/unrolled/render"
"net/http"
"os"
)
func main() {
Run()
}
func Run() {
m := http.DefaultServeMux
n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
l := negronilogrus.NewMiddleware()
r := render.New(render.Options{
Layout: "layout",
})
n.Use(l)
n.UseHandler(m)
m.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
r.HTML(w, http.StatusOK, "index", "world")
})
var addr string
if len(os.Getenv("PORT")) > 0 {
addr = ":" + os.Getenv("PORT")
} else {
addr = ":3000"
}
l.Logger.Infof("Listening on %s", addr)
l.Logger.Fatal(http.ListenAndServe(addr, n))
}
| package main
import (
_ "expvar"
"github.com/codegangsta/negroni"
"github.com/meatballhat/negroni-logrus"
"github.com/unrolled/render"
"net/http"
)
func main() {
Run()
}
func Run() {
m := http.DefaultServeMux
n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
l := negronilogrus.NewMiddleware()
r := render.New(render.Options{
Layout: "layout",
})
n.Use(l)
n.UseHandler(m)
m.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
r.HTML(w, http.StatusOK, "index", "world")
})
addr := ":3000"
l.Logger.Infof("Listening on %s", addr)
l.Logger.Fatal(http.ListenAndServe(addr, n))
}
|
Make splitting with commas more sensible. | // Copyright 2015 Robert S. Gerus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package bot
import (
"math/rand"
"strings"
"time"
"github.com/arachnist/gorepost/irc"
)
func pick(output func(irc.Message), msg irc.Message) {
var args []string
if !strings.HasPrefix(msg.Trailing, ":pick ") {
return
}
a := strings.TrimPrefix(msg.Trailing, ":pick ")
if strings.Contains(a, ", ") {
args = strings.Split(a, ", ")
} else if strings.Contains(a, ",") {
args = strings.Split(a, ",")
} else {
args = strings.Fields(a)
}
choice := args[rand.Intn(len(args))]
output(reply(msg, choice))
}
func init() {
rand.Seed(time.Now().UnixNano())
addCallback("PRIVMSG", "pick", pick)
}
| // Copyright 2015 Robert S. Gerus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package bot
import (
"math/rand"
"strings"
"time"
"github.com/arachnist/gorepost/irc"
)
func pick(output func(irc.Message), msg irc.Message) {
var args []string
if !strings.HasPrefix(msg.Trailing, ":pick ") {
return
}
a := strings.TrimPrefix(msg.Trailing, ":pick ")
if strings.Contains(a, ",") {
args = strings.Split(a, ",")
} else {
args = strings.Fields(a)
}
choice := args[rand.Intn(len(args))]
output(reply(msg, choice))
}
func init() {
rand.Seed(time.Now().UnixNano())
addCallback("PRIVMSG", "pick", pick)
}
|
Move view to top of class | package scoutmgr.client.navbar;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest.Builder;
import scoutmgr.client.place.NameTokens;
public class NavbarPresenter
extends PresenterWidget<NavbarPresenter.View>
implements NavbarUiHandlers
{
interface View
extends com.gwtplatform.mvp.client.View, HasUiHandlers<NavbarUiHandlers>
{
}
@Inject
private PlaceManager _placeManager;
@Override
public void gotoEvents()
{
final PlaceRequest placeRequest = new Builder().nameToken( NameTokens.getEvents() ).build();
_placeManager.revealPlace(placeRequest);
}
@Override
public void gotoMembers()
{
final PlaceRequest placeRequest = new Builder().nameToken( NameTokens.getMembers() ).build();
_placeManager.revealPlace(placeRequest);
}
@Inject
NavbarPresenter( final EventBus eventBus,
final View view )
{
super( eventBus, view );
getView().setUiHandlers( this );
}
}
| package scoutmgr.client.navbar;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest.Builder;
import scoutmgr.client.place.NameTokens;
public class NavbarPresenter
extends PresenterWidget<NavbarPresenter.View>
implements NavbarUiHandlers
{
@Inject
private PlaceManager _placeManager;
@Override
public void gotoEvents()
{
final PlaceRequest placeRequest = new Builder().nameToken( NameTokens.getEvents() ).build();
_placeManager.revealPlace(placeRequest);
}
@Override
public void gotoMembers()
{
final PlaceRequest placeRequest = new Builder().nameToken( NameTokens.getMembers() ).build();
_placeManager.revealPlace(placeRequest);
}
interface View
extends com.gwtplatform.mvp.client.View, HasUiHandlers<NavbarUiHandlers>
{
}
@Inject
NavbarPresenter( final EventBus eventBus,
final View view )
{
super( eventBus, view );
getView().setUiHandlers( this );
}
}
|
Convert Endless Rage to 2 spaces | import React from 'react';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import Analyzer from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { SELECTED_PLAYER } from 'parser/core/EventFilter';
class EndlessRage extends Analyzer {
rageGen = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.ENDLESS_RAGE_TALENT.id);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).to(SELECTED_PLAYER), this.onPlayerBuff);
}
onPlayerBuff(event) {
if (event.ability.guid === SPELLS.ENRAGE.id) {
this.rageGen += 6;
}
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.ENDLESS_RAGE_TALENT.id}
value={`${this.rageGen} rage generated`}
label="Endless Rage"
/>
);
}
}
export default EndlessRage; | import React from 'react';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import Analyzer from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { SELECTED_PLAYER } from 'parser/core/EventFilter';
class EndlessRage extends Analyzer {
rageGen = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.ENDLESS_RAGE_TALENT.id);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).to(SELECTED_PLAYER), this.onPlayerBuff);
}
onPlayerBuff(event) {
if (event.ability.guid === SPELLS.ENRAGE.id) {
this.rageGen += 6;
}
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.ENDLESS_RAGE_TALENT.id}
value={`${this.rageGen} rage generated`}
label="Endless Rage"
/>
);
}
}
export default EndlessRage; |
Fix runtime JavaScript errors in chrome://options.
With chrome built with CHROMEOS=1, the following error occurs
in in chrome://options as sync-button and dummy-button don't exist.
Remove the binding code to fix the error.
[28843:28843:611993994873:INFO:CONSOLE(0)] "Uncaught TypeError: Cannot set property 'onclick' of null," source: chrome://options/system (528)
TEST=manually on ubuntu by "out/Release/chrome --test-type"
BUG=none
Review URL: http://codereview.chromium.org/2900008
git-svn-id: http://src.chromium.org/svn/trunk/src@52281 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f9c2701f5826f6dd7f578be3ed5ff2f6f5307e86 | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
///////////////////////////////////////////////////////////////////////////////
// SystemOptions class:
/**
* Encapsulated handling of ChromeOS system options page.
* @constructor
*/
function SystemOptions(model) {
OptionsPage.call(this, 'system', templateData.systemPage, 'systemPage');
}
SystemOptions.getInstance = function() {
if (SystemOptions.instance_)
return SystemOptions.instance_;
SystemOptions.instance_ = new SystemOptions(null);
return SystemOptions.instance_;
}
// Inherit SystemOptions from OptionsPage.
SystemOptions.prototype = {
__proto__: OptionsPage.prototype,
/**
* Initializes SystemOptions page.
* Calls base class implementation to starts preference initialization.
*/
initializePage: function() {
OptionsPage.prototype.initializePage.call(this);
var timezone = $('timezone-select');
if (timezone) {
timezone.initializeValues(templateData.timezoneList);
}
$('language-button').onclick = function(event) {
// TODO: Open ChromeOS language settings page.
};
},
};
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
///////////////////////////////////////////////////////////////////////////////
// SystemOptions class:
/**
* Encapsulated handling of ChromeOS system options page.
* @constructor
*/
function SystemOptions(model) {
OptionsPage.call(this, 'system', templateData.systemPage, 'systemPage');
}
SystemOptions.getInstance = function() {
if (SystemOptions.instance_)
return SystemOptions.instance_;
SystemOptions.instance_ = new SystemOptions(null);
return SystemOptions.instance_;
}
// Inherit SystemOptions from OptionsPage.
SystemOptions.prototype = {
__proto__: OptionsPage.prototype,
/**
* Initializes SystemOptions page.
* Calls base class implementation to starts preference initialization.
*/
initializePage: function() {
OptionsPage.prototype.initializePage.call(this);
var timezone = $('timezone-select');
if (timezone) {
timezone.initializeValues(templateData.timezoneList);
}
$('language-button').onclick = function(event) {
// TODO: Open ChromeOS language settings page.
};
$('sync-button').onclick = function(event) {
OptionsPage.showPageByName('sync');
}
$('dummy-button').onclick = function(event) {
OptionsPage.showOverlay('dummy');
}
},
};
|
Support FormData in request body; minor refactor | export default class HttpApi {
constructor (prefix = '') {
this.prefix = prefix
this.options = {
credentials: 'same-origin',
}
return this.callApi
}
callApi = (method, url, options = {}) => {
const opts = {
...this.options,
...options,
method,
}
if (typeof opts.body === 'object' && !(opts.body instanceof FormData)) {
opts.body = JSON.stringify(opts.body)
}
return fetch(`/api/${this.prefix}${url}`, opts)
.then(res => {
if (res.ok) {
const type = res.headers.get('Content-Type')
return (type && type.includes('application/json')) ? res.json() : res
}
// error
return res.text().then(txt => {
return Promise.reject(new Error(txt))
})
})
}
}
| export default class HttpApi {
constructor (prefix = '') {
this.prefix = prefix
this.opts = {
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json',
})
}
return this.callApi
}
callApi = (method, url, opts = {}) => {
opts = Object.assign({}, this.opts, opts)
opts.method = method
if (typeof opts.body === 'object') {
opts.body = JSON.stringify(opts.body)
}
return fetch(`/api/${this.prefix}${url}`, opts)
.then(res => {
if (res.ok) {
const type = res.headers.get('Content-Type')
return (type && type.includes('application/json')) ? res.json() : res
}
// error
return res.text().then(txt => {
return Promise.reject(new Error(txt))
})
})
}
}
|
Add small title specifically for Sticky posts and restructure if-else blocks | <header class="entry-header">
<?php
if (is_sticky() && !is_single()):
printf('<p class="sticky-title-sm">%s</p>', __('Must read', 'keitaro'));
endif;
if (is_singular()) :
the_title('<h1 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h1>');
elseif (is_front_page() && is_home()) :
the_title('<h3 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h3>');
elseif (is_sticky()) :
the_title('<h2 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h2>');
else :
the_title('<h2 class="entry-title h3"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h2>');
endif;
if ('post' === get_post_type()) :
echo '<div class="entry-meta">';
if (is_single() || is_archive() || is_home()) :
keitaro_posted_on();
endif;
echo '</div><!-- .entry-meta -->';
endif;
?>
</header>
| <header class="entry-header">
<?php
if (is_singular()) {
the_title('<h1 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h1>');
} elseif (is_front_page() && is_home()) {
the_title('<h3 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h3>');
} else {
the_title('<h2 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h2>');
}
if ('post' === get_post_type()) {
echo '<div class="entry-meta">';
if (is_single() || is_archive() || is_home()) {
keitaro_posted_on();
}
echo '</div><!-- .entry-meta -->';
};
?>
</header>
|
Use an exception without @ResponseStatus | /*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.mpalourdio.springboottemplate.service;
import com.mpalourdio.springboottemplate.exception.AnotherCustomException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ServiceWithProperties {
private final String valueFromConfig;
public ServiceWithProperties(@Value("${admin.username}") final String valueFromConfig) {
this.valueFromConfig = valueFromConfig;
}
public String getValueFromConfig() {
return valueFromConfig;
}
public void throwException() throws AnotherCustomException {
throw new AnotherCustomException("gosh");
}
}
| /*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.mpalourdio.springboottemplate.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ServiceWithProperties {
private final String valueFromConfig;
public ServiceWithProperties(@Value("${admin.username}") final String valueFromConfig) {
this.valueFromConfig = valueFromConfig;
}
public String getValueFromConfig() {
return valueFromConfig;
}
}
|
Add version by commit count | # Copyright 2017 Google 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
#
# https://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 setuptools import setup
import subprocess
COMMIT_COUNT = subprocess.check_output("git rev-list HEAD --count", shell=True)
VERSION = '1.0.{}'.format(COMMIT_COUNT)
setup(name='cloud-utils',
version=VERSION,
description='Python Cloud Utilities',
author='Arie Abramovici',
author_email='beast@google.com',
packages=['cloud_utils'],
entry_points={'console_scripts': ['list_instances = cloud_utils.list_instances:main']},
install_requires=['boto3', 'botocore', 'google-api-python-client',
'google-auth', 'texttable', 'futures', 'python-dateutil', 'pytz'],
zip_safe=False)
| # Copyright 2017 Google 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
#
# https://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 setuptools import setup
setup(name='cloud-utils',
version='1.0',
description='Python Cloud Utilities',
author='Arie Abramovici',
author_email='beast@google.com',
packages=['cloud_utils'],
entry_points={'console_scripts': ['list_instances = cloud_utils.list_instances:main']},
install_requires=['boto3', 'botocore', 'google-api-python-client',
'google-auth', 'texttable', 'futures', 'python-dateutil', 'pytz'],
zip_safe=False)
|
Add space_station field to detailed docking event | from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
class Meta:
model = SpaceStation
fields = ('id', 'url', 'name', 'image_url')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
| from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
|
Add stackdriver format support via TV4/logrus-stackdriver-formatter. Simply set format in config to stackdriver | package logging
import (
stackdriver "github.com/TV4/logrus-stackdriver-formatter"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// ConfigureLogging sets up open match logrus instance using the logging section of the matchmaker_config.json
// - log line format (text[default] or json)
// - min log level to include (debug, info [default], warn, error, fatal, panic)
// - include source file and line number for every event (false [default], true)
func ConfigureLogging(cfg *viper.Viper) {
switch cfg.GetString("logging.format") {
case "stackdriver":
logrus.SetFormatter(stackdriver.NewFormatter())
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "text":
default:
logrus.SetFormatter(&logrus.TextFormatter{})
}
switch cfg.GetString("logging.level") {
case "debug":
logrus.SetLevel(logrus.DebugLevel)
logrus.Warn("Debug logging level configured. Not recommended for production!")
case "warn":
logrus.SetLevel(logrus.WarnLevel)
case "error":
logrus.SetLevel(logrus.ErrorLevel)
case "fatal":
logrus.SetLevel(logrus.FatalLevel)
case "panic":
logrus.SetLevel(logrus.PanicLevel)
case "info":
default:
logrus.SetLevel(logrus.InfoLevel)
}
switch cfg.GetBool("logging.source") {
case true:
logrus.SetReportCaller(true)
}
}
| package logging
import (
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// ConfigureLogging sets up open match logrus instance using the logging section of the matchmaker_config.json
// - log line format (text[default] or json)
// - min log level to include (debug, info [default], warn, error, fatal, panic)
// - include source file and line number for every event (false [default], true)
func ConfigureLogging(cfg *viper.Viper) {
switch cfg.GetString("logging.format") {
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "text":
default:
logrus.SetFormatter(&logrus.TextFormatter{})
}
switch cfg.GetString("logging.level") {
case "debug":
logrus.SetLevel(logrus.DebugLevel)
logrus.Warn("Debug logging level configured. Not recommended for production!")
case "warn":
logrus.SetLevel(logrus.WarnLevel)
case "error":
logrus.SetLevel(logrus.ErrorLevel)
case "fatal":
logrus.SetLevel(logrus.FatalLevel)
case "panic":
logrus.SetLevel(logrus.PanicLevel)
case "info":
default:
logrus.SetLevel(logrus.InfoLevel)
}
switch cfg.GetBool("logging.source") {
case true:
logrus.SetReportCaller(true)
}
}
|
Create blank layer with VectorLayer instead of TileLayer | /**
* @module app.backgroundlayer.BlankLayer
*/
/**
* @fileoverview This file defines the Blank Layer service. This service
* creates an empty layer and the corresponding spec.
*/
import appModule from '../module.js';
import olVectorLayer from 'ol/layer/Vector';
import olVectorSource from 'ol/source/Vector';
/**
* @constructor
* @param {angularGettext.Catalog} gettextCatalog Gettext service.
* @ngInject
*/
const exports = function(gettextCatalog) {
/**
* @typedef {ol.layer.Tile}
* @private
*/
this.blankLayer_ = new olVectorLayer({
source: new olVectorSource({features: []})
});
var blankLabel = gettextCatalog.getString('blank');
this.blankLayer_.set('label', blankLabel);
};
/**
* Get the blank layer.
* @return {ol.layer.Tile} The blank tile.
*/
exports.prototype.getLayer = function() {
return this.blankLayer_;
};
appModule.service('appBlankLayer', exports);
export default exports;
| /**
* @module app.backgroundlayer.BlankLayer
*/
/**
* @fileoverview This file defines the Blank Layer service. This service
* creates an empty layer and the corresponding spec.
*/
import appModule from '../module.js';
import olLayerTile from 'ol/layer/Tile.js';
/**
* @constructor
* @param {angularGettext.Catalog} gettextCatalog Gettext service.
* @ngInject
*/
const exports = function(gettextCatalog) {
/**
* @typedef {ol.layer.Tile}
* @private
*/
this.blankLayer_ = new olLayerTile();
var blankLabel = gettextCatalog.getString('blank');
this.blankLayer_.set('label', blankLabel);
};
/**
* Get the blank layer.
* @return {ol.layer.Tile} The blank tile.
*/
exports.prototype.getLayer = function() {
return this.blankLayer_;
};
appModule.service('appBlankLayer', exports);
export default exports;
|
Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly. | """Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
| """Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
|
Allow invert of stack scroll | import BaseTool from './base/BaseTool.js';
import scroll from '../util/scroll.js';
/**
* @public
* @class StackScrollMouseWheelTool
* @memberof Tools
*
* @classdesc Tool for scrolling through a series using the mouse wheel.
* @extends Tools.Base.BaseTool
*/
export default class StackScrollMouseWheelTool extends BaseTool {
constructor(configuration = {}) {
const defaultConfig = {
name: 'StackScrollMouseWheel',
supportedInteractionTypes: ['MouseWheel'],
configuration: {
loop: false,
allowSkipping: true,
invert: false,
},
};
const initialConfiguration = Object.assign(defaultConfig, configuration);
super(initialConfiguration);
this.initialConfiguration = initialConfiguration;
}
mouseWheelCallback(evt) {
const { direction: images, element } = evt.detail;
const { loop, allowSkipping, invert } = this.configuration;
const direction = invert ? -images : images;
scroll(element, direction, loop, allowSkipping);
}
}
| import BaseTool from './base/BaseTool.js';
import scroll from '../util/scroll.js';
/**
* @public
* @class StackScrollMouseWheelTool
* @memberof Tools
*
* @classdesc Tool for scrolling through a series using the mouse wheel.
* @extends Tools.Base.BaseTool
*/
export default class StackScrollMouseWheelTool extends BaseTool {
constructor(configuration = {}) {
const defaultConfig = {
name: 'StackScrollMouseWheel',
supportedInteractionTypes: ['MouseWheel'],
configuration: {
loop: false,
allowSkipping: true,
},
};
const initialConfiguration = Object.assign(defaultConfig, configuration);
super(initialConfiguration);
this.initialConfiguration = initialConfiguration;
}
mouseWheelCallback(evt) {
const { direction: images, element } = evt.detail;
const { loop, allowSkipping } = this.configuration;
scroll(element, -images, loop, allowSkipping);
}
}
|
Remove repository function for getting requests by session | require('./request-store-manage');
var glimpse = require('glimpse'),
resourceRepository = require('./request-repository-remote'),
localRepository = require('./request-repository-local'),
streamRepository = require('./request-repository-stream');
module.exports = {
triggerGetLastestSummaries: function() {
resourceRepository.triggerGetLastestSummaries();
localRepository.triggerGetLastestSummaries();
},
triggerGetDetailFor: function(requestId) {
resourceRepository.triggerGetDetailFor(requestId);
localRepository.triggerGetDetailFor(requestId);
},
// TODO: Need to look and see if this is the best place for these
subscribeToLatestSummaries: function() {
streamRepository.subscribeToLatestSummaries();
},
subscribeToLatestSummariesPatches: function() {
streamRepository.subscribeToLatestSummariesPatches();
},
subscribeToDetailPatchesFor: function(requestId) {
streamRepository.subscribeToDetailPatchesFor(requestId);
}
};
| require('./request-store-manage');
var glimpse = require('glimpse'),
resourceRepository = require('./request-repository-remote'),
localRepository = require('./request-repository-local'),
streamRepository = require('./request-repository-stream');
module.exports = {
triggerGetLatestSummaryForSession: function(sessionId) {
// TODO: Not sure how this is going to work yet
// i.e. triggering a request for given sessions request
triggerGetLastestSummaries: function() {
resourceRepository.triggerGetLastestSummaries();
localRepository.triggerGetLastestSummaries();
},
triggerGetDetailFor: function(requestId) {
resourceRepository.triggerGetDetailFor(requestId);
localRepository.triggerGetDetailFor(requestId);
},
// TODO: Need to look and see if this is the best place for these
subscribeToLatestSummaries: function() {
streamRepository.subscribeToLatestSummaries();
},
subscribeToLatestSummariesPatches: function() {
streamRepository.subscribeToLatestSummariesPatches();
},
subscribeToDetailPatchesFor: function(requestId) {
streamRepository.subscribeToDetailPatchesFor(requestId);
}
};
|
Resolve bug with immutable map in rem-image.
Change-Id: Icb28f94059f3d577124984503020fd62f54e0c7a | package com.bq.oss.corbel.resources.rem.util;
import java.util.Optional;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;
public class ImageRemUtil {
public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
RequestParameters<ResourceParameters> requestParameters) {
MultivaluedMap<String, String> newParameters = new MultivaluedHashMap<String, String>(requestParameters.getParams());
newParameters.putSingle("prefix", "cachedImage." + prefix);
return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
requestParameters.getHeaders());
}
}
| package com.bq.oss.corbel.resources.rem.util;
import java.util.Optional;
import javax.ws.rs.core.MultivaluedMap;
import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;
public class ImageRemUtil {
public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
RequestParameters<ResourceParameters> requestParameters) {
MultivaluedMap<String, String> newParameters = requestParameters.getParams();
newParameters.putSingle("prefix", "cachedImage." + prefix);
return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
requestParameters.getHeaders());
}
}
|
OAK-3898: Add filter capabilities to the segment graph run mode
Bump export version
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1725678 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Version("10.0.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;
import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Version("9.0.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;
import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;
|
refactor(AirtableSerializer): Use Ember.Inflector to pluralize modelName | import Ember from 'ember';
import DS from 'ember-data';
const inflector = new Ember.Inflector();
export default DS.RESTSerializer.extend({
normalizeResponse(store, type, payload) {
const modelNamePlural = inflector.pluralize(type.modelName);
if(payload.records) {
payload[modelNamePlural] = payload.records;
delete payload.records;
payload.meta = {
offset: payload.offset
};
delete payload.offset;
payload[modelNamePlural].forEach((record) => {
Ember.merge(record, record.fields);
delete record.fields;
record.created = record.createdTime;
delete record.createdTime;
});
} else {
payload[type.modelName] = payload.fields;
payload[type.modelName].id = payload.id;
payload[type.modelName].created = payload.createdTime;
delete payload.id;
delete payload.fields;
delete payload.createdTime;
}
return this._super(...arguments);
}
// ToDo: Improve from
// https://github.com/201-created/ember-data-hal-9000/blob/master/addon/serializer.js
// keyForRelationship(key) {
// return Ember.String.underscore(key);
// }
});
| import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeResponse(store, type, payload) {
const modelNamePlural = type.modelName + 's'; // ToDo: Fix to pluralize // Ember.String.*
if(payload.records) {
payload[modelNamePlural] = payload.records;
delete payload.records;
payload.meta = {
offset: payload.offset
};
delete payload.offset;
payload[modelNamePlural].forEach((record) => {
Ember.merge(record, record.fields);
delete record.fields;
record.created = record.createdTime;
delete record.createdTime;
});
} else {
payload[type.modelName] = payload.fields;
payload[type.modelName].id = payload.id;
payload[type.modelName].created = payload.createdTime;
delete payload.id;
delete payload.fields;
delete payload.createdTime;
}
return this._super(...arguments);
}
// ToDo: Improve from
// https://github.com/201-created/ember-data-hal-9000/blob/master/addon/serializer.js
// keyForRelationship(key) {
// return Ember.String.underscore(key);
// }
});
|
Check duplicates > 1 instead of > 2 | import frappe
def execute():
keys_encountered = set()
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT distinct name, current
from
`tabSeries`
where
name in (Select name from `tabSeries` group by name having count(name) > 1)
''', as_dict=True)
for row in duplicate_keys:
if row.name in keys_encountered:
frappe.throw('''
Key {row.name} appears twice in `tabSeries` with different values.
Kindly remove the faulty one manually before continuing
'''.format(row=row))
frappe.db.sql('delete from `tabSeries` where name = %(key)s', {
'key': row.name
})
if row.current:
frappe.db.sql('insert into `tabSeries`(`name`, `current`) values (%(name)s, %(current)s)', row)
keys_encountered.add(row.name)
frappe.db.commit()
frappe.db.sql('ALTER table `tabSeries` ADD PRIMARY KEY IF NOT EXISTS (name)')
| import frappe
def execute():
keys_encountered = set()
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT distinct name, current
from
`tabSeries`
where
name in (Select name from `tabSeries` group by name having count(name) > 2)
''', as_dict=True)
for row in duplicate_keys:
if row.name in keys_encountered:
frappe.throw('''
Key {row.name} appears twice in `tabSeries` with different values.
Kindly remove the faulty one manually before continuing
'''.format(row=row))
frappe.db.sql('delete from `tabSeries` where name = %(key)s', {
'key': row.name
})
if row.current:
frappe.db.sql('insert into `tabSeries`(`name`, `current`) values (%(name)s, %(current)s)', row)
keys_encountered.add(row.name)
frappe.db.commit()
frappe.db.sql('ALTER table `tabSeries` ADD PRIMARY KEY IF NOT EXISTS (name)')
|
Remove these dependencies for now | // Load libraries
import angular from 'angular';
import 'angular-animate';
import 'angular-aria';
import 'angular-material';
//import 'tinycolor'
//import 'md-color-picker'
import AppController from 'src/AppController';
import MaterialHue from 'src/materialhue/MaterialHue';
export default angular.module( 'material-hue', [ 'ngMaterial', MaterialHue.name ] )
.config(($mdIconProvider, $mdThemingProvider) => {
// Register the user `avatar` icons
$mdIconProvider
.defaultIconSet("./assets/svg/avatars.svg", 128)
.icon("menu", "./assets/svg/menu.svg", 24)
.icon("share", "./assets/svg/share.svg", 24)
.icon("phone", "./assets/svg/phone.svg", 24);
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('pink');
})
.controller('AppController', AppController);
| // Load libraries
import angular from 'angular';
import 'angular-animate';
import 'angular-aria';
import 'angular-material';
import 'tinycolor'
import 'md-color-picker'
import AppController from 'src/AppController';
import MaterialHue from 'src/materialhue/MaterialHue';
export default angular.module( 'material-hue', [ 'ngMaterial', MaterialHue.name ] )
.config(($mdIconProvider, $mdThemingProvider) => {
// Register the user `avatar` icons
$mdIconProvider
.defaultIconSet("./assets/svg/avatars.svg", 128)
.icon("menu", "./assets/svg/menu.svg", 24)
.icon("share", "./assets/svg/share.svg", 24)
.icon("phone", "./assets/svg/phone.svg", 24);
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('pink');
})
.controller('AppController', AppController);
|
Comment to explain the magic number |
exports.up = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.string('event_id').index();
table.foreign('event_id')
.references('id')
.inTable('events')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
})
.raw(`
CREATE UNIQUE INDEX
only_one_check_in_per_event
ON
actions(user_id, event_id)
-- Magic number 9 is CHECK_IN_EVENT action type ID.
WHERE action_type_id = 9;
`);
};
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('event_id');
});
}
|
exports.up = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.string('event_id').index();
table.foreign('event_id')
.references('id')
.inTable('events')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
})
.raw(`
CREATE UNIQUE INDEX
only_one_check_in_per_event
ON
actions(user_id, event_id)
WHERE action_type_id = 9;
`);
};
// ALTER TABLE actions ADD CONSTRAINT actions_user_event_uniq UNIQUE (user_id, event_id)
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('event_id');
});
}
|
Reset version number to 0.2.1 in preparation for making release 0.2.2 (release script bumps version number) | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='relengapi-mapper',
version='0.2.1',
description='hg to git mapper',
author='Chris AtLee',
author_email='chris@atlee.ca',
url='https://github.com/petemoore/mapper',
packages=find_packages(),
namespace_packages=['relengapi', 'relengapi.blueprints'],
entry_points={
"relengapi.blueprints": [
'mapper = relengapi.blueprints.mapper:bp',
],
},
install_requires=[
'Flask',
'relengapi>=0.3',
'IPy',
'python-dateutil',
],
license='MPL2',
extras_require={
'test': [
'nose',
'mock'
]
})
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='relengapi-mapper',
version='0.2.3',
description='hg to git mapper',
author='Chris AtLee',
author_email='chris@atlee.ca',
url='https://github.com/petemoore/mapper',
packages=find_packages(),
namespace_packages=['relengapi', 'relengapi.blueprints'],
entry_points={
"relengapi.blueprints": [
'mapper = relengapi.blueprints.mapper:bp',
],
},
install_requires=[
'Flask',
'relengapi>=0.3',
'IPy',
'python-dateutil',
],
license='MPL2',
extras_require={
'test': [
'nose',
'mock'
]
})
|
Disable duplicate Rsync progress output | 'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
| 'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
progress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
|
Add empty state to My Stories (don't show empty table) + php-cs-fixer | <?php
use_helper('FrontEnd', 'Widgets');
$num_stories = StoriesPeer::getStoriesCounts($sf_user->getUserId());
?>
<h2>My Stories</h2>
<?php if ($num_stories->total === 0): ?>
<p>
This page will let you browse all the kanji stories you have edited in the <?= link_to('Study page', 'study/index'); ?>.
</p>
<?php else: ?>
<div class="mystories-stats text-xl mb-6">
<strong><?= $num_stories->private; ?></strong> private</li>,
<strong><?= $num_stories->public; ?></strong> public</li>
(<?= $num_stories->total; ?> total)
</div>
<div class="mb-6 relative">
<div class="absolute right-0 top-0">
<?= _bs_button_with_icon('Export to CSV', 'study/export', ['icon' => 'fa-file']); ?>
</div>
<div id="MyStoriesSelect" class="mb-3"><!-- vue --></div>
</div>
<div id="MyStoriesComponent">
<?php include_component('study', 'MyStoriesTable', [
'stories_uid' => $sf_user->getUserId(),
'profile_page' => false,
]); ?>
</div>
<?php endif; ?>
<?php
kk_globals_put('MYSTORIES_SORT_ACTIVE', $sort_active);
kk_globals_put('MYSTORIES_SORT_OPTIONS', $sort_options);
?>
| <?php
use_helper('FrontEnd', 'Widgets');
$num_stories = StoriesPeer::getStoriesCounts($sf_user->getUserId());
?>
<h2>My Stories</h2>
<div class="mystories-stats text-xl mb-6">
<strong><?php echo $num_stories->private ?></strong> private</li>,
<strong><?php echo $num_stories->public ?></strong> public</li>
(<?php echo $num_stories->total ?> total)
</div>
<div class="mb-6 relative">
<div class="absolute right-0 top-0">
<?php echo _bs_button_with_icon('Export to CSV', 'study/export', ['icon' => 'fa-file']) ?>
</div>
<div id="MyStoriesSelect" class="mb-3"><!-- vue --></div>
</div>
<div id="MyStoriesComponent">
<?php include_component('study', 'MyStoriesTable', ['stories_uid' => $sf_user->getUserId(), 'profile_page' => false]) ?>
</div>
<?php
kk_globals_put('MYSTORIES_SORT_ACTIVE', $sort_active);
kk_globals_put('MYSTORIES_SORT_OPTIONS', $sort_options);
?>
|
Add use statement for annotation. | <?php
namespace Ray\Di\Sample;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;
use Ray\Di\Di\PostConstruct;
use Ray\Di\Sample\Transactional;
use Ray\Di\Sample\Template;
class User
{
private $db;
/**
* @Inject
* @Named("pdo=pdo_user")
*/
public function __construct(\PDO $pdo)
{
$this->db = $pdo;
}
/**
* @PostConstruct
*/
public function init()
{
// if not exist...
$this->db->query("CREATE TABLE User (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)");
}
/**
* @Transactional
*/
public function createUser($name, $age)
{
$sth = $this->db->prepare("INSERT INTO User (Name, Age) VALUES (:name, :age)");
$sth->execute([':name' => $name, ':age' => $age]);
}
/**
* @Template
*/
public function readUsers()
{
$sth = $this->db->query("SELECT name, age FROM User");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
return $result;
}
}
| <?php
namespace Ray\Di\Sample;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;
use Ray\Di\Sample\Transactional;
use Ray\Di\Sample\Template;
class User
{
private $db;
/**
* @Inject
* @Named("pdo=pdo_user")
*/
public function __construct(\PDO $pdo)
{
$this->db = $pdo;
}
/**
* @PostConstruct
*/
public function init()
{
// if not exist...
$this->db->query("CREATE TABLE User (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)");
}
/**
* @Transactional
*/
public function createUser($name, $age)
{
$sth = $this->db->prepare("INSERT INTO User (Name, Age) VALUES (:name, :age)");
$sth->execute([':name' => $name, ':age' => $age]);
}
/**
* @Template
*/
public function readUsers()
{
$sth = $this->db->query("SELECT name, age FROM User");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
return $result;
}
}
|
Rename get -> one and asList -> all | package me.hfox.morphix.query;
import java.util.Iterator;
import java.util.List;
/**
* Created by Harry on 28/11/2017.
*
* An iterable set of results returned by a query object
*/
public interface QueryResult<T> extends Iterator<T> {
/**
* Alias of
* @see me.hfox.morphix.query.QueryResult#first();
* @return The first result returned by the query
*/
T one();
/**
* Get the first result from the query
* @return The first result returned by the query
*/
T first();
/**
* Get the last result from the query
* @return The last result returned by the query
*/
T last();
/**
* Get the results given by the query as a List
* @return An unmodifiable list of results
*/
List<T> all();
}
| package me.hfox.morphix.query;
import java.util.Iterator;
import java.util.List;
/**
* Created by Harry on 28/11/2017.
*
* An iterable set of results returned by a query object
*/
public interface QueryResult<T> extends Iterator<T> {
/**
* Alias of
* @see me.hfox.morphix.query.QueryResult#first();
* @return The first result returned by the query
*/
T get();
/**
* Get the first result from the query
* @return The first result returned by the query
*/
T first();
/**
* Get the last result from the query
* @return The last result returned by the query
*/
T last();
/**
* Get the results given by the query as a List
* @return An unmodifiable list of results
*/
List<T> asList();
}
|
Fix not returning value from deprecated functions in methods module | // Class static helpers.
import getHelper from '../class_static_methods/getHelper.js';
import getHelpers from '../class_static_methods/getHelpers.js';
import hasHelper from '../class_static_methods/hasHelper.js';
function onInitClass(Class, className) {
Class.getHelper = getHelper;
Class.getHelpers = getHelpers;
Class.hasHelper = hasHelper;
// Class static helpers.
Class.getMethod = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.getHelper" function instead.`
);
return this.getHelper.apply(this, args);
};
Class.getMethods = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.getHelpers" function instead.`
);
return this.getHelpers.apply(this, args);
};
Class.hasMethod = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.hasHelper" function instead.`
);
return this.hasHelper.apply(this, args);
};
};
export default onInitClass; | // Class static helpers.
import getHelper from '../class_static_methods/getHelper.js';
import getHelpers from '../class_static_methods/getHelpers.js';
import hasHelper from '../class_static_methods/hasHelper.js';
function onInitClass(Class, className) {
Class.getHelper = getHelper;
Class.getHelpers = getHelpers;
Class.hasHelper = hasHelper;
// Class static helpers.
Class.getMethod = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.getHelper" function instead.`
);
this.getHelper.apply(this, args);
};
Class.getMethods = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.getHelpers" function instead.`
);
this.getHelpers.apply(this, args);
};
Class.hasMethod = function(...args) {
console.warn(
`Deprecation warning: methods have been renamed to helpers, please ` +
`use the "${className}.hasHelper" function instead.`
);
this.hasHelper.apply(this, args);
};
};
export default onInitClass; |
Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily | import configargparse
DEFAULT_CONFIG_FILES=[
'./track.cfg',
'~/.track.cfg',
]
# Bit of a cheat... not actually an object constructor, just a 'make me an object' method
def ArgParser():
return configargparse.ArgParser(
ignore_unknown_config_file_keys =True,
allow_abbrev =True,
default_config_files =DEFAULT_CONFIG_FILES,
# formatter_class =configargparse.ArgumentDefaultsHelpFormatter,
formatter_class =configargparse.RawDescriptionHelpFormatter,
config_file_parser_class =configargparse.DefaultConfigFileParser, # INI format
args_for_setting_config_path =['-c', '--cfg'],
args_for_writing_out_config_file=['-w', '--cfg-write'],
)
| import configargparse
DEFAULT_CONFIG_FILES=[
'./track.cfg',
'~/.track.cfg',
]
# Bit of a cheat... not actually an object constructor, just a 'make me an object' method
def ArgParser():
return configargparse.ArgParser(
ignore_unknown_config_file_keys =True,
allow_abbrev =True,
default_config_files =DEFAULT_CONFIG_FILES,
formatter_class =configargparse.ArgumentDefaultsHelpFormatter,
config_file_parser_class =configargparse.DefaultConfigFileParser, # INI format
args_for_setting_config_path =['-c', '--cfg'],
args_for_writing_out_config_file=['-w', '--cfg-write'],
)
|
Correct the plugin name typo mistake | from distutils.core import setup
setup(
name='cmsplugin-filery',
version=".".join(map(str, __import__('cmsplugin_filery').__version__)),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description = 'Image gallery based on django-filer',
keywords=[
'django',
'django-cms',
'web',
'cms',
'cmsplugin',
'plugin',
'image',
'gallery',
],
packages=['cmsplugin_filery',],
package_dir={'cmsplugin_filery': 'cmsplugin_filery'},
package_data={'cmsplugin_filery': ['templates/*/*']},
provides=['cmsplugin_filery'],
include_package_data=True,
install_requires = ['django-inline-ordering>=0.1.1', 'easy-thumbnails',
'django-filer']
)
| from distutils.core import setup
setup(
name='cmsplugin_filery',
version=".".join(map(str, __import__('cmsplugin_filery').__version__)),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description = 'Image gallery based on django-filer',
keywords=[
'django',
'django-cms',
'web',
'cms',
'cmsplugin',
'plugin',
'image',
'gallery',
],
packages=['cmsplugin_filery',],
package_dir={'cmsplugin_filery': 'cmsplugin_filery'},
package_data={'cmsplugin_filery': ['templates/*/*']},
provides=['cmsplugin_filery'],
include_package_data=True,
install_requires = ['django-inline-ordering>=0.1.1', 'easy-thumbnails',
'django-filer']
)
|
Migrate Remote test to new HTTP API | var assert = require('assert');
var expect = require('chai').expect;
var Remote = require('../lib/remote');
var HTTP = require('../lib/http');
var server = new HTTP();
var index = '/';
describe('Remote', function () {
before(async function () {
await server.start();
});
after(async function () {
await server.stop();
});
it('should expose a constructor', function () {
assert.equal(typeof Remote, 'function');
});
it('can emulate HTTP GET', async function () {
var remote = new Remote({
host: 'localhost:3000',
secure: false
});
var result = await remote._GET(index);
assert.ok(result);
});
it('can emulate HTTP OPTIONS', async function () {
var remote = new Remote({
host: 'localhost:3000',
secure: false
});
var result = await remote._OPTIONS(index);
assert.ok(result);
});
});
| var assert = require('assert');
var expect = require('chai').expect;
var Remote = require('../lib/remote');
var HTTP = require('../lib/http');
var server = new HTTP();
var index = '/';
describe('Remote', function () {
before(function (done) {
server.start(done);
});
after(async function () {
await server.stop();
});
it('should expose a constructor', function () {
assert.equal(typeof Remote, 'function');
});
it('can emulate HTTP GET', async function () {
var remote = new Remote({
host: 'localhost:3000',
secure: false
});
var result = await remote._GET(index);
assert.ok(result);
});
it('can emulate HTTP OPTIONS', async function () {
var remote = new Remote({
host: 'localhost:3000',
secure: false
});
var result = await remote._OPTIONS(index);
assert.ok(result);
});
});
|
Remove duplicate definition of write_file | import os
import os.path
import subprocess
from whack.files import write_file
class HelloWorld(object):
BUILD = r"""#!/bin/sh
set -e
cd $1
cat > hello << EOF
#!/bin/sh
echo Hello world!
EOF
chmod +x hello
"""
EXPECTED_OUTPUT = "Hello world!\n"
def write_package_source(package_dir, scripts):
whack_dir = os.path.join(package_dir, "whack")
os.makedirs(whack_dir)
for name, contents in scripts.iteritems():
_write_script(os.path.join(whack_dir, name), contents)
def _write_script(path, contents):
write_file(path, contents)
_make_executable(path)
def _make_executable(path):
subprocess.check_call(["chmod", "u+x", path])
| import os
import os.path
import subprocess
class HelloWorld(object):
BUILD = r"""#!/bin/sh
set -e
cd $1
cat > hello << EOF
#!/bin/sh
echo Hello world!
EOF
chmod +x hello
"""
EXPECTED_OUTPUT = "Hello world!\n"
def write_package_source(package_dir, scripts):
whack_dir = os.path.join(package_dir, "whack")
os.makedirs(whack_dir)
for name, contents in scripts.iteritems():
_write_script(os.path.join(whack_dir, name), contents)
def _write_script(path, contents):
_write_file(path, contents)
_make_executable(path)
def _make_executable(path):
subprocess.check_call(["chmod", "u+x", path])
def _write_file(path, contents):
open(path, "w").write(contents)
|
Change cap on view file name. | var OppQuery = require('../models/OppQuery');
var Opp = require('../models/Opportunity');
module.exports = function(app) {
app.get('/fundme', oppQueryCreate);
app.get('/fundme.json', oppQueryCreateJson);
app.get('/oppquery/execute', oppQueryExecute);
};
/**
* GET /fundme
* FundMe Wizard.
*/
var oppQueryCreate = function(req, res, next) {
var formRenderObject = OppQuery.buildForm({ unflatten: true });
res.render('fundmeWizard', {
title: 'Wizard',
bodyClass: 'fundmeWizard',
form: formRenderObject
});
};
var oppQueryCreateJson = function(req, res, next) {
var form = OppQuery.buildForm({ unflatten: true });
res.json(form);
}
var oppQueryExecute = function(req, res, next) {
res.json(req.query);
/*var query = new OppQuery({ query: req.query });
query.save(function(err, savedQuery){
// Execute search here, render results;
res.json(savedQuery);
});*/
};
| var OppQuery = require('../models/OppQuery');
var Opp = require('../models/Opportunity');
module.exports = function(app) {
app.get('/fundme', oppQueryCreate);
app.get('/fundme.json', oppQueryCreateJson);
app.get('/oppquery/execute', oppQueryExecute);
};
/**
* GET /fundme
* FundMe Wizard.
*/
var oppQueryCreate = function(req, res, next) {
var formRenderObject = OppQuery.buildForm({ unflatten: true });
res.render('fundmewizard', {
title: 'Wizard',
bodyClass: 'fundmeWizard',
form: formRenderObject
});
};
var oppQueryCreateJson = function(req, res, next) {
var form = OppQuery.buildForm({ unflatten: true });
res.json(form);
}
var oppQueryExecute = function(req, res, next) {
res.json(req.query);
/*var query = new OppQuery({ query: req.query });
query.save(function(err, savedQuery){
// Execute search here, render results;
res.json(savedQuery);
});*/
};
|
TST: Add coverage for basic broker usage. | import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..examples.sample_data import temperature_ramp
from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=True, filestore=True)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
temperature_ramp.run()
def test_basic_usage(self):
header = db[-1]
events = db.fetch_events(header)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
| import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
Disable direct connect for sauce labs | var pr = process.env.TRAVIS_PULL_REQUEST;
var souceUser = process.env.SAUCE_USERNAME || "liqd";
var sauceKey = process.env.SAUCE_ACCESS_KEY;
var name = ((pr === "false") ? "" : "#" + pr + " ") + process.env.TRAVIS_COMMIT;
var common = require("./protractorCommon.js");
var local = {
sauceUser: souceUser,
sauceKey: sauceKey,
directConnect: false,
capabilities: {
"browserName": "chrome",
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER,
"build": process.env.TRAVIS_BUILD_NUMBER,
"name": name
},
allScriptsTimeout: 21000,
getPageTimeout: 20000,
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 120000,
isVerbose: true,
includeStackTrace: true
}
};
exports.config = Object.assign({}, common.config, local);
| var pr = process.env.TRAVIS_PULL_REQUEST;
var souceUser = process.env.SAUCE_USERNAME || "liqd";
var sauceKey = process.env.SAUCE_ACCESS_KEY;
var name = ((pr === "false") ? "" : "#" + pr + " ") + process.env.TRAVIS_COMMIT;
var common = require("./protractorCommon.js");
var local = {
sauceUser: souceUser,
sauceKey: sauceKey,
capabilities: {
"browserName": "chrome",
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER,
"build": process.env.TRAVIS_BUILD_NUMBER,
"name": name
},
allScriptsTimeout: 21000,
getPageTimeout: 20000,
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 120000,
isVerbose: true,
includeStackTrace: true
}
};
exports.config = Object.assign({}, common.config, local);
|
Fix an issue with the Stop mediakey | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
switch(request.action){
case 'NEXT-MK':
document.getElementsByClassName('control-next')[0].dispatchEvent(click_event);
break;
case 'PREV-MK':
document.getElementsByClassName('control-prev')[0].dispatchEvent(click_event);
break;
case 'STOP-MK':
if ( document.getElementsByClassName('control-pause').length > 0 )
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
break;
case 'PLAY-PAUSE-MK':
if ( document.getElementsByClassName('control-play').length > 0 )
document.getElementsByClassName('control-play')[0].dispatchEvent(click_event);
else
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
break;
}
}); | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
switch(request.action){
case 'NEXT-MK':
document.getElementsByClassName('control-next')[0].dispatchEvent(click_event);
break;
case 'PREV-MK':
document.getElementsByClassName('control-prev')[0].dispatchEvent(click_event);
break;
case 'STOP-MK':
if ( document.getElementsByClassName('control-pause').length > 0 )
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
case 'PLAY-PAUSE-MK':
if ( document.getElementsByClassName('control-play').length > 0 )
document.getElementsByClassName('control-play')[0].dispatchEvent(click_event);
else
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
break;
}
}); |
Fix broken default value in a Twitter migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('twitter', '0013_user_favorites'),
]
operations = [
migrations.AlterField(
model_name='tweet',
name='favorite_count',
field=models.PositiveIntegerField(default=0, help_text=b'Approximately how many times this had been favorited when fetched', blank=True),
),
migrations.AlterField(
model_name='tweet',
name='retweet_count',
field=models.PositiveIntegerField(default=0, help_text=b'Number of times this had been retweeted when fetched', blank=True),
),
migrations.AlterField(
model_name='user',
name='url',
field=models.URLField(default=b'', help_text=b'A URL provided by the user as part of their profile', blank=True),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('twitter', '0013_user_favorites'),
]
operations = [
migrations.AlterField(
model_name='tweet',
name='favorite_count',
field=models.PositiveIntegerField(default=b'', help_text=b'Approximately how many times this had been favorited when fetched', blank=True),
),
migrations.AlterField(
model_name='tweet',
name='retweet_count',
field=models.PositiveIntegerField(default=b'', help_text=b'Number of times this had been retweeted when fetched', blank=True),
),
migrations.AlterField(
model_name='user',
name='url',
field=models.URLField(default=b'', help_text=b'A URL provided by the user as part of their profile', blank=True),
),
]
|
Add additional comment about only matching first value | package eu.livotov.labs.android.d3s;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;
/**
* Utilities to find 3DS values in ACS webpages.
*/
final class D3SRegexUtils {
/**
* Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes.
*/
private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE);
/**
* Finds the PaRes in an html page.
* <p>
* Note: If more than one PaRes is found in a page only the first will be returned.
*
* @param html String representation of the html page to search within.
* @return PaRes or null if not found
*/
@Nullable
static String findPaRes(@NonNull String html) {
if (html.trim().isEmpty()) return null;
String paRes = null;
Matcher paresMatcher = paresFinder.matcher(html);
if (paresMatcher.find()) {
paRes = paresMatcher.group(1);
}
return paRes;
}
} | package eu.livotov.labs.android.d3s;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;
/**
* Utilities to find 3DS values in ACS webpages.
*/
final class D3SRegexUtils {
/**
* Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes.
*/
private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE);
/**
* Finds the PaRes in an html page.
*
* @param html String representation of the html page to search within.
* @return PaRes or null if not found
*/
@Nullable
static String findPaRes(@NonNull String html) {
if (html.trim().isEmpty()) return null;
String paRes = null;
Matcher paresMatcher = paresFinder.matcher(html);
if (paresMatcher.find()) {
paRes = paresMatcher.group(1);
}
return paRes;
}
} |
Change key used for url shortener
Incompatible with old keys, so do not use same key | var $ = require('jquery');
var LocalStorage = require('./local_storage');
var LOGIN = 'vizzuality';
var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b';
var UrlShortener = function() {
this.localStorage = new LocalStorage('cartodb_urls2'); // to not clash with old local storage cache, they're incompatible
};
UrlShortener.prototype.fetch = function(originalUrl, callbacks) {
var cachedUrl = this.localStorage.search(originalUrl);
if (cachedUrl) {
return callbacks.success(cachedUrl);
}
var self = this;
$.ajax({
url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY,
type: 'GET',
async: false,
dataType: 'jsonp',
success: function(res) {
if (res && res.data && res.data.url) {
var shortURL = res.data.url;
var d = {};
d[originalUrl] = shortURL;
self.localStorage.add(d);
callbacks.success(shortURL);
} else {
callbacks.error(originalUrl);
}
},
error: function() {
callbacks.error(originalUrl);
}
});
};
module.exports = UrlShortener;
| var $ = require('jquery');
var LocalStorage = require('./local_storage');
var LOGIN = 'vizzuality';
var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b';
var UrlShortener = function() {
this.localStorage = new LocalStorage('cartodb_urls');
};
UrlShortener.prototype.fetch = function(originalUrl, callbacks) {
var cachedUrl = this.localStorage.search(originalUrl);
if (cachedUrl) {
return callbacks.success(cachedUrl);
}
var self = this;
$.ajax({
url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY,
type: 'GET',
async: false,
dataType: 'jsonp',
success: function(res) {
if (res && res.data && res.data.url) {
var shortURL = res.data.url;
var d = {};
d[originalUrl] = shortURL;
self.localStorage.add(d);
callbacks.success(shortURL);
} else {
callbacks.error(originalUrl);
}
},
error: function() {
callbacks.error(originalUrl);
}
});
};
module.exports = UrlShortener;
|
Remove broken development mode detection from install command, but build by default as init does. | <?php
namespace drunomics\Phapp\Commands;
use drunomics\Phapp\PhappCommandBase;
use drunomics\Phapp\ServiceUtil\BuildCommandsTrait;
/**
* Provides the install command.
*/
class InstallCommands extends PhappCommandBase {
use BuildCommandsTrait;
/**
* Installs the application.
*
* @option bool $build Build before running an update.
*
* @command install
*/
public function install(array $options = ['build' => TRUE]) {
$collection = $this->collectionBuilder();
$collection->setProgressIndicator(NULL);
if ($options['build']) {
$collection->addCode(function() {
$this->io()->title('Building...');
});
$collection->addTask(
$this->getBuildCommands()->build(['clean' => FALSE])
);
$collection->addCode(function() {
$this->io()->title('Installing...');
});
}
$collection->addTask(
$this->invokeManifestCommand('install')
);
return $collection;
}
}
| <?php
namespace drunomics\Phapp\Commands;
use drunomics\Phapp\PhappCommandBase;
use drunomics\Phapp\ServiceUtil\BuildCommandsTrait;
/**
* Provides the install command.
*/
class InstallCommands extends PhappCommandBase {
use BuildCommandsTrait;
/**
* Installs the application.
*
* @option bool $build Build before running an update if the app is in
* development mode.
*
* @command install
*/
public function install(array $options = ['build' => TRUE]) {
$collection = $this->collectionBuilder();
$collection->setProgressIndicator(NULL);
if (getenv('PHAPP_ENV_MODE') == 'development' && $options['build']) {
$collection->addCode(function() {
$this->io()->title('Building...');
});
$collection->addTask(
$this->getBuildCommands()->build(['clean' => FALSE])
);
$collection->addCode(function() {
$this->io()->title('Installing...');
});
}
$collection->addTask(
$this->invokeManifestCommand('install')
);
return $collection;
}
}
|
Fix malformed example suffix for a function. | package simpledb_test
import (
"github.com/garyburd/redigo/redis"
"github.com/northbright/simpledb"
)
func ExampleGetRedisHashMaxZiplistEntries() {
var err error
var redisHashMaxZiplistEntries uint64 = 0
simpledb.DebugPrintf("\n")
simpledb.DebugPrintf("--------- GetRedisHashMaxZiplistEntries() Test Begin --------\n")
c, err := redis.Dial("tcp", ":6379")
if err != nil {
goto end
}
defer c.Close()
redisHashMaxZiplistEntries, err = simpledb.GetRedisHashMaxZiplistEntries(c)
if err != nil {
goto end
}
simpledb.DebugPrintf("Redis hash-max-ziplist-entries: %v\n", redisHashMaxZiplistEntries)
end:
if err != nil {
simpledb.DebugPrintf("error: %v\n", err)
}
simpledb.DebugPrintf("--------- GetRedisHashMaxZiplistEntries() Test End --------\n")
// Output:
}
| package simpledb_test
import (
"github.com/garyburd/redigo/redis"
"github.com/northbright/simpledb"
)
func Example_GetRedisHashMaxZiplistEntries() {
var err error
var redisHashMaxZiplistEntries uint64 = 0
simpledb.DebugPrintf("\n")
simpledb.DebugPrintf("--------- GetRedisHashMaxZiplistEntries() Test Begin --------\n")
c, err := redis.Dial("tcp", ":6379")
if err != nil {
goto end
}
defer c.Close()
redisHashMaxZiplistEntries, err = simpledb.GetRedisHashMaxZiplistEntries(c)
if err != nil {
goto end
}
simpledb.DebugPrintf("Redis hash-max-ziplist-entries: %v\n", redisHashMaxZiplistEntries)
end:
if err != nil {
simpledb.DebugPrintf("error: %v\n", err)
}
simpledb.DebugPrintf("--------- GetRedisHashMaxZiplistEntries() Test End --------\n")
// Output:
}
|
Add data to api fixture | import APIConstants from '../constants/APIConstants'
import randomInt from '../../app/helpers/random-int'
const fixture = require('../fixture-data')
function getLatest(){
var p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, AppConstants.DEV_TIMEOUT)
})
return p
}
function getByDate(date){
return getByDateCall(date)
.then((data) => {
if (APIConstants.TEST_FAILURE)
throw new Error("Error")
else
return data
})
}
function getByDateCall(date){
var arr = Array.apply(null, Array(7))
arr.forEach((item, i) => arr[i] = `images/img_${i+1}.jpg`)
let image = randomInt(1, 7)
fixture.hdurl = arr[image-1]
fixture.url = arr[image-1]
fixture.date = date
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, APIConstants.DEV_TIMEOUT)
})
return p
}
module.exports = {
getLatest,
getByDate
}
| import APIConstants from '../constants/APIConstants'
import randomInt from '../../app/helpers/random-int'
const fixture = require('../fixture-data')
function getLatest(){
var p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, AppConstants.DEV_TIMEOUT)
})
return p
}
function getByDate(date){
return getByDateCall(date)
.then((data) => {
if (APIConstants.TEST_FAILURE)
throw new Error("Error")
else
return data
})
}
function getByDateCall(date){
var arr = Array.apply(null, Array(7))
arr.forEach((item, i) => arr[i] = `images/img_${i+1}.jpg`)
let image = randomInt(1, 7)
fixture.hdurl = arr[image-1]
fixture.url = arr[image-1]
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fixture)
}, APIConstants.DEV_TIMEOUT)
})
return p
}
module.exports = {
getLatest,
getByDate
}
|
Fix bug in rerender test helper | import { Component } from '../../src';
/**
* Setup the test environment
* @returns {HTMLDivElement}
*/
export function setupScratch() {
const scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
return scratch;
}
/**
* Setup a rerender function that will drain the queue of pending renders
* @returns {() => void}
*/
export function setupRerender() {
Component.__test__previousDebounce = Component.debounce;
Component.debounce = cb => Component.__test__drainQueue = cb;
return () => Component.__test__drainQueue && Component.__test__drainQueue();
}
/**
* Teardown test environment and reset preact's internal state
* @param {HTMLDivElement} scratch
*/
export function teardown(scratch) {
scratch.parentNode.removeChild(scratch);
if (Component.__test__drainQueue) {
// Flush any pending updates leftover by test
Component.__test__drainQueue();
delete Component.__test__drainQueue;
}
if (typeof Component.__test__previousDebounce !== 'undefined') {
Component.debounce = Component.__test__previousDebounce;
delete Component.__test__previousDebounce;
}
}
| import { Component } from '../../src';
/**
* Setup the test environment
* @returns {HTMLDivElement}
*/
export function setupScratch() {
const scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
return scratch;
}
/**
* Setup a rerender function that will drain the queue of pending renders
* @returns {() => void}
*/
export function setupRerender() {
let drainQueue;
Component.__test__previousDebounce = Component.debounce;
Component.debounce = cb => drainQueue = cb;
return () => drainQueue && drainQueue();
}
/**
* Teardown test environment and reset preact's internal state
* @param {HTMLDivElement} scratch
*/
export function teardown(scratch) {
scratch.parentNode.removeChild(scratch);
if (typeof Component.__test__previousDebounce !== 'undefined') {
Component.debounce = Component.__test__previousDebounce;
delete Component.__test__previousDebounce;
}
}
|
Order the records by creation date | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
City = mongoose.model('City'),
_ = require('lodash');
/**
* Find city by id
*/
exports.city = function(req, res, next, id) {
City.load(id, function(err, city) {
if (err) return next(err);
if (!city) return next(new Error('Failed to load city ' + id));
city.records = _.sortBy(city.records, 'created');
req.city = city;
next();
});
};
/**
* Show a city
*/
exports.show = function(req, res) {
res.jsonp(req.city);
};
/**
* List of Cities
*/
exports.all = function(req, res) {
City.find().exec(function(err, cities) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list the cities'
});
}
_.each(cities, function(city){
city.records = _.sortBy(city.records, 'created');
});
res.jsonp(cities);
});
};
| 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
City = mongoose.model('City');
/**
* Find city by id
*/
exports.city = function(req, res, next, id) {
City.load(id, function(err, city) {
if (err) return next(err);
if (!city) return next(new Error('Failed to load city ' + id));
req.city = city;
next();
});
};
/**
* Show a city
*/
exports.show = function(req, res) {
res.jsonp(req.city);
};
/**
* List of Cities
*/
exports.all = function(req, res) {
City.find().sort('-created').exec(function(err, cities) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list the cities'
});
}
res.jsonp(cities);
});
};
|
Use /dist as the base output dir for all plugins | /* eslint-env node */
const webpack = require('webpack');
const debug = require('debug')('app:webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const isDev = process.env.NODE_ENV !== 'production';
debug(`Running in ${isDev ? 'development' : 'production'} mode`);
module.exports = {
entry: {
main: './src/browser/main',
'service-worker': './src/browser/service-worker.js',
},
output: {
path: `${__dirname}/dist`,
filename: 'scripts/[name].js',
},
module: {
rules: [{test: /\.js$/, exclude: /node_modules/, use: ['babel-loader']}],
},
plugins: [].concat(
new CleanWebpackPlugin('dist'),
new CopyWebpackPlugin([{from: 'static'}]),
isDev ? [] : new webpack.optimize.UglifyJsPlugin({sourceMap: true}),
new webpack.DefinePlugin({BUILD_ID: Date.now()}),
new webpack.BannerPlugin({banner: `Build date: ${new Date()}`})
),
devtool: 'source-map',
};
| /* eslint-env node */
const webpack = require('webpack');
const debug = require('debug')('app:webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const isDev = process.env.NODE_ENV !== 'production';
debug(`Running in ${isDev ? 'development' : 'production'} mode`);
module.exports = {
entry: {
main: './src/browser/main',
'service-worker': './src/browser/service-worker.js',
},
output: {
path: `${__dirname}/dist/scripts`,
filename: '[name].js',
},
module: {
rules: [{test: /\.js$/, exclude: /node_modules/, use: ['babel-loader']}],
},
plugins: [].concat(
new CleanWebpackPlugin('dist'),
new CopyWebpackPlugin([{from: 'static', to: `${__dirname}/dist`}]),
isDev ? [] : new webpack.optimize.UglifyJsPlugin({sourceMap: true}),
new webpack.DefinePlugin({BUILD_ID: Date.now()}),
new webpack.BannerPlugin({banner: `Build date: ${new Date()}`})
),
devtool: 'source-map',
};
|
Return only resident latesst activity by type. | Meteor.methods({
'getResidentsLatestActivityByType': function (activityTypeId) {
// Get resident latest activity by type
var residentLatestActivityByType = Activities.aggregate([
{$match:
{activityTypeId: 'ccuz85YWbfAx4Yg7B'}
},
{$sort:
{activityDate: -1}
},
{$unwind: '$residentIds'},
{$group:
{
_id: "$residentIds",
latestActivity: {$first: '$activityDate'}
}
}
]);
return residentLatestActivityByType;
},
'getResidentsWithoutActivityByType': function (activityTypeId) {
// Get resident latest activity by type
var residentLastActivityByType = Meteor.call('getResidentsLatestActivityByType', activityTypeId);
// Get all resident IDs
var residentIds = Residents.find({}, {fields: {_id: 1}}).fetch();
// Get residents who have participated in the activity type
var residentsWithPreviousActivity = _.map(residentLastActivityByType, function (resident) {
return resident._id;
});
// Get residents who have not participated in activity type
var residentsWithoutPreviousActivity = _.difference(residentIds, residentsWithPreviousActivity);
return residentsWithoutPreviousActivity;
}
});
| Meteor.methods({
'getResidentsLatestActivityByType': function (activityTypeId) {
// Get resident latest activity by type
var residentLastActivityByType = Activities.aggregate([
{$match:
{activityTypeId: 'ccuz85YWbfAx4Yg7B'}
},
{$sort:
{activityDate: -1}
},
{$unwind: '$residentIds'},
{$group:
{
_id: "$residentIds",
activities: {$push: '$activityDate'}
}
}
]);
return residentLastActivityByType;
},
'getResidentsWithoutActivityByType': function (activityTypeId) {
// Get resident latest activity by type
var residentLastActivityByType = Meteor.call('getResidentsLatestActivityByType', activityTypeId);
// Get all resident IDs
var residentIds = Residents.find({}, {fields: {_id: 1}}).fetch();
// Get residents who have participated in the activity type
var residentsWithPreviousActivity = _.map(residentLastActivityByType, function (resident) {
return resident._id;
});
// Get residents who have not participated in activity type
var residentsWithoutPreviousActivity = _.difference(residentIds, residentsWithPreviousActivity);
return residentsWithoutPreviousActivity;
}
});
|
Make m2sh have the same version number as mongrel2. |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '1.0beta5',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '0.2',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
|
Remove all-gap columns after removing rows of the alignment | #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
| #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
Make sure to also swap out the options | import React from 'react';
import _Story from './components/Story';
export const Story = _Story;
const defaultOptions = {
inline: false,
header: true,
source: true,
};
export default {
addWithInfo(storyName, _info, _storyFn, _options) {
const options = {
...defaultOptions,
..._options
};
this.add(storyName, (context) => {
let info = _info;
let storyFn = _storyFn;
if (typeof storyFn !== 'function') {
if (typeof info === 'function') {
options = storyFn;
storyFn = info;
info = '';
} else {
throw new Error('No story defining function has been specified');
}
}
const props = {
info,
context,
showInline: Boolean(options.inline),
showHeader: Boolean(options.header),
showSource: Boolean(options.source),
propTables: options.propTables,
};
return (
<Story {...props}>
{storyFn(context)}
</Story>
);
});
}
};
| import React from 'react';
import _Story from './components/Story';
export const Story = _Story;
const defaultOptions = {
inline: false,
header: true,
source: true,
};
export default {
addWithInfo(storyName, _info, _storyFn, _options) {
const options = {
...defaultOptions,
..._options
};
this.add(storyName, (context) => {
let info = _info;
let storyFn = _storyFn;
if (typeof storyFn !== 'function') {
if (typeof info === 'function') {
storyFn = info;
info = '';
} else {
throw new Error('No story defining function has been specified');
}
}
const props = {
info,
context,
showInline: Boolean(options.inline),
showHeader: Boolean(options.header),
showSource: Boolean(options.source),
propTables: options.propTables,
};
return (
<Story {...props}>
{storyFn(context)}
</Story>
);
});
}
};
|
Use Descendent `increment` and `decrement`. | var Queue = require('prolific.queue')
var createUncaughtExceptionHandler = require('./uncaught')
var abend = require('abend')
var assert = require('assert')
function Shuttle (pid, sync, uncaught, descendent) {
this.queue = new Queue(pid, sync)
this.uncaught = createUncaughtExceptionHandler(uncaught)
this._descendent = descendent
this._descendent.increment()
}
Shuttle.prototype.uncaughtException = function (error) {
this.uncaught.call(null, error)
this.exit()
throw error
}
Shuttle.prototype.close = function () {
this._descendent.decrement()
this.queue.close()
}
Shuttle.prototype.exit = function () {
this.close()
this.queue.exit()
}
Shuttle.prototype.setPipe = function (input, output) {
this.queue.setPipe(output)
}
Shuttle.shuttle = require('./bootstrap').createShuttle(require('net'), Shuttle, Date)
Shuttle.filename = module.filename
Shuttle.sink = require('prolific.sink')
module.exports = Shuttle
| var Queue = require('prolific.queue')
var createUncaughtExceptionHandler = require('./uncaught')
var abend = require('abend')
var assert = require('assert')
function Shuttle (pid, sync, uncaught, descendent) {
this.queue = new Queue(pid, sync)
this.uncaught = createUncaughtExceptionHandler(uncaught)
this._descendent = descendent
}
Shuttle.prototype.uncaughtException = function (error) {
this.uncaught.call(null, error)
this.exit()
throw error
}
Shuttle.prototype.close = function () {
this._descendent.destroy()
this.queue.close()
}
Shuttle.prototype.exit = function () {
this.close()
this.queue.exit()
}
Shuttle.prototype.setPipe = function (input, output) {
this.queue.setPipe(output)
}
Shuttle.shuttle = require('./bootstrap').createShuttle(require('net'), Shuttle, Date)
Shuttle.filename = module.filename
Shuttle.sink = require('prolific.sink')
module.exports = Shuttle
|
Make sure all React pages have a CSRF token in session
Fixes GH-2419 | from __future__ import absolute_import
from django.core.context_processors import csrf
from django.http import HttpResponse
from django.template import loader, Context
from sentry.web.frontend.base import BaseView, OrganizationView
class ReactMixin(object):
def handle_react(self, request):
context = Context({'request': request})
context.update(csrf(request))
template = loader.render_to_string('sentry/bases/react.html', context)
response = HttpResponse(template)
response['Content-Type'] = 'text/html'
return response
# TODO(dcramer): once we implement basic auth hooks in React we can make this
# generic
class ReactPageView(OrganizationView, ReactMixin):
def handle(self, request, **kwargs):
return self.handle_react(request)
class GenericReactPageView(BaseView, ReactMixin):
def handle(self, request, **kwargs):
return self.handle_react(request)
| from __future__ import absolute_import
from django.http import HttpResponse
from django.template import loader, Context
from sentry.web.frontend.base import BaseView, OrganizationView
class ReactMixin(object):
def handle_react(self, request):
context = Context({'request': request})
template = loader.render_to_string('sentry/bases/react.html', context)
response = HttpResponse(template)
response['Content-Type'] = 'text/html'
return response
# TODO(dcramer): once we implement basic auth hooks in React we can make this
# generic
class ReactPageView(OrganizationView, ReactMixin):
def handle(self, request, **kwargs):
return self.handle_react(request)
class GenericReactPageView(BaseView, ReactMixin):
def handle(self, request, **kwargs):
return self.handle_react(request)
|
Remove unneeded div around tile element
Signed-off-by: Max Brunsfeld <78036c9b69b887700d5846f26a788d53b201ffbb@gmail.com> | 'use babel';
let lineEndingTile = null;
export function activate() {
atom.workspace.observeActivePaneItem((item) => {
let ending = getLineEnding(item);
if (lineEndingTile) lineEndingTile.textContent = ending;
});
}
export function consumeStatusBar(statusBar) {
lineEndingTile = document.createElement('a');
lineEndingTile.className = "line-ending-tile";
statusBar.addRightTile({item: lineEndingTile, priority: 200});
}
function getLineEnding(item) {
if (!item) return "";
let hasLF = false;
let hasCRLF = false;
if (item && item.scan) {
item.scan(/\n|\r\n/g, ({matchText}) => {
if (matchText === "\n") hasLF = true;
if (matchText === "\r\n") hasCRLF = true;
});
}
if (hasLF && hasCRLF) return "Mixed";
if (hasLF) return "LF";
if (hasCRLF) return "CRLF";
if (process.platform === 'win32') return "CRLF";
return "LF";
}
| 'use babel';
let lineEndingTile = null;
export function activate() {
atom.workspace.observeActivePaneItem((item) => {
let ending = getLineEnding(item);
if (lineEndingTile) lineEndingTile.firstChild.textContent = ending;
});
}
export function consumeStatusBar(statusBar) {
lineEndingTile = document.createElement('div');
lineEndingTile.style.display = "inline-block";
lineEndingTile.className = "line-ending-tile";
lineEndingTile.innerHTML = "<a></a>";
statusBar.addRightTile({item: lineEndingTile, priority: 200});
}
function getLineEnding(item) {
if (!item) return "";
let hasLF = false;
let hasCRLF = false;
if (item && item.scan) {
item.scan(/\n|\r\n/g, ({matchText}) => {
if (matchText === "\n") hasLF = true;
if (matchText === "\r\n") hasCRLF = true;
});
}
if (hasLF && hasCRLF) return "Mixed";
if (hasLF) return "LF";
if (hasCRLF) return "CRLF";
if (process.platform === 'win32') return "CRLF";
return "LF";
}
|
Change development reload shortcut to F5
This prevents interference when using bash's Ctrl-R command | "use strict";
const electron = require("electron");
const {app} = electron;
const {Menu} = electron;
const {BrowserWindow} = electron;
module.exports.setDevMenu = function () {
var devMenu = Menu.buildFromTemplate([{
label: "Development",
submenu: [{
label: "Reload",
accelerator: "F5",
click: function () {
BrowserWindow.getFocusedWindow().reload();
}
},{
label: "Toggle DevTools",
accelerator: "Alt+CmdOrCtrl+I",
click: function () {
BrowserWindow.getFocusedWindow().toggleDevTools();
}
},{
label: "Quit",
accelerator: "CmdOrCtrl+Q",
click: function () {
app.quit();
}
}]
}]);
Menu.setApplicationMenu(devMenu);
}; | "use strict";
const electron = require("electron");
const {app} = electron;
const {Menu} = electron;
const {BrowserWindow} = electron;
module.exports.setDevMenu = function () {
var devMenu = Menu.buildFromTemplate([{
label: "Development",
submenu: [{
label: "Reload",
accelerator: "CmdOrCtrl+R",
click: function () {
BrowserWindow.getFocusedWindow().reload();
}
},{
label: "Toggle DevTools",
accelerator: "Alt+CmdOrCtrl+I",
click: function () {
BrowserWindow.getFocusedWindow().toggleDevTools();
}
},{
label: "Quit",
accelerator: "CmdOrCtrl+Q",
click: function () {
app.quit();
}
}]
}]);
Menu.setApplicationMenu(devMenu);
}; |
Add 'dicom' package to the requirements | import sys
# Make sure we are running python3.5+
if 10 * sys.version_info[0] + sys.version_info[1] < 35:
sys.exit("Sorry, only Python 3.5+ is supported.")
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(
name = 'med2image',
version = '1.1.1',
description = '(Python) utility to convert medical images to jpg and png',
long_description = readme(),
author = 'FNNDSC',
author_email = 'dev@babymri.org',
url = 'https://github.com/FNNDSC/med2image',
packages = ['med2image'],
install_requires = ['nibabel', 'dicom', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
#test_suite = 'nose.collector',
#tests_require = ['nose'],
scripts = ['bin/med2image'],
license = 'MIT',
zip_safe = False
)
| import sys
# Make sure we are running python3.5+
if 10 * sys.version_info[0] + sys.version_info[1] < 35:
sys.exit("Sorry, only Python 3.5+ is supported.")
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(
name = 'med2image',
version = '1.1.1',
description = '(Python) utility to convert medical images to jpg and png',
long_description = readme(),
author = 'FNNDSC',
author_email = 'dev@babymri.org',
url = 'https://github.com/FNNDSC/med2image',
packages = ['med2image'],
install_requires = ['nibabel', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
#test_suite = 'nose.collector',
#tests_require = ['nose'],
scripts = ['bin/med2image'],
license = 'MIT',
zip_safe = False
) |
Update variable names, add better comments, convert to JSON. | import re
import json
import hashlib
import requests
location = "http://www.ieee.org/netstorage/standards/oui.txt"
oui_id = re.compile(" *(\w{6}) *\(.*\)[^\w]+(.*)$")
request_hash = hashlib.sha1()
organizations = []
# Get the listing from the source location.
request = requests.get(location)
# Update our hash object with the value from our request string.
request_hash.update(bytes(request.text, "utf-8"))
# Ignore the first 127 characters of junk data.
request_string = request.text[127:]
# Break the request string into a list of entries.
entries = request_string.split('\r\n\r\n')
# Remove junk entry at the end.
del entries[-1]
# For each entry...
for entry in entries:
# Break the entry into lines.
lines = entry.split('\r\n')
# Find the id and oui for the organization.
matches = oui_id.search(lines[1])
# Find the address for the organization.
address = re.sub('\s+', ' ', ' '.join(lines[2:]).strip())
# Create a dictionary for the organization.
organization = {'id': matches.group(2),
'oui': matches.group(1),
'address': address}
# Append that dictionary to our list of organizations.
organizations.append(organization)
# Convert the list of organizations to a JSON formatted string.
json_organizations = json.dumps(organizations)
print(json_organizations)
| import re
import hashlib
import requests
location = "http://www.ieee.org/netstorage/standards/oui.txt"
number_name = re.compile(" *(\w{6}) *\(.*\)[^\w]+(.*)$")
oui_hash = hashlib.sha1()
companies = []
# Get the listing from the source location.
req = requests.get(location)
# Update our hash object with the value from our request string.
oui_hash.update(bytes(req.text, "utf-8"))
# Ignore the first 127 characters of junk data.
req_string = req.text[127:]
# Break the request string into a list of entries.
entries = req_string.split('\r\n\r\n')
# Remove junk entry at the end.
del entries[-1]
for entry in entries:
lines = entry.split('\r\n')
matches = number_name.search(lines[1])
company = {'name': matches.group(2), 'oui': matches.group(1)}
companies.append(company)
|
Add a function for notifying DataModels about ID changes | var datastore = require('../lib/environment').datastore,
util = require('util');
module.exports = DataModel;
function DataModel() {
}
DataModel.prototype.save = function () {
datastore.set(this.model, this.id, this);
};
DataModel.prototype.del = function () {
datastore.del(this.model, this.id);
};
DataModel.prototype.changeId = function (oldid) {
datastore.del(this.model, oldid);
datastore.set(this.model, this.id, this);
};
DataModel.findOne = function (Model, key, callback) {
datastore.get(Model.name, key, function (err, results) {
callback(err, results === null ? null : new Model(results));
});
};
DataModel.all = function (Model, callback) {
datastore.get(Model.name, '*', function (err, results) {
var map = {};
var list = [];
for (var idx in results) {
map[idx] = new Model(results[idx]);
}
if (typeof callback === 'function') {
callback(err, map);
}
});
};
module.exports.extend = function (Model) {
util.inherits(Model, DataModel);
for (var classmethod in DataModel) {
Model[classmethod] = DataModel[classmethod].bind(Model, Model);
}
};
| var datastore = require('../lib/environment').datastore,
util = require('util');
module.exports = DataModel;
function DataModel() {
}
DataModel.prototype.save = function () {
datastore.set(this.model, this.id, this);
};
DataModel.prototype.del = function () {
datastore.del(this.model, this.id);
};
DataModel.findOne = function (Model, key, callback) {
datastore.get(Model.name, key, function (err, results) {
callback(err, results === null ? null : new Model(results));
});
};
DataModel.all = function (Model, callback) {
datastore.get(Model.name, '*', function (err, results) {
var map = {};
var list = [];
for (var idx in results) {
map[idx] = new Model(results[idx]);
}
if (typeof callback === 'function') {
callback(err, map);
}
});
};
module.exports.extend = function (Model) {
util.inherits(Model, DataModel);
for (var classmethod in DataModel) {
Model[classmethod] = DataModel[classmethod].bind(Model, Model);
}
};
|
SF34: Remove assertion config (traverse is true by default) | <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\EventsDeferring;
use JMS\Serializer\Annotation as JMS;
use Smartbox\CoreBundle\Type\SerializableInterface;
use Smartbox\Integration\FrameworkBundle\Events\Event;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Message;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class EventMessage.
*/
class EventMessage extends Message
{
const HEADER_EVENT_NAME = 'event_name';
/**
* @Assert\Valid()
* @JMS\Type("Smartbox\Integration\FrameworkBundle\Events\Event")
* @JMS\Groups({"logs"})
* @JMS\Expose
*
* @var Event
*/
protected $body;
/**
* @return Event
*/
public function getBody()
{
return $this->body;
}
/**
* @param SerializableInterface $event
*/
public function setBody(SerializableInterface $event = null)
{
if (!$event instanceof Event) {
throw new \InvalidArgumentException('Expected Event as parameter');
}
if ($event->getEventName()) {
$this->addHeader(self::HEADER_EVENT_NAME, $event->getEventName());
}
$this->body = $event;
}
}
| <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\EventsDeferring;
use JMS\Serializer\Annotation as JMS;
use Smartbox\CoreBundle\Type\SerializableInterface;
use Smartbox\Integration\FrameworkBundle\Events\Event;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Message;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class EventMessage.
*/
class EventMessage extends Message
{
const HEADER_EVENT_NAME = 'event_name';
/**
* @Assert\Valid(traverse=true)
* @JMS\Type("Smartbox\Integration\FrameworkBundle\Events\Event")
* @JMS\Groups({"logs"})
* @JMS\Expose
*
* @var Event
*/
protected $body;
/**
* @return Event
*/
public function getBody()
{
return $this->body;
}
/**
* @param SerializableInterface $event
*/
public function setBody(SerializableInterface $event = null)
{
if (!$event instanceof Event) {
throw new \InvalidArgumentException('Expected Event as parameter');
}
if ($event->getEventName()) {
$this->addHeader(self::HEADER_EVENT_NAME, $event->getEventName());
}
$this->body = $event;
}
}
|
Add image with span wrapper and appendChild | (function(document){
function setStyle(style, param) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, param);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
function addImage(e) {
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
var newImage = document.createElement('span');
newImage.innerHTML = "<img src=" + event.target.result + " >";
e.target.appendChild(newImage);
};
reader.readAsDataURL(file);
}
var pad = document.getElementById('pad');
pad.addEventListener('drop', addImage, false);
})(document);
| (function(document){
function setStyle(style, param) {
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand(style, false, param);
document.designMode = "off";
}
}
Mousetrap.bind('mod+b', function(e) {
e.preventDefault();
setStyle("bold");
});
Mousetrap.bind('mod+i', function(e) {
e.preventDefault();
setStyle("italic");
});
Mousetrap.bind('mod+u', function(e) {
e.preventDefault();
setStyle("underline");
});
function addImage(e) {
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
e.target.innerHTML = "<img src=" + event.target.result + " >";
};
reader.readAsDataURL(file);
}
var pad = document.getElementById('pad');
pad.addEventListener('drop', addImage, false);
})(document);
|
Fix bug where it was impossible to plant seeds on crop sticks | package com.infinityraider.agricraft.plugins.minecraft;
import com.infinityraider.agricraft.api.v1.adapter.IAgriAdapter;
import com.infinityraider.agricraft.api.v1.crop.CropCapability;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenome;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenomeProvider;
import net.minecraft.tileentity.TileEntity;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;
public class GenomeWrapper implements IAgriAdapter<IAgriGenome> {
@Override
public boolean accepts(@Nullable Object obj) {
return obj instanceof IAgriGenomeProvider || obj instanceof TileEntity;
}
@Nonnull
@Override
public Optional<IAgriGenome> valueOf(@Nullable Object obj) {
if(obj instanceof IAgriGenomeProvider) {
return ((IAgriGenomeProvider) obj).getGenome();
}
if(obj instanceof TileEntity) {
TileEntity tile = (TileEntity) obj;
return tile.getCapability(CropCapability.getCapability())
.map(crop -> crop)
.flatMap(IAgriGenomeProvider::getGenome);
}
return Optional.empty();
}
}
| package com.infinityraider.agricraft.plugins.minecraft;
import com.infinityraider.agricraft.api.v1.adapter.IAgriAdapter;
import com.infinityraider.agricraft.api.v1.crop.CropCapability;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenome;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenomeProvider;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;
public class GenomeWrapper implements IAgriAdapter<IAgriGenome> {
@Override
public boolean accepts(@Nullable Object obj) {
return obj instanceof IAgriGenomeProvider || obj instanceof ICapabilityProvider;
}
@Nonnull
@Override
public Optional<IAgriGenome> valueOf(@Nullable Object obj) {
if(obj instanceof IAgriGenomeProvider) {
return ((IAgriGenomeProvider) obj).getGenome();
}
if(obj instanceof ICapabilityProvider) {
ICapabilityProvider capabilityProvider = (ICapabilityProvider) obj;
return capabilityProvider.getCapability(CropCapability.getCapability())
.map(crop -> crop)
.flatMap(IAgriGenomeProvider::getGenome);
}
return Optional.empty();
}
}
|
Test for deterministic results when testing BERT model | import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
results2 = trainer.test(test_features)
print('Evaluation results:', results2)
eval_acc1, eval_acc2 = results['eval_accuracy'], results2['eval_accuracy']
assertEqual(eval_acc1, eval_acc2)
if __name__ == '__main__':
unittest.main()
| import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
Allow finding theme with inconsistent directory separator.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\View\Theme;
class Finder {
/**
* Application instance.
*
* @var \Illuminate\Foundation\Application
*/
protected $app = null;
/**
* Construct a new finder.
*
* @param \Illuminate\Foundation\Application $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* Detect available themes.
*
* @return array
* @throws \RuntimeException
*/
public function detect()
{
$themes = array();
$file = $this->app['files'];
$path = rtrim($this->app['path.public'], '/').'/themes/';
$folders = $file->directories($path);
foreach ($folders as $folder)
{
$name = $this->parseThemeNameFromPath($folder);
$themes[$name] = new Manifest($file, rtrim($folder, '/').'/');
}
return $themes;
}
/**
* Get folder name from full path.
*
* @param string $path
* @return string
*/
protected function parseThemeNameFromPath($path)
{
$path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path);
$path = explode(DIRECTORY_SEPARATOR, $path);
return array_pop($path);
}
}
| <?php namespace Orchestra\View\Theme;
class Finder {
/**
* Application instance.
*
* @var \Illuminate\Foundation\Application
*/
protected $app = null;
/**
* Construct a new finder.
*
* @param \Illuminate\Foundation\Application $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* Detect available themes.
*
* @return array
* @throws \RuntimeException
*/
public function detect()
{
$themes = array();
$file = $this->app['files'];
$path = rtrim($this->app['path.public'], '/').'/themes/';
$folders = $file->directories($path);
foreach ($folders as $folder)
{
$name = $this->parseThemeNameFromPath($folder);
$themes[$name] = new Manifest($file, rtrim($folder, '/').'/');
}
return $themes;
}
/**
* Get folder name from full path.
*
* @param string $path
* @return string
*/
protected function parseThemeNameFromPath($path)
{
$path = str_replace('\\', DIRECTORY_SEPARATOR, $path);
$path = explode(DIRECTORY_SEPARATOR, $path);
return array_pop($path);
}
}
|
Simplify null check with optional() | <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;
class ChatController extends Controller
{
public function __construct()
{
$this->middleware('auth');
return parent::__construct();
}
public function index()
{
$json = [];
$targetUser = User::lookup(Request::input('sendto'), 'id');
if ($targetUser) {
$json['target'] = json_item($targetUser, 'UserCompact');
$json['can_message'] = priv_check('ChatStart', $targetUser)->can();
$channel = Channel::findPM($targetUser, Auth::user());
optional($channel)->addUser(Auth::user());
}
$presence = UserChannel::presenceForUser(Auth::user());
return ext_view('chat.index', compact('presence', 'json'));
}
}
| <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;
class ChatController extends Controller
{
public function __construct()
{
$this->middleware('auth');
return parent::__construct();
}
public function index()
{
$json = [];
$targetUser = User::lookup(Request::input('sendto'), 'id');
if ($targetUser) {
$json['target'] = json_item($targetUser, 'UserCompact');
$json['can_message'] = priv_check('ChatStart', $targetUser)->can();
$channel = Channel::findPM($targetUser, Auth::user());
if ($channel !== null) {
$channel->addUser(Auth::user());
}
}
$presence = UserChannel::presenceForUser(Auth::user());
return ext_view('chat.index', compact('presence', 'json'));
}
}
|
Use new comprehension syntax and six (nc-263) | import pkg_resources
from django.utils import six
from django.utils.lru_cache import lru_cache
@lru_cache()
def get_backup_strategies():
entry_points = pkg_resources.get_entry_map('nodeconductor').get('backup_strategies', {})
strategies = {name.upper(): entry_point.load() for name, entry_point in six.iteritems(entry_points)}
return strategies
def has_object_backup_strategy(obj):
strategies = get_backup_strategies()
return obj.__class__.__name__.upper() in strategies
def get_object_backup_strategy(obj):
strategies = get_backup_strategies()
return strategies[obj.__class__.__name__.upper()]
def get_backupable_models():
strategies = get_backup_strategies()
return [strategy.get_model() for strategy in six.itervalues(strategies)]
| import pkg_resources
from django.utils import six
from django.utils.lru_cache import lru_cache
@lru_cache()
def get_backup_strategies():
entry_points = pkg_resources.get_entry_map('nodeconductor').get('backup_strategies', {})
strategies = dict((name.upper(), entry_point.load()) for name, entry_point in entry_points.iteritems())
return strategies
def has_object_backup_strategy(obj):
strategies = get_backup_strategies()
return obj.__class__.__name__.upper() in strategies
def get_object_backup_strategy(obj):
strategies = get_backup_strategies()
return strategies[obj.__class__.__name__.upper()]
def get_backupable_models():
strategies = get_backup_strategies()
return [strategy.get_model() for strategy in six.itervalues(strategies)]
|
fix: Allow laneId to be passed as param to onCardClick handler
https://github.com/rcdexta/react-trello/issues/34 | import React from 'react'
import {withInfo} from '@storybook/addon-info'
import {storiesOf} from '@storybook/react'
import Board from '../src'
const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
cards: [
{id: 'Card1', title: 'Card1', description: 'foo card', metadata: {id: 'Card1'}},
{id: 'Card2', title: 'Card2', description: 'bar card', metadata: {id: 'Card2'}}
]
},
{
id: 'lane2',
title: 'Executing',
cards: [
{id: 'Card3', title: 'Card3', description: 'foobar card', metadata: {id: 'Card3'}}
]
}
]
}
storiesOf('React Trello', module).add(
'Event Handling',
withInfo('Adding event handlers to cards')(() =>
<Board
draggable={true}
data={data}
onCardClick={(cardId, metadata, laneId) => alert(`Card with id:${cardId} clicked. Has metadata.id: ${metadata.id}. Card in lane: ${laneId}`)}
onLaneClick={(laneId) => alert(`Lane with id:${laneId} clicked`)}
/>
)
)
| import React from 'react'
import {withInfo} from '@storybook/addon-info'
import {storiesOf} from '@storybook/react'
import Board from '../src'
const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
cards: [
{id: 'Card1', title: 'Card1', description: 'foo card', metadata: {id: 'Card1'}},
{id: 'Card2', title: 'Card2', description: 'bar card', metadata: {id: 'Card2'}}
]
},
{
id: 'lane2',
title: 'Executing',
cards: []
}
]
}
storiesOf('React Trello', module).add(
'Event Handling',
withInfo('Adding event handlers to cards')(() =>
<Board
draggable={true}
data={data}
onCardClick={(cardId, metadata, laneId) => alert(`Card with id:${cardId} clicked. Has metadata.id: ${metadata.id}. Card in lane: ${laneId}`)}
onLaneClick={(laneId) => alert(`Lane with id:${laneId} clicked`)}
/>
)
)
|
Add "scaled" class after scaling elements. | define([
"jquery",
"../registry"
], function($, registry) {
var _ = {
name: "autoscale",
trigger: ".pat-auto-scale",
transform: $('html').hasClass('csstransforms'),
init: function($el, options) {
return $el.each(_.resizeElement);
},
resizeElement: function() {
var $this = $(this),
scale;
if (this.tagName.toLowerCase()==='body')
scale = $(window).width()/$this.outerWidth();
else
scale = $this.parent().outerWidth()/$this.outerWidth();
if (_.transform)
$this.css('transform', 'scale(' + scale + ')');
else
$this.css('zoom', scale);
$this.addClass("scaled");
},
resizeEvent: function() {
$(_.trigger).each(_.resizeElement);
}
};
$(window).resize(_.resizeEvent);
registry.register(_);
return _;
});
| define([
"jquery",
"../registry"
], function($, registry) {
var _ = {
name: "autoscale",
trigger: ".pat-auto-scale",
transform: $('html').hasClass('csstransforms'),
init: function($el, options) {
return $el.each(_.resizeElement);
},
resizeElement: function() {
var $this = $(this),
scale;
if (this.tagName.toLowerCase()==='body')
scale = $(window).width()/$this.outerWidth();
else
scale = $this.parent().outerWidth()/$this.outerWidth();
if (_.transform)
$this.css('transform', 'scale(' + scale + ')');
else
$this.css('zoom', scale);
},
resizeEvent: function() {
$(_.trigger).each(_.resizeElement);
}
};
$(window).resize(_.resizeEvent);
registry.register(_);
return _;
});
|
Add test to ensure mongodb is running. | /* global require, describe, it */
'use strict';
var expect = require('chai').expect;
var request = require('request');
var url = function(path) {
return 'http://localhost:8000' + path;
};
describe("MongoDB", function() {
it("is there a server running", function(next) {
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/brainstormer', function(err, db) {
expect(err).to.equal(null);
next();
});
});
});
describe('GET /', function() {
it('responds', function(done){
request(url('/'), function(error, res) {
expect(res.statusCode).to.equal(200);
done();
});
});
});
describe('GET /index.html', function() {
it('responds', function(done){
request(url('/indexs.html'), function(error, res) {
expect(res.headers['content-type'].indexOf('html')).to.not.equal(-1);
done();
});
});
});
describe('GET /no-such-file.html', function() {
it('responds', function(done){
request(url('/no-such-file.html'), function(error, res) {
expect(res.statusCode).to.equal(404);
done();
});
});
});
| /* global require, describe, it */
'use strict';
var expect = require('chai').expect;
var request = require('request');
var url = function(path) {
return 'http://localhost:8000' + path;
};
describe('GET /', function() {
it('responds', function(done){
request(url('/'), function(error, res) {
expect(res.statusCode).to.equal(200);
done();
});
});
});
describe('GET /index.html', function() {
it('responds', function(done){
request(url('/indexs.html'), function(error, res) {
expect(res.headers['content-type'].indexOf('html')).to.not.equal(-1);
done();
});
});
});
describe('GET /no-such-file.html', function() {
it('responds', function(done){
request(url('/no-such-file.html'), function(error, res) {
expect(res.statusCode).to.equal(404);
done();
});
});
});
|
Increment version for mock test fix | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
| import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.0',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Test for compatibility of primary key AutoField | """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class CompatibilityTest(TestCase):
def test_capitalized_id(self):
test_lead = Lead(Company='sf_test lead', LastName='name')
test_lead.save()
try:
refreshed_lead = Lead.objects.get(Id=test_lead.Id)
self.assertEqual(refreshed_lead.Id, test_lead.Id)
self.assertEqual(refreshed_lead.Owner.Username, current_user)
leads = Lead.objects.filter(Company='sf_test lead', LastName='name')
self.assertEqual(len(leads), 1)
repr(test_lead.__dict__)
finally:
test_lead.delete()
class DjangoCompatibility(TestCase):
def test_autofield_compatible(self):
"""Test that the light weigh AutoField is compatible in all Django ver."""
primary_key = [x for x in Lead._meta.fields if x.primary_key][0]
self.assertEqual(primary_key.auto_created, True)
self.assertEqual(primary_key.get_internal_type(), 'AutoField')
self.assertIn(primary_key.name, ('id', 'Id'))
| """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class CompatibilityTest(TestCase):
def test_capitalized_id(self):
test_lead = Lead(Company='sf_test lead', LastName='name')
test_lead.save()
try:
refreshed_lead = Lead.objects.get(Id=test_lead.Id)
self.assertEqual(refreshed_lead.Id, test_lead.Id)
self.assertEqual(refreshed_lead.Owner.Username, current_user)
leads = Lead.objects.filter(Company='sf_test lead', LastName='name')
self.assertEqual(len(leads), 1)
repr(test_lead.__dict__)
finally:
test_lead.delete()
|
Make GET to /renderedConfigs/{serviceId} at the Agent level not require authentication | package com.hubspot.baragon.agent.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.hubspot.baragon.agent.managers.AgentRequestManager;
import com.hubspot.baragon.auth.NoAuth;
@Path("/renderedConfigs")
@Produces(MediaType.APPLICATION_JSON)
public class RenderedConfigsResource {
private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class);
private final AgentRequestManager agentRequestManager;
@Inject
public RenderedConfigsResource(
AgentRequestManager agentRequestManager) {
this.agentRequestManager = agentRequestManager;
}
@GET
@NoAuth
@Path("/{serviceId}")
public Response getServiceId(@PathParam("serviceId") String serviceId) {
LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId);
return agentRequestManager.getRenderedConfigs(serviceId);
}
}
| package com.hubspot.baragon.agent.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.hubspot.baragon.agent.managers.AgentRequestManager;
@Path("/renderedConfigs")
@Produces(MediaType.APPLICATION_JSON)
public class RenderedConfigsResource {
private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class);
private final AgentRequestManager agentRequestManager;
@Inject
public RenderedConfigsResource(
AgentRequestManager agentRequestManager) {
this.agentRequestManager = agentRequestManager;
}
@GET
@Path("/{serviceId}")
public Response getServiceId(@PathParam("serviceId") String serviceId) {
LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId);
return agentRequestManager.getRenderedConfigs(serviceId);
}
}
|
Update example dbus client to account for Format interface. |
import dbus
bus = dbus.SystemBus()
# This adds a signal match so that the client gets signals sent by Blivet1's
# ObjectManager. These signals are used to notify clients of changes to the
# managed objects (for blivet, this will be devices, formats, and actions).
bus.add_match_string("type='signal',sender='com.redhat.Blivet1',path_namespace='/com/redhat/Blivet1'")
blivet = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1/Blivet')
blivet.Reset()
object_manager = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1')
objects = object_manager.GetManagedObjects()
for object_path in blivet.ListDevices():
device = objects[object_path]['com.redhat.Blivet1.Device']
fmt = objects[device['Format']]['com.redhat.Blivet1.Format']
print(device['Name'], device['Type'], device['Size'], fmt['Type'])
|
import dbus
bus = dbus.SystemBus()
# This adds a signal match so that the client gets signals sent by Blivet1's
# ObjectManager. These signals are used to notify clients of changes to the
# managed objects (for blivet, this will be devices, formats, and actions).
bus.add_match_string("type='signal',sender='com.redhat.Blivet1',path_namespace='/com/redhat/Blivet1'")
blivet = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1/Blivet')
blivet.Reset()
object_manager = bus.get_object('com.redhat.Blivet1', '/com/redhat/Blivet1')
objects = object_manager.GetManagedObjects()
for object_path in blivet.ListDevices():
device = objects[object_path]['com.redhat.Blivet1.Device']
print(device['Name'], device['Type'], device['Size'], device['FormatType'])
|
Fix indexerr caused by debug page in non-debug mode | /* jshint devel: true */
'use strict';
xss.debug.NS = 'DEBUG';
// Debug URL: debug.html?debug=level:0
xss.debug.debugLevelMatch = location.search.match(/debug=level:([0-9]+)$/);
if (xss.debug.debugLevelMatch) {
document.addEventListener('DOMContentLoaded', function() {
window.setTimeout(function() {
xss.levels.onload = xss.debug.level;
}, 0);
});
}
xss.debug.level = function() {
var game;
xss.socket = {emit: xss.util.noop};
xss.menuSnake.destruct();
game = new xss.Game(0, xss.debug.debugLevelMatch, ['']);
game.start();
console.info(game.level.levelData);
xss.event.on(xss.PUB_GAME_TICK, xss.debug.NS, function() {
if (game.snakes[0].limbo) {
console.log(game.snakes[0]);
game.snakes[0].crash();
xss.event.off(xss.PUB_GAME_TICK, xss.debug.NS);
}
});
};
| /* jshint devel: true */
'use strict';
xss.debug.NS = 'DEBUG';
// Debug URL: debug.html?debug=level:0
xss.debug.levelIndex = location.search.match(/debug=level:([0-9]+)$/)[1];
if (xss.debug.levelIndex) {
document.addEventListener('DOMContentLoaded', function() {
window.setTimeout(function() {
xss.levels.onload = xss.debug.level;
}, 0);
});
}
xss.debug.level = function() {
var game;
xss.socket = {emit: xss.util.noop};
xss.menuSnake.destruct();
game = new xss.Game(0, xss.debug.levelIndex, ['']);
game.start();
console.info(game.level.levelData);
xss.event.on(xss.PUB_GAME_TICK, xss.debug.NS, function() {
if (game.snakes[0].limbo) {
console.log(game.snakes[0]);
game.snakes[0].crash();
xss.event.off(xss.PUB_GAME_TICK, xss.debug.NS);
}
});
};
|
Fix CSS loaders for ssr | var webpack = require('webpack');
module.exports = {
entry: './entry',
externals: {
// Add global variables you would like to import
'react': 'React',
'react-router': 'ReactRouter',
'react-router-ssr': 'ReactRouterSSR',
'react-meteor-data': 'ReactMeteorData',
'blaze-to-react': 'BlazeToReact'
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.css', '.scss']
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', query: { stage: 0 }, exclude: /node_modules/ },
{ test: /\.css$/, loader: 'style-collector!css' },
{ test: /\.scss$/, loader: 'style-collector!css!sass' },
{ test: /\.(png|jpe?g)(\?.*)?$/, loader: 'url?limit=8182' },
{ test: /\.(svg|ttf|woff|eot)(\?.*)?$/, loader: 'file' }
]
}
};
| var webpack = require('webpack');
module.exports = {
entry: './entry',
externals: {
// Add global variables you would like to import
'react': 'React',
'react-router': 'ReactRouter',
'react-router-ssr': 'ReactRouterSSR',
'react-meteor-data': 'ReactMeteorData',
'blaze-to-react': 'BlazeToReact'
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.css', '.scss']
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', query: { stage: 0 }, exclude: /node_modules/ },
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.scss$/, loader: 'style!css!sass' },
{ test: /\.(png|jpe?g)(\?.*)?$/, loader: 'url?limit=8182' },
{ test: /\.(svg|ttf|woff|eot)(\?.*)?$/, loader: 'file' }
]
}
};
|
Update docblock & add explanatory comment. | <?php
namespace Aurora\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class CheckRole
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// e.g. $this->middleware('role:admin,intern') => ['admin', 'intern']
$roles = array_slice(func_get_args(), 2);
// If user is a guest (e.g. no role), or is missing the provided role... get out!
if ($this->auth->guest() || ! $this->auth->user()->hasRole($roles)) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return view('auth.unauthorized');
}
}
return $next($request);
}
}
| <?php
namespace Aurora\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class CheckRole
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param $roles
* @return mixed
*/
public function handle($request, Closure $next)
{
$roles = array_slice(func_get_args(), 2);
// If user is a guest (e.g. no role), or is missing the provided role... get out!
if ($this->auth->guest() || ! $this->auth->user()->hasRole($roles)) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return view('auth.unauthorized');
}
}
return $next($request);
}
}
|
Change the third item of the search_field from 'mac' to 'mac1' | from django.contrib import admin
from django.db import models
from Machine import models as mmod
class ContactInLine(admin.TabularInline):
model = mmod.Contact
max_num = 2
class StatusAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
fieldsets = (
(None, {'fields': ('name', 'description')}),
)
class ItemAdmin(admin.ModelAdmin):
list_display = ('name', 'type','location','ip','mac1','mac2',
'wall_port','date_added','manu_tag','uw_tag')
search_fields = ['name','ip','mac1','wall_port']
list_filter = ['type','date_added']
class GroupAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('name', 'is_lab', 'casting_server', 'gateway',
'items', 'description')}),
)
list_display = ('name','is_lab','casting_server','gateway')
inlines = [
ContactInLine,
]
admin.site.register(mmod.Item, ItemAdmin)
admin.site.register(mmod.Group, GroupAdmin)
admin.site.register(mmod.Platform)
admin.site.register(mmod.Type)
admin.site.register(mmod.Location)
admin.site.register(mmod.Status)
# history here for development, remove for production
admin.site.register(mmod.History)
| from django.contrib import admin
from django.db import models
from Machine import models as mmod
class ContactInLine(admin.TabularInline):
model = mmod.Contact
max_num = 2
class StatusAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
fieldsets = (
(None, {'fields': ('name', 'description')}),
)
class ItemAdmin(admin.ModelAdmin):
list_display = ('name', 'type','location','ip','mac1','mac2',
'wall_port','date_added','manu_tag','uw_tag')
search_fields = ['name','ip','mac','wall_port']
list_filter = ['type','date_added']
class GroupAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('name', 'is_lab', 'casting_server', 'gateway',
'items', 'description')}),
)
list_display = ('name','is_lab','casting_server','gateway')
inlines = [
ContactInLine,
]
admin.site.register(mmod.Item, ItemAdmin)
admin.site.register(mmod.Group, GroupAdmin)
admin.site.register(mmod.Platform)
admin.site.register(mmod.Type)
admin.site.register(mmod.Location)
admin.site.register(mmod.Status)
# history here for development, remove for production
admin.site.register(mmod.History)
|
Remove the intentional throwing of internal server errors.
Fixes failing tests. | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspection PyMethodMayBeStatic
def index(self) -> str:
"""
Display a simple greeting.
:return: The home page with a message to all visitors.
"""
return flask.render_template('index.html')
# noinspection PyMethodMayBeStatic
def get(self, name: str) -> str:
"""
Display a simple personalized greeting.
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
return flask.render_template('index.html', name = name)
IndexView.register(views)
| # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspection PyMethodMayBeStatic
def index(self) -> str:
"""
Display a simple greeting.
:return: The home page with a message to all visitors.
"""
return flask.render_template('index.html')
# noinspection PyMethodMayBeStatic
def get(self, name: str) -> str:
"""
Display a simple personalized greeting.
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
if name == 'BMeu':
flask.abort(500)
elif name == 'BMeu2':
raise ValueError
return flask.render_template('index.html', name = name)
IndexView.register(views)
|
Fix NameError on Python 2.6 | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
'scrapy>0.9',
'argparse',
'mock',
'PyYAML',
'autoresponse>=0.2',
],
)
### Python 2.7 already has importlib. Because of that,
### we can't put it in install_requires. We test for
### that here; if needed, we add it.
try:
import importlib
except ImportError:
setup_params['install_requires'].append('importlib')
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
| #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
'scrapy>0.9',
'argparse',
'mock',
'PyYAML',
'autoresponse>=0.2',
],
)
### Python 2.7 already has importlib. Because of that,
### we can't put it in install_requires. We test for
### that here; if needed, we add it.
try:
import importlib
except ImportError:
install_requires.append('importlib')
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
|
Load up database functions into clize | from . import utils
# TODO: Override with port=NNNN if specified by environment
from . import database # Let the database functions register themselves
# Note that these functions lazily import their corresponding modules,
# otherwise package startup would take three parts of forever.
@utils.cmdline
def renderer(*, gain:"g"=0.0):
"""Invoke the infinite renderer
gain: dB gain (positive or negative) for volume adjustment
"""
from . import renderer
renderer.run(gain=gain) # doesn't return
@utils.cmdline
def major_glitch(*, dev=False):
"""Rebuild the Major Glitch"""
utils.enable_timer()
from . import renderer
renderer.major_glitch(profile=dev)
@utils.cmdline
def audition(id1, id2, fn):
"""Audition a transition
id1: ID of earlier track (will render last 10s)
id2: ID of later track (will render first 10s)
fn: File name to save into
"""
from . import renderer
renderer.audition(id1, id2, fn)
@utils.cmdline
def main(*, dev=False):
"""Start the main server (debug mode - production uses gunicorn)"""
from . import server
server.run(disable_logins=dev) # doesn't return
utils.main()
| from . import utils
# TODO: Override with port=NNNN if specified by environment
# Note that these functions lazily import their corresponding modules,
# otherwise package startup would take three parts of forever.
@utils.cmdline
def renderer(*, gain:"g"=0.0):
"""Invoke the infinite renderer
gain: dB gain (positive or negative) for volume adjustment
"""
from . import renderer
renderer.run(gain=gain) # doesn't return
@utils.cmdline
def major_glitch(*, dev=False):
"""Rebuild the Major Glitch"""
utils.enable_timer()
from . import renderer
renderer.major_glitch(profile=dev)
@utils.cmdline
def audition(id1, id2, fn):
"""Audition a transition
id1: ID of earlier track (will render last 10s)
id2: ID of later track (will render first 10s)
fn: File name to save into
"""
from . import renderer
renderer.audition(id1, id2, fn)
@utils.cmdline
def main(*, dev=False):
"""Start the main server (debug mode - production uses gunicorn)"""
from . import server
server.run(disable_logins=dev) # doesn't return
utils.main()
|
Add documentation to the getLocale method. | <?php namespace Vinkla\Translator;
use Vinkla\Translator\Exceptions\TranslatorException;
use Config, Session;
trait TranslatorTrait {
/**
* The default localization key.
*
* @var string
*/
private $defaultLocaleKey = 'locale_id';
/**
* Translator instance.
*
* @var mixed
*/
protected $translatorInstance;
/**
* Prepare a translator instance and fetch translations.
*
* @throws TranslatorException
* @return mixed
*/
public function translate()
{
if (!$this->translator || !class_exists($this->translator))
{
throw new TranslatorException('Please set the $translator property to your translation model path.');
}
if (!$this->translatorInstance)
{
$this->translatorInstance = new $this->translator();
}
return $this->translatorInstance
->where($this->getForeignKey(), $this->id)
->where($this->getLocaleKey(), $this->getLocale())
->first();
}
/**
* Fetch the default localisation key comparison.
* If you not want to fetch the localization id from
* a session, this could be overwritten in the modal.
*
* @return mixed
*/
public function getLocale()
{
return Session::get($this->getLocaleKey());
}
/**
* Fetch the localisation key.
*
* @return string
*/
private function getLocaleKey()
{
return $this->localeKey ? $this->localeKey : $this->defaultLocaleKey;
}
}
| <?php namespace Vinkla\Translator;
use Vinkla\Translator\Exceptions\TranslatorException;
use Config, Session;
trait TranslatorTrait {
/**
* The default localization key.
*
* @var string
*/
private $defaultLocaleKey = 'locale_id';
/**
* Translator instance.
*
* @var mixed
*/
protected $translatorInstance;
/**
* Prepare a translator instance and fetch translations.
*
* @throws TranslatorException
* @return mixed
*/
public function translate()
{
if (!$this->translator || !class_exists($this->translator))
{
throw new TranslatorException('Please set the $translator property to your translation model path.');
}
if (!$this->translatorInstance)
{
$this->translatorInstance = new $this->translator();
}
return $this->translatorInstance
->where($this->getForeignKey(), $this->id)
->where($this->getLocaleKey(), $this->getLocale())
->first();
}
/**
* Fetch the default localisation key comparison.
*
* @return mixed
*/
public function getLocale()
{
return Session::get($this->getLocaleKey());
}
/**
* Fetch the localisation key.
*
* @return string
*/
private function getLocaleKey()
{
return $this->localeKey ? $this->localeKey : $this->defaultLocaleKey;
}
}
|
Fix quotes in test description for linting | import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
const { run } = Ember;
let application;
function getCssProperty(element, property) {
let elem = document.getElementById(element);
return window.getComputedStyle(elem, null).getPropertyValue(property);
}
module('Acceptance: Application (Chrome Only)', {
beforeEach() {
application = startApp();
},
afterEach() {
run(application, 'destroy');
}
});
/**
Execute this test in Chrome or PhantomJS for correct results
*/
test('Verify postcss has run', (assert) => {
assert.expect(4);
visit('/');
andThen(function() {
assert.equal(currentPath(), 'index', 'On the index page');
assert.equal(find('#title').length, 1, 'Page contains a header title');
assert.equal(getCssProperty('title', 'color'), 'rgb(0, 0, 0)', 'postcss-color-gray has run');
assert.equal(getCssProperty('paragraph', 'color'), 'rgb(102, 51, 153)', 'postcss-rebeccapurple has run');
});
});
test('Verify additional files can be compiled', (assert) => {
assert.expect(2);
visit('/');
andThen(function() {
assert.equal(currentPath(), 'index', 'On the index page');
assert.equal(getCssProperty('paragraph', 'margin-bottom'), '16px', 'secondary.css has been processed');
});
});
| import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
const { run } = Ember;
let application;
function getCssProperty(element, property) {
let elem = document.getElementById(element);
return window.getComputedStyle(elem, null).getPropertyValue(property);
}
module('Acceptance: Application (Chrome Only)', {
beforeEach() {
application = startApp();
},
afterEach() {
run(application, 'destroy');
}
});
/**
Execute this test in Chrome or PhantomJS for correct results
*/
test('Verify postcss has run', (assert) => {
assert.expect(4);
visit('/');
andThen(function() {
assert.equal(currentPath(), 'index', 'On the index page');
assert.equal(find('#title').length, 1, 'Page contains a header title');
assert.equal(getCssProperty('title', 'color'), 'rgb(0, 0, 0)', 'postcss-color-gray has run');
assert.equal(getCssProperty('paragraph', 'color'), 'rgb(102, 51, 153)', 'postcss-rebeccapurple has run');
});
});
test('Verify additional files can be compiled', (assert) => {
assert.expect(2);
visit('/');
andThen(function() {
assert.equal(currentPath(), 'index', "On the index page");
assert.equal(getCssProperty('paragraph', 'margin-bottom'), '16px', 'secondary.css has been processed');
});
});
|
Raise ValueError instead of struct.error
The protocol for field encoding and decoding is to raise ValueError, so this is a necessary translation. | import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # long long
}
def __init__(self, *args, endianness='<', **kwargs):
super(Integer, self).__init__(*args, **kwargs)
self.format_code = endianness + self.size_formats[self.size]
def encode(self, value):
try:
return struct.pack(self.format_code, value)
except struct.error as e:
raise ValueError(*e.args)
def decode(self, value):
# The index on the end is because unpack always returns a tuple
try:
return struct.unpack(self.format_code, value)[0]
except struct.error as e:
raise ValueError(*e.args)
| import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # long long
}
def __init__(self, *args, endianness='<', **kwargs):
super(Integer, self).__init__(*args, **kwargs)
self.format_code = endianness + self.size_formats[self.size]
def encode(self, value):
return struct.pack(self.format_code, value)
def decode(self, value):
# The index on the end is because unpack always returns a tuple
return struct.unpack(self.format_code, value)[0]
|
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@2022 d6536bca-fef9-0310-8506-e4c0a848fbcf |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
config.add_subpackage('cluster')
config.add_subpackage('fftpack')
config.add_subpackage('integrate')
config.add_subpackage('interpolate')
config.add_subpackage('io')
config.add_subpackage('lib')
config.add_subpackage('linalg')
config.add_subpackage('linsolve')
config.add_subpackage('maxentropy')
config.add_subpackage('misc')
#config.add_subpackage('montecarlo')
config.add_subpackage('optimize')
config.add_subpackage('sandbox')
config.add_subpackage('signal')
config.add_subpackage('sparse')
config.add_subpackage('special')
config.add_subpackage('stats')
config.add_subpackage('ndimage')
config.add_subpackage('weave')
config.make_svn_version_py() # installs __svn_version__.py
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
#config.add_subpackage('cluster')
#config.add_subpackage('fftpack')
#config.add_subpackage('integrate')
#config.add_subpackage('interpolate')
#config.add_subpackage('io')
config.add_subpackage('lib')
config.add_subpackage('linalg')
#config.add_subpackage('linsolve')
#config.add_subpackage('maxentropy')
config.add_subpackage('misc')
#config.add_subpackage('montecarlo')
config.add_subpackage('optimize')
#config.add_subpackage('sandbox')
#config.add_subpackage('signal')
#config.add_subpackage('sparse')
config.add_subpackage('special')
config.add_subpackage('stats')
#config.add_subpackage('ndimage')
#config.add_subpackage('weave')
config.make_svn_version_py() # installs __svn_version__.py
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Include accordion.js in list of JavaScript files for testing. | var gulp = require( 'gulp' ),
bower = require( 'gulp-bower' ),
del = require( 'del' ),
vui = require( 'vui-helpers' );
gulp.task( 'clean', function( cb ) {
del([ 'accordion.css' ], cb);
} );
gulp.task( 'lib', function() {
return bower( 'lib/' );
} );
gulp.task( 'css', function () {
return vui.makeCss(
'accordion.css.less',
'accordion.css',
{ 'lintOpts' : '.csslintrc' }
);
} );
gulp.task( 'default', [ 'clean' ], function() {
gulp.start( 'css' );
} );
gulp.task( 'test', [ 'lib' ], function () {
return vui.test(
'test/unit/karma.conf.js',
[
'lib/jquery/jquery.min.js',
'lib/jquery.ui/ui/jquery.ui.core.js',
'lib//jquery.ui/ui/jquery.ui.widget.js',
'accordion.js',
'test/unit/**/*Spec.js'
],
'accordion.css'
);
} ); | var gulp = require( 'gulp' ),
bower = require( 'gulp-bower' ),
del = require( 'del' ),
vui = require( 'vui-helpers' );
gulp.task( 'clean', function( cb ) {
del([ 'accordion.css' ], cb);
} );
gulp.task( 'lib', function() {
return bower( 'lib/' );
} );
gulp.task( 'css', function () {
return vui.makeCss(
'accordion.css.less',
'accordion.css',
{ 'lintOpts' : '.csslintrc' }
);
} );
gulp.task( 'default', [ 'clean' ], function() {
gulp.start( 'css' );
} );
gulp.task( 'test', [ 'lib' ], function () {
return vui.test(
'test/unit/karma.conf.js',
[
'lib/jquery/jquery.min.js',
'lib/jquery.ui/ui/jquery.ui.core.js',
'lib//jquery.ui/ui/jquery.ui.widget.js',
'test/unit/**/*Spec.js'
],
'accordion.css'
);
} ); |
Insert custom commands through the getCommands() function. | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Modules
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Modules Toolbar Class
*
* @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
* @category Nooku
* @package Nooku_Server
* @subpackage Modules
*/
class ComModulesControllerToolbarModules extends ComDefaultControllerToolbarDefault
{
public function getCommands()
{
$this->addSeperator()
->addEenable()
->addDisable();
return parent::getCommands();
}
protected function _commandNew(KControllerToolbarCommand $command)
{
$command->append(array(
'attribs' => array(
'class' => array('modal'),
'rel' => '{handler: \'url\', ajaxOptions:{method:\'get\'}}',
'href' => 'index.php?option=com_modules&view=modules&layout=list&installed=1&tmpl=component'
)
));
}
} | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Modules
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Modules Toolbar Class
*
* @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
* @category Nooku
* @package Nooku_Server
* @subpackage Modules
*/
class ComModulesControllerToolbarModules extends ComDefaultControllerToolbarDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->addSeperator()
->addEenable()
->addDisable();
}
protected function _commandNew(KControllerToolbarCommand $command)
{
$command->append(array(
'attribs' => array(
'class' => array('modal'),
'rel' => '{handler: \'url\', ajaxOptions:{method:\'get\'}}',
'href' => 'index.php?option=com_modules&view=modules&layout=list&installed=1&tmpl=component'
)
));
}
} |
Remove unused import. Parameter checking. | package path
import (
"github.com/aybabtme/graph"
)
type PathFinder interface {
HasPathTo(to int) bool
PathTo(to int) []int
}
type TremauxDFS struct {
g graph.Graph
from int
marked []bool
edgeTo []int
}
func BuildTremauxDFS(g graph.Graph, from int) PathFinder {
if from < 0 {
panic("Can't start DFS from vertex v < 0")
}
if from >= g.V() {
panic("Can't start DFS from vertex v >= total vertex count")
}
t := TremauxDFS{
g: g,
from: from,
marked: make([]bool, g.V()),
edgeTo: make([]int, g.V()),
}
var visit func(v int)
steps := 0
visit = func(v int) {
t.marked[v] = true
for _, adj := range g.Adj(v) {
steps++
if !t.marked[adj] {
t.edgeTo[adj] = v
visit(adj)
}
}
}
visit(from)
return t
}
func (t TremauxDFS) HasPathTo(to int) bool {
return t.marked[to]
}
func (t TremauxDFS) PathTo(to int) []int {
return []int{}
}
| package path
import (
"fmt"
"github.com/aybabtme/graph"
)
type PathFinder interface {
HasPathTo(to int) bool
PathTo(to int) []int
}
type TremauxDFS struct {
g graph.Graph
from int
marked []bool
edgeTo []int
}
func BuildTremauxDFS(g graph.Graph, from int) PathFinder {
t := TremauxDFS{
g: g,
from: from,
marked: make([]bool, g.V()),
edgeTo: make([]int, g.V()),
}
var visit func(v int)
steps := 0
visit = func(v int) {
t.marked[v] = true
for _, adj := range g.Adj(v) {
steps++
if !t.marked[adj] {
t.edgeTo[adj] = v
visit(adj)
}
}
}
visit(from)
return t
}
func (t TremauxDFS) HasPathTo(to int) bool {
return t.marked[to]
}
func (t TremauxDFS) PathTo(to int) []int {
return []int{}
}
|
Add newline to end of file
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com> | from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.formatters import HtmlFormatter
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django_git.utils import *
def index(request, template_name='django_git/index.html'):
return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request))
def repo(request, repo, template_name='django_git/repo.html'):
return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request))
def commit(request, repo, commit, template_name='django_git/commit.html'):
print repo, commit
return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request))
def blob(request, repo, commit):
file = request.GET.get('file', '')
blob = get_blob(repo, commit, file)
lexer = guess_lexer_for_filename(blob.basename, blob.data)
return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline')))
| from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.formatters import HtmlFormatter
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django_git.utils import *
def index(request, template_name='django_git/index.html'):
return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request))
def repo(request, repo, template_name='django_git/repo.html'):
return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request))
def commit(request, repo, commit, template_name='django_git/commit.html'):
return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request))
def blob(request, repo, commit):
file = request.GET.get('file', '')
blob = get_blob(repo, commit, file)
lexer = guess_lexer_for_filename(blob.basename, blob.data)
return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline'))) |
Check the presence of focus on the window reference | import Ember from 'ember';
import layout from '../templates/components/share-button';
export default Ember.Component.extend({
layout: layout,
tagName: 'button',
title: '',
text: '',
image: '',
classNameBindings: ['adaptive:adaptive-button'],
adaptive: true,
getCurrentUrl() {
return this.get('url') ? this.get('url') : document.location.href;
},
getPopupPosition() {
const dualScreenLeft = screen.availLeft;
const dualScreenTop = screen.availTop;
const windowWidth = screen.availWidth;
const windowheight = screen.availHeight;
const left = ((windowWidth / 2) - (600 / 2)) + dualScreenLeft;
const top = ((windowheight / 2) - (600 / 2)) + dualScreenTop;
return {left: left, top: top};
},
openSharePopup(url) {
let popupPosition = this.getPopupPosition();
var newWindow = window.open(url, 'Facebook',
'location=no,toolbar=no,menubar=no,scrollbars=no,status=no, width=600, height=600, top=' + popupPosition.top + ', left=' + popupPosition.left);
if (newWindow.focus) {
newWindow.focus();
}
}
});
| import Ember from 'ember';
import layout from '../templates/components/share-button';
export default Ember.Component.extend({
layout: layout,
tagName: 'button',
title: '',
text: '',
image: '',
classNameBindings: ['adaptive:adaptive-button'],
adaptive: true,
getCurrentUrl() {
return this.get('url') ? this.get('url') : document.location.href;
},
getPopupPosition() {
const dualScreenLeft = screen.availLeft;
const dualScreenTop = screen.availTop;
const windowWidth = screen.availWidth;
const windowheight = screen.availHeight;
const left = ((windowWidth / 2) - (600 / 2)) + dualScreenLeft;
const top = ((windowheight / 2) - (600 / 2)) + dualScreenTop;
return {left: left, top: top};
},
openSharePopup(url) {
let popupPosition = this.getPopupPosition();
var newWindow = window.open(url, 'Facebook',
'location=no,toolbar=no,menubar=no,scrollbars=no,status=no, width=600, height=600, top=' + popupPosition.top + ', left=' + popupPosition.left);
if (window.focus) {
newWindow.focus();
}
}
});
|
Update py2app script for Qt 5.11 | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
| """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
Add HTTP method and URL to error object in case of invalid status code | 'use strict';
var http = require('http');
var util = require('util');
var PassThrough = require('stream').PassThrough;
// A PassThrough stream that takes a list of valid status codes. The
// supplied status codes will act as a whilelist of allowed HTTP
// response codes. If a HTTP reponse is received which doens't conform
// to the whilelist, an error event is emitted.
var Status = function () {
var self = this;
PassThrough.call(this);
if (arguments.length > 0)
var codes = Array.prototype.slice.call(arguments);
// Listen for the special `response` event emitted by the flowHttp
// module
this.once('response', function (res) {
// Forward the `response` event down the pipe-line
self._forwardFlowHttpResponse(res);
var code = res.statusCode;
if (codes && codes.indexOf(code) === -1) {
var err = new Error('Unexpected response: ' + code + ' ' + http.STATUS_CODES[code]);
err.method = self._src.req.method;
err.url = self._src.req.url;
self.emit('error', err);
}
});
// Record the source of the pipe to be used above
this.once('pipe', function (src) {
self._src = src;
});
};
util.inherits(Status, PassThrough);
module.exports = Status;
| 'use strict';
var http = require('http');
var util = require('util');
var PassThrough = require('stream').PassThrough;
// A PassThrough stream that takes a list of valid status codes. The
// supplied status codes will act as a whilelist of allowed HTTP
// response codes. If a HTTP reponse is received which doens't conform
// to the whilelist, an error event is emitted.
var Status = function () {
var self = this;
PassThrough.call(this);
if (arguments.length > 0)
var codes = Array.prototype.slice.call(arguments);
// Listen for the special `response` event emitted by the flowHttp
// module
this.once('response', function (res) {
// Forward the `response` event down the pipe-line
self._forwardFlowHttpResponse(res);
var code = res.statusCode;
if (codes && codes.indexOf(code) === -1) {
var err = new Error('Unexpected response: ' + code + ' ' + http.STATUS_CODES[code]);
self.emit('error', err);
}
});
// Record the source of the pipe to be used above
this.once('pipe', function (src) {
self._src = src;
});
};
util.inherits(Status, PassThrough);
module.exports = Status;
|
Fix undeinfed function in obj visit | (function () {
$.misc = {
uuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
})();
$.extend(Object.prototype, {
visit: function (func) {
for (var prop in this) {
func.apply(this, [prop, this[prop]]);
if ($.type(this[prop]) === "thisect") {
visit(this[prop], func);
}
else if ($.type(this[prop]) === "array") {
var array = this[prop];
$.each(array, function (i, item) {
visit(item, func);
})
}
}
}
}); | (function () {
$.misc = {
uuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
})();
$.extend(Object.prototype, {
visit: function (obj, func) {
for (var prop in obj) {
func.apply(this, [prop, obj[prop]]);
if ($.type(obj[prop]) === "object") {
visit(obj[prop], func);
}
else if ($.type(obj[prop]) === "array") {
var array = obj[prop];
$.each(array, function (i, item) {
visit(item, func);
})
}
}
}
}); |
Add adsID to settings slugs and sort. | /**
* `modules/analytics` base data store
*
* Site Kit by Google, Copyright 2021 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
import { submitChanges, validateCanSubmitChanges } from './settings';
const baseModuleStore = Modules.createModuleStore( 'analytics', {
storeName: STORE_NAME,
settingSlugs: [
'accountID',
'adsID',
'anonymizeIP',
'canUseSnippet',
'internalWebPropertyID',
'ownerID',
'profileID',
'propertyID',
'trackingDisabled',
'useSnippet',
],
adminPage: 'googlesitekit-module-analytics',
submitChanges,
validateCanSubmitChanges,
} );
export default baseModuleStore;
| /**
* `modules/analytics` base data store
*
* Site Kit by Google, Copyright 2021 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
import { submitChanges, validateCanSubmitChanges } from './settings';
const baseModuleStore = Modules.createModuleStore( 'analytics', {
storeName: STORE_NAME,
settingSlugs: [
'anonymizeIP',
'accountID',
'profileID',
'propertyID',
'internalWebPropertyID',
'useSnippet',
'canUseSnippet',
'trackingDisabled',
'ownerID',
],
adminPage: 'googlesitekit-module-analytics',
submitChanges,
validateCanSubmitChanges,
} );
export default baseModuleStore;
|
Implement OnEditorActionListener and add interface for EditRepoDialogListener | package com.example.octoissues;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditOwnerRepoDialog extends DialogFragment implements OnEditorActionListener{
public interface EditRepoDialogListener {
void onFinishEditDialog(String inputText);
}
private EditText editOwner;
private EditText editRepo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_owner_repo, container);
editOwner = (EditText) view.findViewById(R.id.owner_name);
editRepo = (EditText) view.findViewById(R.id.repo_name);
getDialog().setTitle("Enter Owner and Repo");
return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
| package com.example.octoissues;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class EditOwnerRepoDialog extends DialogFragment {
private EditText editOwner;
private EditText editRepo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_owner_repo, container);
editOwner = (EditText) view.findViewById(R.id.owner_name);
editRepo = (EditText) view.findViewById(R.id.repo_name);
getDialog().setTitle("Enter Owner and Repo");
return view;
}
}
|
Adjust port to use nconf | var nconf = require("nconf");
var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()
nconf.argv().env().file({ file: 'local.json'});
/**
* This is your custom transform function
* move it wherever, call it whatever
*/
var transform = require("./transformer")
// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))
/**
* Home route serves index.html file, and
* responds with 200 by default for revisit
*/
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
/**
* Service route is where the magic happens.
*/
app.post('/service', function(req, res) {
var imgBuff = dataUriToBuffer(req.body.content.data)
// Transform the image
var transformed = transform(imgBuff)
var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
req.body.content.data = dataUri
req.body.content.type = imgBuff.type
res.json(req.body)
})
var port = nconf.get("port");
app.listen(port)
console.log('server running on port: ', port)
| var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()
/**
* This is your custom transform function
* move it wherever, call it whatever
*/
var transform = require("./transformer")
// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))
/**
* Home route serves index.html file, and
* responds with 200 by default for revisit
*/
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
/**
* Service route is where the magic happens.
*/
app.post('/service', function(req, res) {
var imgBuff = dataUriToBuffer(req.body.content.data)
// Transform the image
var transformed = transform(imgBuff)
var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
req.body.content.data = dataUri
req.body.content.type = imgBuff.type
res.json(req.body)
})
var port = 8000
app.listen(port)
console.log('server running on port: ', port)
|
Refactor method to eliminate duplicate method calls | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
final class Breadcrumbs extends AbstractSetup
{
public function run()
{
\add_action('jentil_before_before_title', [$this, 'render']);
}
/**
* @action jentil_before_before_title
*/
public function render()
{
$utilities = $this->app->utilities;
if ($utilities->page->is('front_page') &&
!$utilities->page->is('paged')
) {
return;
}
echo $utilities->breadcrumbs([
'before' => \esc_html__('Path: ', 'jentil')
])->render();
}
}
| <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
final class Breadcrumbs extends AbstractSetup
{
public function run()
{
\add_action('jentil_before_before_title', [$this, 'render']);
}
/**
* @action jentil_before_before_title
*/
public function render()
{
$page = $this->app->utilities->page;
if ($page->is('front_page') && !$page->is('paged')) {
return;
}
echo $this->app->utilities->breadcrumbs([
'before' => \esc_html__('Path: ', 'jentil')
])->render();
}
}
|
!!!TASK: Add method argument and return type hints | <?php
declare(strict_types=1);
namespace Neos\Flow\Persistence;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* A container for the list of allowed objects to be persisted during this request.
*
* @Flow\Scope("singleton")
*/
final class AllowedObjectsContainer extends \SplObjectStorage
{
/**
* @var bool
*/
protected $checkNext = false;
/**
* Set the internal flag to return true for `shouldCheck()` on the next invocation.
*
* @param bool $checkNext
*/
public function checkNext(bool $checkNext = true): void
{
$this->checkNext = $checkNext;
}
/**
* Returns true if allowed objects should be checked this time and resets the internal flag to false,
* so the next call will return false unless `checkNext(true)` is called again.
*
* @return bool
*/
public function shouldCheck(): bool
{
$shouldCheck = $this->checkNext;
$this->checkNext = false;
return $shouldCheck;
}
}
| <?php
declare(strict_types=1);
namespace Neos\Flow\Persistence;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* A container for the list of allowed objects to be persisted during this request.
*
* @Flow\Scope("singleton")
*/
final class AllowedObjectsContainer extends \SplObjectStorage
{
/**
* @var bool
*/
protected $checkNext = false;
/**
* Set the internal flag to return true for `shouldCheck()` on the next invocation.
*
* @param bool $checkNext
*/
public function checkNext($checkNext = true)
{
$this->checkNext = $checkNext;
}
/**
* Returns true if allowed objects should be checked this time and resets the internal flag to false,
* so the next call will return false unless `checkNext(true)` is called again.
*
* @return bool
*/
public function shouldCheck(): bool
{
$shouldCheck = $this->checkNext;
$this->checkNext = false;
return $shouldCheck;
}
}
|
Fix user global patching.
Work around wierd runtime error | const path = require('path')
module.exports = function (config) {
if (config.engine.driver) {
// TODO: For some reason this is missing on runtimes, this needs
// investigated as it makes on('playerSandbox') never trigger
require('./driver')(config)
}
config.engine.on('init', function (processType) {
console.log('INIT', processType)
// processType will be 'runner','processor', or 'main'
// Useful for detecting what module you are in
if (processType === 'main') {
// if (!config.common.storage.db.users.count()) {
// importDB(config)
// }
}
if (processType === 'runtime') {
patchRuntimeGlobals(config)
}
})
}
function patchRuntimeGlobals (config) {
let pathToModule = path.join(path.dirname(require.main.filename), 'user-globals.js')
let userGlobals = require(pathToModule)
let newUserGlobals = require('./runtime/user-globals.js')
Object.assign(userGlobals, newUserGlobals)
}
| const path = require('path')
module.exports = function engine (config) {
require('./driver')(config)
config.engine.on('init', function (processType) {
// processType will be 'runner','processor', or 'main'
// Useful for detecting what module you are in
if (processType === 'main') {
// if (!config.common.storage.db.users.count()) {
// importDB(config)
// }
}
if (processType === 'runtime') {
patchRuntimeGlobals(config)
}
})
}
function patchRuntimeGlobals (config) {
let pathToModule = path.join(path.dirname(require.main.filename), 'runtime/user-globals.js')
let userGlobals = require(pathToModule)
let newUserGlobals = require('./runtime/user-globals.js')
Object.assign(userGlobals, newUserGlobals)
}
|
Allow --config and --rippled arguments | var fs = require('fs');
var path = require('path');
var URL = require('url');
var nconf = require('nconf');
/** Load Configuration according to the following hierarchy
* (where items higher on the list take precedence)
*
* 1. Command line arguments
* 2. Environment variables
* 3. The config.json file (if it exists) in the root directory
* 4. The defaults defined below
*/
nconf.argv().env();
// If config.json exists, load from that
var configPath = nconf.get('config') || path.join(__dirname, '/config.json');
if (fs.existsSync(configPath)) {
nconf.file(configPath);
}
if (nconf.get('rippled')) {
var rippledURL = URL.parse(nconf.get('rippled'));
var opts = {
host: rippledURL.hostname,
port: Number(rippledURL.port),
secure: (rippledURL.protocol === 'wss:')
}
nconf.set('rippled_servers', [ opts ]);
}
nconf.defaults({
PORT: 5990,
NODE_ENV: 'development',
HOST: 'localhost',
// sqlite: {
// schemas: __dirname + '/../schemas-for-sqlite',
// files: __dirname + '../'
// },
rippled_servers: [
{
host: 's-west.ripple.com',
port: 443,
secure: true
}
]
});
module.exports = nconf;
| var fs = require('fs');
var nconf = require('nconf');
/** Load Configuration according to the following hierarchy
* (where items higher on the list take precedence)
*
* 1. Command line arguments
* 2. Environment variables
* 3. The config.json file (if it exists) in the root directory
* 4. The defaults defined below
*/
nconf
.argv()
.env();
// If config.json exists, load from that
try {
var config_url = './config.json';
fs.readFileSync(config_url);
nconf.file(config_url);
} catch (err) {}
nconf.defaults({
PORT: 5990,
NODE_ENV: 'development',
HOST: 'localhost',
// sqlite: {
// schemas: __dirname + '/../schemas-for-sqlite',
// files: __dirname + '../'
// },
rippled_servers: [
{
host: 's-west.ripple.com',
port: 443,
secure: true
}
]
});
module.exports = nconf; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.