text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add option to verify jwt token
|
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework_jwt import views as jwt_views
from . import views
router = DefaultRouter()
router.register(r'quotes', views.QuoteViewSet)
router.register(r'authors', views.AuthorViewSet)
router.register(r'categories', views.CategoryViewSet)
router.register(r'tags', views.TagViewSet)
urlpatterns = [
url(r'^docs/$', views.schema_view),
url(r'^', include(router.urls)),
url(r'^token/new/$', jwt_views.ObtainJSONWebToken.as_view()),
url(r'^token/refresh/$', jwt_views.RefreshJSONWebToken.as_view()),
url(r'^token/verify/$', jwt_views.VerifyJSONWebToken.as_view()),
url(r'^filters/$', views.FiltersOptionsView.as_view()),
url(r'^templates/(?P<page>[-\w]+.html)/$', views.AngularTemplateView.as_view()),
]
|
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework_jwt import views as jwt_views
from . import views
router = DefaultRouter()
router.register(r'quotes', views.QuoteViewSet)
router.register(r'authors', views.AuthorViewSet)
router.register(r'categories', views.CategoryViewSet)
router.register(r'tags', views.TagViewSet)
urlpatterns = [
url(r'^docs/$', views.schema_view),
url(r'^', include(router.urls)),
url(r'^token/new/$', jwt_views.obtain_jwt_token),
url(r'^token/refresh/$', jwt_views.refresh_jwt_token),
url(r'^filters/$', views.FiltersOptionsView.as_view()),
url(r'^templates/(?P<page>[-\w]+.html)/$', views.AngularTemplateView.as_view()),
]
|
Remove redundant console message about password prompt
|
'use strict';
var serialNumber = require('./index');
var fail = function (err) {
console.error('Could not read serial number:', err);
};
serialNumber(function (err) {
if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) {
[
'\x1B[7m' + // inverse style
'Your system requires root/administrative priviledge to access the serial number.' +
'\x1B[27m',
'\x1B[31m' + // red
'Attempting to run command with `sudo` and cache your serial for future use.' +
'\x1B[39m'
].forEach(function (msg) {console.info(msg);});
serialNumber.useSudo(function (err, val) {
if (err) {return fail(err);}
require('fs').writeFile('cached', val, function (err) {
if (err) {
console.error('Could not write serial number cache file:', err);
} else {
// green
console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m');
}
});
});
} else if (err) {
fail(err);
}
});
|
'use strict';
var serialNumber = require('./index');
var fail = function (err) {
console.error('Could not read serial number:', err);
};
serialNumber(function (err) {
if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) {
[
'\x1B[7m' + // inverse style
'Your system requires root/administrative priviledge to access the serial number.' +
'\x1B[27m',
'\x1B[31m' + // red
'Attempting to run command with `sudo` and cache your serial for future use.' +
'\x1B[39m',
'\x1B[31m' + // red
'You will be prompted for password.' +
'\x1B[39m'
].forEach(function (msg) {console.info(msg);});
serialNumber.useSudo(function (err, val) {
if (err) {return fail(err);}
require('fs').writeFile('cached', val, function (err) {
if (err) {
console.error('Could not write serial number cache file:', err);
} else {
// green
console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m');
}
});
});
} else if (err) {
fail(err);
}
});
|
Fix prettyTime not being found
|
var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
try {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} catch (e) {
viewCount = 'unknown';
}
return `**${video.title}** by **${video.author}** *(${viewCount} views)* [${exports.prettyTime(video.length_seconds*1000)}]`;
};
exports.prettyPrintWithUser = function(video) {
return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};
exports.simplify = function(video, vid) {
return {
vid: vid,
title: video.title,
author: video.author,
view_count: video.view_count,
};
};
exports.prettyTime = function(ms) {
var seconds = ms / 1000;
var actualSeconds = Math.ceil(seconds % 60);
var paddedSeconds = String('00' + actualSeconds).slice(-2);
var minutes = Math.round((seconds - actualSeconds) / 60);
return `${minutes}:${paddedSeconds}`;
};
module.exports = exports;
|
var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
try {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} catch (e) {
viewCount = 'unknown';
}
return `**${video.title}** by **${video.author}** *(${viewCount} views)* [${prettyTime(video.length_seconds*1000)}]`;
};
exports.prettyPrintWithUser = function(video) {
return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};
exports.simplify = function(video, vid) {
return {
vid: vid,
title: video.title,
author: video.author,
view_count: video.view_count,
};
};
exports.prettyTime = function(ms) {
var seconds = ms / 1000;
var actualSeconds = Math.ceil(seconds % 60);
var paddedSeconds = String('00' + actualSeconds).slice(-2);
var minutes = Math.round((seconds - actualSeconds) / 60);
return `${minutes}:${paddedSeconds}`;
};
module.exports = exports;
|
Move authentication block inside network layer setup
|
/*
Bootstrap components and api on DOM Load
*/
/* global Turbolinks document */
import Relay from 'react-relay';
import {
mountComponents,
unmountComponents,
} from './utils/componentMounter';
import Authentication from './helpers/authentication.es6';
const setupNetworkLayer = () => {
const auth = new Authentication();
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin',
fetchTimeout: 30000,
retryDelays: [5000],
headers: {
'X-CSRF-Token': auth.csrfToken(),
},
})
);
};
const renderComponents = () => {
document.addEventListener('DOMContentLoaded', () => {
if (typeof Turbolinks !== 'undefined' && typeof Turbolinks.controller !== 'undefined') {
setupNetworkLayer();
document.addEventListener('turbolinks:render', unmountComponents);
document.addEventListener('turbolinks:load', mountComponents);
} else {
setupNetworkLayer();
mountComponents();
}
});
};
export default renderComponents;
|
/*
Bootstrap components and api on DOM Load
*/
/* global Turbolinks document */
import Relay from 'react-relay';
import {
mountComponents,
unmountComponents,
} from './utils/componentMounter';
import Authentication from './helpers/authentication.es6';
const auth = new Authentication();
const setupNetworkLayer = () => {
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin',
fetchTimeout: 30000,
retryDelays: [5000],
headers: {
'X-CSRF-Token': auth.csrfToken(),
},
})
);
};
const renderComponents = () => {
document.addEventListener('DOMContentLoaded', () => {
if (typeof Turbolinks !== 'undefined' && typeof Turbolinks.controller !== 'undefined') {
setupNetworkLayer();
document.addEventListener('turbolinks:render', unmountComponents);
document.addEventListener('turbolinks:load', mountComponents);
} else {
setupNetworkLayer();
mountComponents();
}
});
};
export default renderComponents;
|
Check if PluginExecutionContext was started before shutting it down.
If a `PluginExecutionContext().shutdown()` is called _before_
`PluginExecutionContext().start()` was called,
this leads to an `AttributeError` exception since finalizer tries to
access to attributes which were never defined.
|
from bonobo.execution.base import LoopingExecutionContext, recoverable
class PluginExecutionContext(LoopingExecutionContext):
PERIOD = 0.5
def __init__(self, wrapped, parent):
# Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure
# plugins, for example if it depends on an external service.
super().__init__(wrapped(self), parent)
def start(self):
super().start()
with recoverable(self.handle_error):
self.wrapped.initialize()
def shutdown(self):
if self.started:
with recoverable(self.handle_error):
self.wrapped.finalize()
self.alive = False
def step(self):
with recoverable(self.handle_error):
self.wrapped.run()
|
from bonobo.execution.base import LoopingExecutionContext, recoverable
class PluginExecutionContext(LoopingExecutionContext):
PERIOD = 0.5
def __init__(self, wrapped, parent):
# Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure
# plugins, for example if it depends on an external service.
super().__init__(wrapped(self), parent)
def start(self):
super().start()
with recoverable(self.handle_error):
self.wrapped.initialize()
def shutdown(self):
with recoverable(self.handle_error):
self.wrapped.finalize()
self.alive = False
def step(self):
with recoverable(self.handle_error):
self.wrapped.run()
|
Support layout on template endpoints
|
from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class MemeRequest:
template_id: str
style: list[str]
text: list[str]
layout: str
font: str
extension: str
redirect: bool
@dataclass
class CustomRequest:
background: str
style: str
text: list[str]
layout: str
font: str
extension: str
redirect: bool
@dataclass
class MemeTemplateRequest:
style: list[str]
text: list[str]
layout: str
font: str
extension: str
redirect: bool
@dataclass
class AutomaticRequest:
text: str
safe: bool
redirect: bool
@dataclass
class MemeResponse:
url: str
@dataclass
class ExampleResponse:
url: str
template: str
@dataclass
class _Example:
text: list[str]
url: str
@dataclass
class TemplateResponse:
id: str
name: str
lines: int
overlays: int
styles: list[str]
blank: str
example: _Example
source: str
_self: str
@dataclass
class ErrorResponse:
error: str
|
from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class MemeRequest:
template_id: str
style: list[str]
text: list[str]
layout: str
font: str
extension: str
redirect: bool
@dataclass
class CustomRequest:
background: str
style: str
text: list[str]
layout: str
font: str
extension: str
redirect: bool
@dataclass
class MemeTemplateRequest:
style: list[str]
text: list[str]
font: str
extension: str
redirect: bool
@dataclass
class AutomaticRequest:
text: str
safe: bool
redirect: bool
@dataclass
class MemeResponse:
url: str
@dataclass
class ExampleResponse:
url: str
template: str
@dataclass
class _Example:
text: list[str]
url: str
@dataclass
class TemplateResponse:
id: str
name: str
lines: int
overlays: int
styles: list[str]
blank: str
example: _Example
source: str
_self: str
@dataclass
class ErrorResponse:
error: str
|
Change version format to allow MAJOR.MINOR.PATCH.
|
#!/usr/bin/env python
from setuptools import setup, find_packages
version_tuple = __import__('pymysql').VERSION
if version_tuple[3] is not None:
version = "%d.%d.%d_%s" % version_tuple
else:
version = "%d.%d.%d" % version_tuple[:3]
try:
with open('README.rst') as f:
readme = f.read()
except IOError:
readme = ''
setup(
name="PyMySQL",
version=version,
url='https://github.com/PyMySQL/PyMySQL/',
download_url = 'https://github.com/PyMySQL/PyMySQL/tarball/pymysql-%s' % version,
author='yutaka.matsubara',
author_email='yutaka.matsubara@gmail.com',
maintainer='Marcel Rodrigues',
maintainer_email='marcelgmr@gmail.com',
description='Pure-Python MySQL Driver',
long_description=readme,
license="MIT",
packages=find_packages(),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Database',
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
version_tuple = __import__('pymysql').VERSION
if version_tuple[2] is not None:
version = "%d.%d_%s" % version_tuple
else:
version = "%d.%d" % version_tuple[:2]
try:
with open('README.rst') as f:
readme = f.read()
except IOError:
readme = ''
setup(
name="PyMySQL",
version=version,
url='https://github.com/PyMySQL/PyMySQL/',
download_url = 'https://github.com/PyMySQL/PyMySQL/tarball/pymysql-%s' % version,
author='yutaka.matsubara',
author_email='yutaka.matsubara@gmail.com',
maintainer='Marcel Rodrigues',
maintainer_email='marcelgmr@gmail.com',
description='Pure-Python MySQL Driver',
long_description=readme,
license="MIT",
packages=find_packages(),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Database',
]
)
|
Add control panel test for update
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test update payment session timeout."""
httpretty.register_uri(
httpretty.PUT,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout updated"}',
status=201,
)
response = ControlPanel.update_payment_session_timeout(timeout=30)
self.assertTrue(response['status'])
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
|
Fix cardboard items being unrepairable
|
package net.mcft.copy.betterstorage.item.cardboard;
import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;
public class ItemCardboardSheet extends ItemBetterStorage {
public static final EnumToolMaterial toolMaterial =
EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
public static final EnumArmorMaterial armorMaterial =
EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);
public ItemCardboardSheet(int id) {
super(id);
setMaxStackSize(8);
toolMaterial.customCraftingMaterial = this;
armorMaterial.customCraftingMaterial = this;
}
}
|
package net.mcft.copy.betterstorage.item.cardboard;
import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;
public class ItemCardboardSheet extends ItemBetterStorage {
public static final EnumToolMaterial toolMaterial =
EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
public static final EnumArmorMaterial armorMaterial =
EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);
static {
toolMaterial.customCraftingMaterial = Items.cardboardSheet;
armorMaterial.customCraftingMaterial = Items.cardboardSheet;
}
public ItemCardboardSheet(int id) {
super(id);
setMaxStackSize(8);
}
}
|
Fix resolution of value in composites
|
'use strict';
var last = require('es5-ext/array/#/last')
, noop = require('es5-ext/function/noop')
, mapKeys = require('es5-ext/object/map-keys')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, splitId = require('dbjs/_setup/unserialize/id')
, DOMInput = require('../_composite')
, getPrototypeOf = Object.getPrototypeOf
, getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get
, mapKey = function (id) { return last.call(splitId(id)); }
, Input;
module.exports = Input = function (document, type/*, options*/) {
var options = arguments[2], fn, proto;
this.type = type;
options = this._resolveOptions(options);
options.dbOptions = Object(options.dbOptions);
proto = options.dbOptions;
fn = proto._value_;
while ((fn !== undefined) && (typeof fn !== 'function')) {
proto = getPrototypeOf(proto);
fn = proto._value_;
}
this.getValue = callable(fn);
DOMInput.call(this, document, type, options);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
name: d.gs(noop, noop),
inputValue: d.gs(function () {
var state = mapKeys(getInputValue.call(this), mapKey);
return this.getValue.call(state);
}, noop)
});
|
'use strict';
var noop = require('es5-ext/function/noop')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, DOMInput = require('../_composite')
, getPrototypeOf = Object.getPrototypeOf
, getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get
, Input;
module.exports = Input = function (document, type/*, options*/) {
var options = arguments[2], fn, proto;
this.type = type;
options = this._resolveOptions(options);
options.dbOptions = Object(options.dbOptions);
proto = options.dbOptions;
fn = proto._value_;
while ((fn !== undefined) && (typeof fn !== 'function')) {
proto = getPrototypeOf(proto);
fn = proto._value_;
}
this.getValue = callable(fn);
DOMInput.call(this, document, type, options);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
name: d.gs(noop, noop),
inputValue: d.gs(function () {
var state = getInputValue.call(this);
return this.getValue.call(state);
}, noop)
});
|
Fix missing auth handler when trying to access EC2.
|
import os
import redis as pyredis
from cloudly.aws import ec2
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_conn():
""" Get a connection to a Redis server. The priority is:
- look for an environment variable REDIS_HOST, else
- look for an EC2 hosted server offering the service 'redis', else
- use localhost, 127.0.0.1.
"""
try:
service_ips = ec2.find_service_ip('redis')
except Exception, exception:
log.warning(exception)
service_ips = []
ip_address = (os.environ.get("REDIS_HOST") or
service_ips[0] if service_ips else None or
"127.0.0.1")
redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku.
'redis://{}:6379'.format(ip_address))
log.info("Connecting to Redis server at {}".format(redis_url))
return pyredis.from_url(redis_url)
redis = get_conn()
|
import os
import redis as pyredis
from cloudly.aws import ec2
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_conn():
""" Get a connection to a Redis server. The priority is:
- look for an environment variable REDIS_HOST, else
- look for an EC2 hosted server offering the service 'redis', else
- use localhost, 127.0.0.1.
"""
service_ips = ec2.find_service_ip('redis')
ip_address = (os.environ.get("REDIS_HOST") or
service_ips[0] if service_ips else None or
"127.0.0.1")
redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku.
'redis://{}:6379'.format(ip_address))
log.info("Connecting to Redis server at {}".format(redis_url))
return pyredis.from_url(redis_url)
redis = get_conn()
|
Normalize variable names, and error check for undefined rather than for falsy
|
/************************************
* Redis key and channel namespaces *
************************************/
module.exports = {
getItemPropertyKey: getItemPropertyKey,
getKeyInfo: getKeyInfo,
getPropertyChannel: getPropertyChannel,
getFocusProperty: getFocusProperty,
// The unique ID key is used to consistently increase item id's. Should we use guid's instead?
uniqueIdKey: '__fin_unique_id'
}
// item properties are stored at I<item id>@<propName> e.g. I20@books
// channel names for items are #I<item id> e.g. #I20
// channel names for properties are #P<propName> e.g. #Pbooks
// Data state keys
function getItemPropertyKey(itemID, propName) {
if (itemID === undefined || propName === undefined) {
throw new Error("itemID and propName are required for keys.getItemPropertyKey")
}
return 'I' + itemID + '@' + propName
}
function getKeyInfo(key) {
var type = key[0],
parts = key.substr(1).split('@')
return { type: type, id: parseInt(parts[0]), property: parts[1] }
}
function getPropertyChannel(propName) {
return '#P' + propName
}
// Misc
function getFocusProperty(propName) {
return '_focus_' + propName
}
|
/************************************
* Redis key and channel namespaces *
************************************/
module.exports = {
getItemPropertyKey: getItemPropertyKey,
getKeyInfo: getKeyInfo,
getPropertyChannel: getPropertyChannel,
getFocusProperty: getFocusProperty,
// The unique ID key is used to consistently increase item id's. Should we use guid's instead?
uniqueIdKey: '__fin_unique_id'
}
// item properties are stored at I<item id>@<propName> e.g. I20@books
// channel names for items are #I<item id> e.g. #I20
// channel names for properties are #P<propName> e.g. #Pbooks
// Data state keys
function getItemPropertyKey(itemId, propName) {
if (!propName || typeof itemId == 'undefined') {
throw new Error("itemId and propName are required for keys.getItemPropertyKey")
}
return 'I' + itemId + '@' + propName
}
function getKeyInfo(key) {
var type = key[0],
parts = key.substr(1).split('@')
return { type: type, id: parseInt(parts[0]), property: parts[1] }
}
function getPropertyChannel(propName) {
return '#P' + propName
}
// Misc
function getFocusProperty(propName) {
return '_focus_' + propName
}
|
Set greeting defaults to null
|
let userConfig;
try {
userConfig = require('../config');
} catch (e) {
throw new Error(`Config file could not be found or read! The error given was: ${e.message}`);
}
const defaultConfig = {
"token": null,
"mailGuildId": null,
"mainGuildId": null,
"logChannelId": null,
"prefix": "!",
"snippetPrefix": "!!",
"status": "Message me for help!",
"responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.",
"inboxServerPermission": null,
"alwaysReply": false,
"alwaysReplyAnon": false,
"useNicknames": false,
"ignoreAccidentalThreads": false,
"enableGreeting": false,
"greetingMessage": null,
"greetingAttachment": null,
"port": 8890,
"url": null
};
const finalConfig = Object.assign({}, defaultConfig);
for (const [prop, value] of Object.entries(userConfig)) {
if (! defaultConfig.hasOwnProperty(prop)) {
throw new Error(`Invalid option: ${prop}`);
}
finalConfig[prop] = value;
}
if (! finalConfig.token) throw new Error('Missing token!');
if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!');
if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!');
module.exports = finalConfig;
|
let userConfig;
try {
userConfig = require('../config');
} catch (e) {
throw new Error(`Config file could not be found or read! The error given was: ${e.message}`);
}
const defaultConfig = {
"token": null,
"mailGuildId": null,
"mainGuildId": null,
"logChannelId": null,
"prefix": "!",
"snippetPrefix": "!!",
"status": "Message me for help!",
"responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.",
"inboxServerPermission": null,
"alwaysReply": false,
"alwaysReplyAnon": false,
"useNicknames": false,
"ignoreAccidentalThreads": false,
"enableGreeting": false,
"greetingMessage": "The message the bot sends to a new user",
"greetingAttachment": "Put a file path here",
"port": 8890,
"url": null
};
const finalConfig = Object.assign({}, defaultConfig);
for (const [prop, value] of Object.entries(userConfig)) {
if (! defaultConfig.hasOwnProperty(prop)) {
throw new Error(`Invalid option: ${prop}`);
}
finalConfig[prop] = value;
}
if (! finalConfig.token) throw new Error('Missing token!');
if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!');
if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!');
module.exports = finalConfig;
|
Fix return type and set strict
|
<?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.
declare(strict_types=1);
namespace App\Models;
/**
* @property int $count
* @property int $name
*/
class Count extends Model
{
public $incrementing = false;
public $timestamps = false;
protected $primaryKey = 'name';
protected $table = 'osu_counts';
public static function currentRankStart(string $mode): static
{
return static::firstOrCreate(['name' => "pp_rank_column_{$mode}"], ['count' => 0]);
}
public static function totalUsers(): static
{
return static::firstOrCreate(['name' => 'usercount'], ['count' => 0]);
}
public static function lastMailUserNotificationIdSent(): static
{
return static::firstOrCreate(['name' => 'last_mail_user_notification_id_sent'], ['count' => 0]);
}
}
|
<?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\Models;
/**
* @property int $count
* @property int $name
*/
class Count extends Model
{
public $incrementing = false;
public $timestamps = false;
protected $primaryKey = 'name';
protected $table = 'osu_counts';
public static function currentRankStart(string $mode): int
{
return static::firstOrCreate(['name' => "pp_rank_column_{$mode}"], ['count' => 0]);
}
public static function totalUsers()
{
return static::firstOrCreate(['name' => 'usercount'], ['count' => 0]);
}
public static function lastMailUserNotificationIdSent()
{
return static::firstOrCreate(['name' => 'last_mail_user_notification_id_sent'], ['count' => 0]);
}
}
|
Add test to include strings to numbers
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test the command line interface """
import pytest
from ..cli import _is_int, _is_float, _resolve_type
@pytest.mark.parametrize("test_input,expected", [
("True", True),
("False", False),
("None", None),
(13.3, 13.3),
("12.51", 12.51),
(10, 10),
("10", 10),
("hello world", "hello world"),
(u"π", u"π"),
])
def test_resolve_type(test_input, expected):
assert _resolve_type(test_input) == expected
@pytest.mark.parametrize("value,expected", [
(13.71, True),
("False", False),
("None", False),
(-8.2, True),
(10, False),
("hello world", False),
("π", False),
])
def test_is_float(value, expected):
assert (_is_float(value)) == expected
@pytest.mark.parametrize("value,expected", [
(13.71, False),
("False", False),
("None", False),
(-8.2, False),
("-23.2", False),
(10, True),
("13", True),
("hello world", False),
("π", False),
])
def test_is_int(value, expected):
assert (_is_int(value)) == expected
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test the command line interface """
import pytest
from ..cli import _is_int, _is_float, _resolve_type
@pytest.mark.parametrize("test_input,expected", [
("True", True),
("False", False),
("None", None),
(13.3, 13.3),
(10, 10),
("hello world", "hello world"),
(u"π", u"π"),
])
def test_resolve_type(test_input, expected):
assert _resolve_type(test_input) == expected
@pytest.mark.parametrize("value,expected", [
(13.71, True),
("False", False),
("None", False),
(-8.2, True),
(10, False),
("hello world", False),
("π", False),
])
def test_is_float(value, expected):
assert (_is_float(value)) == expected
@pytest.mark.parametrize("value,expected", [
(13.71, False),
("False", False),
("None", False),
(-8.2, False),
(10, True),
("hello world", False),
("π", False),
])
def test_is_int(value, expected):
assert (_is_int(value)) == expected
|
Make date and time optional
|
orion.addEntity('activities', _.extend(_.clone(commonSchema), {
location: {
type: Object,
label: 'Location',
optional: true,
autoform: {
type: 'map',
afFieldInput: {
searchBox: true
}
}
},
'location.lat': {
type: String
},
'location.lng': {
type: String
},
date: {
type: Date,
label: 'Date and Time',
optional: true,
autoform: {
afFieldInput: {
type: 'datetime-local'
}
}
},
recipeIds: {
type: Array,
label: 'Recipes',
optional: true,
autoform: {
omit: true
}
},
'recipeIds.$': {
type: String
}
}), {
icon: 'bullhorn',
sidebarName: 'Activities',
pluralName: 'Activities',
singularName: 'Activity',
tableColumns: [
{data: 'title', title: 'Title'},
orion.attributeColumn('summernote', 'body', 'Preview')
]
});
|
orion.addEntity('activities', _.extend(_.clone(commonSchema), {
location: {
type: Object,
label: 'Location',
optional: true,
autoform: {
type: 'map',
afFieldInput: {
searchBox: true
}
}
},
'location.lat': {
type: String
},
'location.lng': {
type: String
},
date: {
type: Date,
label: 'Date and Time',
autoform: {
afFieldInput: {
type: 'datetime-local'
}
}
},
recipeIds: {
type: Array,
label: 'Recipes',
optional: true,
autoform: {
omit: true
}
},
'recipeIds.$': {
type: String
}
}), {
icon: 'bullhorn',
sidebarName: 'Activities',
pluralName: 'Activities',
singularName: 'Activity',
tableColumns: [
{data: 'title', title: 'Title'},
orion.attributeColumn('summernote', 'body', 'Preview')
]
});
|
Fix for ion-modal spurious blaze errors
|
IonLoading = {
show: function (userOptions) {
var userOptions = userOptions || {};
var options = _.extend({
delay: 0,
duration: null,
customTemplate: null,
backdrop: false
}, userOptions);
if (options.backdrop) {
IonBackdrop.retain();
$('.backdrop').addClass('backdrop-loading');
}
Meteor.setTimeout(function () {
this.template = Template['ionLoading'];
this.view = Blaze.renderWithData(this.template, {template: options.customTemplate}, $('.ionic-body').get(0));
var $loadingEl = $(this.view.firstNode());
$loadingEl.addClass('visible');
Meteor.setTimeout(function () {
$loadingEl.addClass('active');
}, 10);
}.bind(this), options.delay);
if (options.duration) {
Meteor.setTimeout(function () {
this.hide();
}.bind(this), options.duration);
}
},
hide: function () {
if (this.view) {
var $loadingEl = $(this.view.firstNode());
$loadingEl.removeClass('active');
Meteor.setTimeout(function () {
IonBackdrop.release();
$loadingEl.removeClass('visible');
Blaze.remove(this.view);
this.view = null;
}.bind(this), 400);
}
}
};
|
IonLoading = {
show: function (userOptions) {
var userOptions = userOptions || {};
var options = _.extend({
delay: 0,
duration: null,
customTemplate: null,
backdrop: false
}, userOptions);
if (options.backdrop) {
IonBackdrop.retain();
$('.backdrop').addClass('backdrop-loading');
}
Meteor.setTimeout(function () {
this.template = Template['ionLoading'];
this.view = Blaze.renderWithData(this.template, {template: options.customTemplate}, $('.ionic-body').get(0));
var $loadingEl = $(this.view.firstNode());
$loadingEl.addClass('visible');
Meteor.setTimeout(function () {
$loadingEl.addClass('active');
}, 10);
}.bind(this), options.delay);
if (options.duration) {
Meteor.setTimeout(function () {
this.hide();
}.bind(this), options.duration);
}
},
hide: function () {
var $loadingEl = $(this.view.firstNode());
$loadingEl.removeClass('active');
Meteor.setTimeout(function () {
IonBackdrop.release();
$loadingEl.removeClass('visible');
Blaze.remove(this.view);
}.bind(this), 400);
}
};
|
FIx exception in dialog tab completion
|
package vg.civcraft.mc.civmodcore.chatDialog;
import java.util.Collections;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.TabCompleteEvent;
public class ChatListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void tabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof Player)) {
return;
}
Dialog dia = DialogManager.getDialog((Player) e.getSender());
if (dia != null) {
String[] split = e.getBuffer().split(" ");
List <String> complet = dia.onTabComplete(split.length > 0 ? split[split.length - 1] : "", split);
if (complet == null) {
complet = Collections.emptyList();
}
e.setCompletions(complet);
}
}
@EventHandler
public void logoff(PlayerQuitEvent e) {
DialogManager.forceEndDialog(e.getPlayer());
}
}
|
package vg.civcraft.mc.civmodcore.chatDialog;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.TabCompleteEvent;
public class ChatListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void tabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof Player)) {
return;
}
Dialog dia = DialogManager.getDialog((Player) e.getSender());
if (dia != null) {
String[] split = e.getBuffer().split(" ");
e.setCompletions(dia.onTabComplete(split.length > 0 ? split[split.length - 1] : "", split));
}
}
@EventHandler
public void logoff(PlayerQuitEvent e) {
DialogManager.forceEndDialog(e.getPlayer());
}
}
|
Remove custom YesNoEnum and use yesno method from ConsoleUI
There is no need to reimplement the yes/no functionality.
Change-Id: I0e9050a38b9785e93b6549d27455f356e828d2de
Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.hooks.its;
import com.google.gerrit.pgm.init.InitStep;
import com.google.gerrit.pgm.init.Section;
import com.google.gerrit.pgm.util.ConsoleUI;
public class InitIts implements InitStep {
public static String COMMENT_LINK_SECTION = "commentLink";
public static enum TrueFalseEnum {
TRUE, FALSE;
}
@Override
public void run() throws Exception {
}
public boolean isConnectivityRequested(ConsoleUI ui, String url) {
return ui.yesno(false, "Test connectivity to %s", url);
}
public boolean enterSSLVerify(Section section) {
return TrueFalseEnum.TRUE == section.select("Verify SSL Certificates",
"sslVerify", TrueFalseEnum.TRUE);
}
}
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.hooks.its;
import com.google.gerrit.pgm.init.InitStep;
import com.google.gerrit.pgm.init.Section;
import com.google.gerrit.pgm.util.ConsoleUI;
public class InitIts implements InitStep {
public static String COMMENT_LINK_SECTION = "commentLink";
public static enum YesNoEnum {
Y, N;
}
public static enum TrueFalseEnum {
TRUE, FALSE;
}
@Override
public void run() throws Exception {
}
public boolean isConnectivityRequested(ConsoleUI ui, String url) {
YesNoEnum wantToTest =
ui.readEnum(YesNoEnum.N, "Test connectivity to %s", url);
return wantToTest == YesNoEnum.Y;
}
public boolean enterSSLVerify(Section section) {
return TrueFalseEnum.TRUE == section.select("Verify SSL Certificates",
"sslVerify", TrueFalseEnum.TRUE);
}
}
|
Support Q, use when not static resolve
|
PromiseAllSync = {
extend: function(PromiseClass) {
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPromise = fn ? fn(item) : item;
return nextPromise.then(function() {
if(unfn) stack.push(item);
});
});
}, (PromiseClass.resolve || PromiseClass.when)())
.catch(function(e) {
if(unfn) while(stack.length) unfn(stack.pop());
return PromiseClass.reject(e);
});
}
}
};
|
PromiseAllSync = {
extend: function(PromiseClass) {
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPromise = fn ? fn(item) : item;
return nextPromise.then(function() {
if(unfn) stack.push(item);
});
});
}, PromiseClass.resolve())
.catch(function(e) {
if(unfn) while(stack.length) unfn(stack.pop());
return PromiseClass.reject(e);
});
}
}
};
|
Update majors when user is created
|
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Jobs\PushToJedi;
use App\User;
use DateTime;
class UserObserver
{
public function created(User $user): void
{
if ('cas_login' === $user->create_reason) {
return;
}
UpdateMajorsForUser::dispatch($user)->onQueue('buzzapi');
}
public function saved(User $user): void
{
PushToJedi::dispatch($user, User::class, $user->id, 'saved')->onQueue('jedi');
}
public function updated(User $user): void
{
if (null === $user->access_override_until || $user->access_override_until <= new DateTime()) {
return;
}
PushToJedi::dispatch($user, User::class, $user->id, 'updated/access override expiration')
->delay($user->access_override_until)->onQueue('jedi');
}
}
|
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Jobs\PushToJedi;
use App\User;
use DateTime;
class UserObserver
{
public function saved(User $user): void
{
PushToJedi::dispatch($user, User::class, $user->id, 'saved')->onQueue('jedi');
}
public function updated(User $user): void
{
if (null === $user->access_override_until || $user->access_override_until <= new DateTime()) {
return;
}
PushToJedi::dispatch($user, User::class, $user->id, 'updated/access override expiration')
->delay($user->access_override_until)->onQueue('jedi');
}
}
|
Fix duplicate captcha import check
|
from django.core.exceptions import ImproperlyConfigured
class CaptchaFormMixin(object):
def _reorder_fields(self, ordering):
"""
Test that the 'captcha' field is really present.
This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration.
"""
if 'captcha' not in ordering:
raise ImproperlyConfigured(
"When using 'FLUENT_COMMENTS_FIELD_ORDER', "
"make sure the 'captcha' field included too to use '{}' form. ".format(
self.__class__.__name__
)
)
super(CaptchaFormMixin, self)._reorder_fields(ordering)
# Avoid making captcha required for previews.
if self.is_preview:
self.fields.pop('captcha')
|
from django.core.exceptions import ImproperlyConfigured
try:
from captcha.fields import ReCaptchaField as CaptchaField
except ImportError:
try:
from captcha.fields import CaptchaField
except ImportError:
raise ImportError(
"To use the captcha contact form, you need to have "
"django-recaptcha or django-simple-captcha installed."
)
class CaptchaFormMixin(object):
def _reorder_fields(self, ordering):
"""
Test that the 'captcha' field is really present.
This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration.
"""
if 'captcha' not in ordering:
raise ImproperlyConfigured(
"When using 'FLUENT_COMMENTS_FIELD_ORDER', "
"make sure the 'captcha' field included too to use '{}' form. ".format(
self.__class__.__name__
)
)
super(CaptchaFormMixin, self)._reorder_fields(ordering)
# Avoid making captcha required for previews.
if self.is_preview:
self.fields.pop('captcha')
|
Replace deprecated PyGlove symbols to new ones.
PiperOrigin-RevId: 408683720
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Regularized Evolution controller from PyGlove. Similar to NEAT."""
import numpy as np
import pyglove as pg
from es_enas.controllers import base_controller
class RegularizedEvolutionController(base_controller.BaseController):
"""Regularized Evolution Controller."""
def __init__(self, dna_spec, batch_size,
**kwargs):
"""Initialization. See base class for more details."""
super().__init__(dna_spec, batch_size)
population_size = self._batch_size
tournament_size = int(np.sqrt(population_size))
self._controller = pg.evolution.regularized_evolution(
population_size=population_size,
tournament_size=tournament_size,
mutator=pg.evolution.mutators.Uniform()) # pytype: disable=wrong-arg-types # gen-stub-imports
self._controller.setup(self._dna_spec)
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Regularized Evolution controller from PyGlove. Similar to NEAT."""
import numpy as np
import pyglove as pg
from es_enas.controllers import base_controller
class RegularizedEvolutionController(base_controller.BaseController):
"""Regularized Evolution Controller."""
def __init__(self, dna_spec, batch_size,
**kwargs):
"""Initialization. See base class for more details."""
super().__init__(dna_spec, batch_size)
population_size = self._batch_size
tournament_size = int(np.sqrt(population_size))
self._controller = pg.generators.RegularizedEvolution(
population_size=population_size,
tournament_size=tournament_size,
mutator=pg.generators.evolution_mutators.Uniform()) # pytype: disable=wrong-arg-types # gen-stub-imports
self._controller.setup(self._dna_spec)
|
Move fade out animation after finish()
|
package io.github.droidkaigi.confsched2017.view.activity;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import io.github.droidkaigi.confsched2017.R;
import io.github.droidkaigi.confsched2017.databinding.ActivitySearchBinding;
import io.github.droidkaigi.confsched2017.view.fragment.SearchFragment;
public class SearchActivity extends BaseActivity {
private ActivitySearchBinding binding;
public static void start(@NonNull Activity activity) {
Intent intent = new Intent(activity, SearchActivity.class);
activity.startActivity(intent);
activity.overridePendingTransition(0, R.anim.activity_fade_exit);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
initBackToolbar(binding.toolbar);
replaceFragment(SearchFragment.newInstance(), R.id.content_view);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(0, R.anim.activity_fade_exit);
}
@Override
public void onBackPressed() {
finish();
}
}
|
package io.github.droidkaigi.confsched2017.view.activity;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import io.github.droidkaigi.confsched2017.R;
import io.github.droidkaigi.confsched2017.databinding.ActivitySearchBinding;
import io.github.droidkaigi.confsched2017.view.fragment.SearchFragment;
public class SearchActivity extends BaseActivity {
private ActivitySearchBinding binding;
public static void start(@NonNull Activity activity) {
Intent intent = new Intent(activity, SearchActivity.class);
activity.startActivity(intent);
activity.overridePendingTransition(0, R.anim.activity_fade_exit);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
initBackToolbar(binding.toolbar);
replaceFragment(SearchFragment.newInstance(), R.id.content_view);
}
@Override
public void finish() {
overridePendingTransition(0, R.anim.activity_fade_exit);
super.finish();
}
@Override
public void onBackPressed() {
finish();
}
}
|
Define our constants FIRST to prevent errors
|
<?php
// Start the session so we can save
// query results across pages requests.
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE);
define("APPNAME", "CNAM");
define("VERSION", "1.3");
define("APIVersion", "1");
define("DEVGITHUB", "https://www.github.com/cedwardsmedia/cnam");
define("DEVELOPER", "Corey Edwards");
define("COPYRIGHTYEAR", "2014 - 2015");
define("COPYRIGHT", "© " . COPYRIGHTYEAR . " " . DEVELOPER);
// Check which version of PHP we're using. If it's too old, die.
if (phpversion() < "5.5") {
echo(APPNAME . " requires PHP 5.5 or greater. You are currently running PHP " . phpversion() . ". Please upgrade PHP.\n");
exit(1);
}
require 'vendor/autoload.php';
require 'APICaller.php';
include 'config.php';
|
<?php
// Start the session so we can save
// query results across pages requests.
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL & E_NOTICE);
require 'vendor/autoload.php';
require 'APICaller.php';
include 'config.php';
define("APPNAME", "CNAM");
define("VERSION", "1.3");
define("APIVersion", "1");
define("DEVGITHUB", "https://www.github.com/cedwardsmedia/cnam");
define("DEVELOPER", "Corey Edwards");
define("COPYRIGHTYEAR", "2014 - 2015");
define("COPYRIGHT", "© " . COPYRIGHTYEAR . " " . DEVELOPER);
// Check which version of PHP we're using. If it's too old, die.
if (phpversion() < "5.5") {
echo(APPNAME . " requires PHP 5.5 or greater. You are currently running PHP " . phpversion() . ". Please upgrade PHP.\n");
exit(1);
}
|
Replace windows backslashes in template definition when precompiling
|
'use strict';
function precompileGlobal(templates, opts) {
var out = '', name, template;
opts = opts || {};
for ( var i = 0; i < templates.length; i++ ) {
// replace all backslashes with forward slashes
var normalizedName = templates[i].name.replace(/\\/g, '');
name = JSON.stringify(normalizedName);
template = templates[i].template;
out += '(function() {' +
'(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' +
'[' + name + '] = (function() {\n' + template + '\n})();\n';
if(opts.asFunction) {
out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n';
}
out += '})();\n';
}
return out;
}
module.exports = precompileGlobal;
|
'use strict';
function precompileGlobal(templates, opts) {
var out = '', name, template;
opts = opts || {};
for ( var i = 0; i < templates.length; i++ ) {
name = JSON.stringify(templates[i].name);
template = templates[i].template;
out += '(function() {' +
'(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' +
'[' + name + '] = (function() {\n' + template + '\n})();\n';
if(opts.asFunction) {
out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n';
}
out += '})();\n';
}
return out;
}
module.exports = precompileGlobal;
|
Add additional comments to command for clarity
|
package useful
import (
"fmt"
"os"
"runtime"
)
// GetPwd1 return .go file path, where func really is
//
// Useful only with .go file
// With binary file always return path of source .go file
func GetPwd1() string {
_, pwd, _, ok := runtime.Caller(0)
if !ok {
panic("No caller information")
}
return pwd
}
// GetPwd2 always return folder path from where you run it
// For example if you run
// cd /folder
// then run in this path (we suppose that this file is exist)
// go run golang/src/project/main.go
// command return - /folder
func GetPwd2() string {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
return pwd
}
// GetPwd3 return file path from where you run it (need binary file, not .go file)
// As of Go 1.8 (Released February 2017) the recommended way of doing PWD is with os.Executable
// But it's only useful when you run binary file (after go build)
// If you run it from .go file you will get something like
// /var/folders/n3/r0chsz09339gm2gbxdhjctgr0000gn/T/go-build824104956/command-line-arguments/_obj/exe/test
func GetPwd3() string {
pwd, err := os.Executable()
if err != nil {
fmt.Println(err)
}
return pwd
}
|
package useful
import (
"fmt"
"os"
"runtime"
)
// GetPwd1 return .go file path, where func really is
//
// Useful only with .go file
// With binary file always return path of source .go file
func GetPwd1() string {
_, pwd, _, ok := runtime.Caller(0)
if !ok {
panic("No caller information")
}
return pwd
}
// GetPwd2 always return folder path from where you run it
func GetPwd2() string {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
return pwd
}
// GetPwd3 return file path from where you run it (need binary file, not .go file)
// As of Go 1.8 (Released February 2017) the recommended way of doing PWD is with os.Executable
// But it's only useful when you run binary file (after go build)
// If you run it from .go file you will get something like
// /var/folders/n3/r0chsz09339gm2gbxdhjctgr0000gn/T/go-build824104956/command-line-arguments/_obj/exe/test
func GetPwd3() string {
pwd, err := os.Executable()
if err != nil {
fmt.Println(err)
}
return pwd
}
|
Add the creation of the data dir for the sqlite file.
|
from .base import *
DEBUG = False
# Make data dir
DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data'))
not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_DIR, '..', 'data', 'db.sqlite3')),
}
}
ALLOWED_HOSTS = [
'127.0.0.1'
]
# email settings
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_REPLY_TO = 'donotreply@'
# Logging
LOG_ENV = 'travis'
EXAMPLES_LOG_FILE = '{}/{}-examples.log'.format(LOG_DIR, LOG_ENV)
DCOLUMNS_LOG_FILE = '{}/{}-dcolumn.log'.format(LOG_DIR, LOG_ENV)
LOGGING.get('handlers', {}).get(
'examples_file', {})['filename'] = EXAMPLES_LOG_FILE
LOGGING.get('handlers', {}).get(
'dcolumns_file', {})['filename'] = DCOLUMNS_LOG_FILE
LOGGING.get('loggers', {}).get('django.request', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('examples', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('dcolumns', {})['level'] = 'DEBUG'
|
from .base import *
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_DIR, '..', 'data', 'db.sqlite3')),
}
}
ALLOWED_HOSTS = [
'127.0.0.1'
]
# email settings
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_REPLY_TO = 'donotreply@'
# Logging
LOG_ENV = 'travis'
EXAMPLES_LOG_FILE = '{}/{}-examples.log'.format(LOG_DIR, LOG_ENV)
DCOLUMNS_LOG_FILE = '{}/{}-dcolumn.log'.format(LOG_DIR, LOG_ENV)
LOGGING.get('handlers', {}).get(
'examples_file', {})['filename'] = EXAMPLES_LOG_FILE
LOGGING.get('handlers', {}).get(
'dcolumns_file', {})['filename'] = DCOLUMNS_LOG_FILE
LOGGING.get('loggers', {}).get('django.request', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('examples', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('dcolumns', {})['level'] = 'DEBUG'
|
Fix non-resolved errors throwing errors on click
|
package me.coley.recaf.ui.controls.text;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
import javafx.scene.text.Text;
import me.coley.recaf.util.struct.Pair;
import org.fxmisc.richtext.CodeArea;
/**
* Cell renderer.
*
* @author Matt
*/
public class ErrorCell extends ListCell<Pair<Integer, String>> {
private final CodeArea codeArea;
/**
* @param codeArea
* Code area containing the text with errors.
*/
public ErrorCell(CodeArea codeArea) {
this.codeArea = codeArea;
}
@Override
public void updateItem(Pair<Integer, String> item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
setText(item.getValue());
int index = item.getKey();
Node g = new Text(String.valueOf(index + 1));
g.getStyleClass().addAll("bold", "error-cell");
setGraphic(g);
// on-click: go to line
if(index >= 0) {
setOnMouseClicked(me -> {
codeArea.moveTo(index, 0);
codeArea.requestFollowCaret();
codeArea.requestFocus();
});
} else {
setText(getText() + "\n(Cannot resolve line number from error)");
}
}
}
}
|
package me.coley.recaf.ui.controls.text;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
import javafx.scene.text.Text;
import me.coley.recaf.util.struct.Pair;
import org.fxmisc.richtext.CodeArea;
/**
* Cell renderer.
*
* @author Matt
*/
public class ErrorCell extends ListCell<Pair<Integer, String>> {
private final CodeArea codeArea;
/**
* @param codeArea
* Code area containing the text with errors.
*/
public ErrorCell(CodeArea codeArea) {
this.codeArea = codeArea;
}
@Override
public void updateItem(Pair<Integer, String> item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
setText(item.getValue());
int index = item.getKey();
Node g = new Text(String.valueOf(index + 1));
g.getStyleClass().addAll("bold", "error-cell");
setGraphic(g);
// on-click: go to line
setOnMouseClicked(me -> {
codeArea.moveTo(index, 0);
codeArea.requestFollowCaret();
codeArea.requestFocus();
});
}
}
}
|
Update to use the spec command in the latest armstrong.dev
|
from armstrong.dev.tasks import *
from fabric.api import task
settings = {
'DEBUG': True,
'INSTALLED_APPS': (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'armstrong.core.arm_sections',
'armstrong.core.arm_sections.tests.arm_sections_support',
'lettuce.django',
'south',
'mptt',
),
'ROOT_URLCONF': 'armstrong.core.arm_sections.tests.arm_sections_support.urls',
'SITE_ID': 1,
}
full_name = "armstrong.core.arm_sections"
main_app = "arm_sections"
tested_apps = (main_app, )
|
from armstrong.dev.tasks import *
from d51.django.virtualenv.base import VirtualEnvironment
from fabric.api import task
settings = {
'DEBUG': True,
'INSTALLED_APPS': (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'armstrong.core.arm_sections',
'armstrong.core.arm_sections.tests.arm_sections_support',
'lettuce.django',
'south',
'mptt',
),
'ROOT_URLCONF': 'armstrong.core.arm_sections.tests.arm_sections_support.urls',
'SITE_ID': 1,
}
main_app = "arm_sections"
tested_apps = (main_app, )
@task
def lettuce(verbosity=4):
defaults = settings
defaults["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
},
}
v = VirtualEnvironment()
v.run(defaults)
v.call_command("syncdb", interactive=False)
v.call_command("harvest", apps='armstrong.core.arm_sections',
verbosity=verbosity)
|
Add fi:wikivoyage and sort by current article count
Fix also pycodestyle (former PEP8) E402 problem
Bug: T153470
Change-Id: Id9bc980c7a9cfb21063597a3d5eae11c31d8040c
|
# -*- coding: utf-8 -*-
"""Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
# The new wikivoyage family that is hosted at wikimedia
from __future__ import absolute_import, unicode_literals
from pywikibot import family
__version__ = '$Id$'
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
name = 'wikivoyage'
def __init__(self):
"""Constructor."""
self.languages_by_size = [
'en', 'de', 'fa', 'it', 'fr', 'ru', 'pl', 'nl', 'pt', 'fi', 'es',
'zh', 'he', 'vi', 'sv', 'el', 'ro', 'uk',
]
super(Family, self).__init__()
# Global bot allowed languages on
# https://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation
self.cross_allowed = ['es', 'ru', ]
|
# -*- coding: utf-8 -*-
"""Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
# The new wikivoyage family that is hosted at wikimedia
from pywikibot import family
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
name = 'wikivoyage'
def __init__(self):
"""Constructor."""
self.languages_by_size = [
'en', 'de', 'fa', 'it', 'fr', 'ru', 'pl', 'nl', 'pt', 'es', 'he',
'zh', 'vi', 'sv', 'el', 'ro', 'uk',
]
super(Family, self).__init__()
# Global bot allowed languages on
# https://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation
self.cross_allowed = ['es', 'ru', ]
|
Include parent layers object, to ease update
git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@1481 cb33b658-6c9e-41a7-9690-cba343611204
|
/**
*
*/
package org.mwc.cmap.plotViewer.actions;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.DebriefActionWrapper;
import MWC.GUI.PlainChart;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;
/**
* @author ian.mayo
*
*/
public class FitToWindow extends CoreEditorAction
{
protected void execute()
{
PlainChart theChart = getChart();
WorldArea oldArea = new WorldArea(theChart.getCanvas().getProjection().getVisibleDataArea());
Action theAction = new MWC.GUI.Tools.Chart.FitToWin.FitToWinAction(theChart, oldArea);
// and wrap it
DebriefActionWrapper daw = new DebriefActionWrapper(theAction, theChart.getLayers());
// and add it to the clipboard
CorePlugin.run(daw);
}
}
|
/**
*
*/
package org.mwc.cmap.plotViewer.actions;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.DebriefActionWrapper;
import MWC.GUI.PlainChart;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;
/**
* @author ian.mayo
*
*/
public class FitToWindow extends CoreEditorAction
{
protected void execute()
{
PlainChart theChart = getChart();
WorldArea oldArea = new WorldArea(theChart.getCanvas().getProjection().getVisibleDataArea());
Action theAction = new MWC.GUI.Tools.Chart.FitToWin.FitToWinAction(theChart, oldArea);
// and wrap it
DebriefActionWrapper daw = new DebriefActionWrapper(theAction, null);
// and add it to the clipboard
CorePlugin.run(daw);
}
}
|
Set links to open in new tab
|
import {Observable} from 'rx';
import {div, a, h2, h3, img} from '@cycle/dom';
import projects from '../data/projects';
function renderSidebar () {
return (
div('.sidebar', [
h2('Built with Cycle.js'),
img({src: 'http://cycle.js.org/img/cyclejs_logo.svg', alt: 'Cycle.js'})
])
);
}
function renderProject (project) {
return (
div('.project', [
a('.homepage', {href: project.homepage, target: '_blank'}, [
h3('.name', project.name)
]),
div('.description', project.description),
img({src: project.screenshot, alt: project.name})
])
);
}
function renderProjects (projects) {
return (
projects.map(renderProject)
);
}
export default function App ({DOM}) {
return {
DOM: Observable.just(
div('.built-with-cycle', [
renderSidebar(),
renderProjects(projects)
])
)
};
}
|
import {Observable} from 'rx';
import {div, a, h2, h3, img} from '@cycle/dom';
import projects from '../data/projects';
function renderSidebar () {
return (
div('.sidebar', [
h2('Built with Cycle.js'),
img({src: 'http://cycle.js.org/img/cyclejs_logo.svg', alt: 'Cycle.js'})
])
);
}
function renderProject (project) {
return (
div('.project', [
a('.homepage', {href: project.homepage}, [
h3('.name', project.name)
]),
div('.description', project.description),
img({src: project.screenshot, alt: project.name})
])
);
}
function renderProjects (projects) {
return (
projects.map(renderProject)
);
}
export default function App ({DOM}) {
return {
DOM: Observable.just(
div('.built-with-cycle', [
renderSidebar(),
renderProjects(projects)
])
)
};
}
|
Fix indentation in PHP example template, now uses 4 spaces consistently
|
```php
$client = new \GuzzleHttp\Client();
$response = $client->{{ strtolower($route['methods'][0]) }}(
'{{ rtrim($baseUrl, '/') . '/' . ltrim($route['boundUri'], '/') }}',
[
@if(!empty($route['headers']))
'headers' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['headers'], 8) !!},
@endif
@if(!empty($route['cleanQueryParameters']))
'query' => [
@foreach($route['cleanQueryParameters'] as $parameter => $value)
'{{$parameter}}' => '{{$value}}',
@endforeach
],
@endif
@if(!empty($route['cleanBodyParameters']))
'json' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['cleanBodyParameters'], 8) !!},
@endif
]
);
$body = $response->getBody();
print_r(json_decode((string) $body));
```
|
```php
$client = new \GuzzleHttp\Client();
$response = $client->{{ strtolower($route['methods'][0]) }}(
'{{ rtrim($baseUrl, '/') . '/' . ltrim($route['boundUri'], '/') }}',
[
@if(!empty($route['headers']))
'headers' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['headers'], 4) !!},
@endif
@if(!empty($route['cleanQueryParameters']))
'query' => [
@foreach($route['cleanQueryParameters'] as $parameter => $value)
'{{$parameter}}' => '{{$value}}',
@endforeach
],
@endif
@if(!empty($route['cleanBodyParameters']))
'json' => {!! \Mpociot\ApiDoc\Tools\Utils::printPhpValue($route['cleanBodyParameters'], 4) !!},
@endif
]
);
$body = $response->getBody();
print_r(json_decode((string) $body));
```
|
Send whole location object over websocket
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from flask import jsonify, Blueprint, abort, request
from .models import Location
from api.tokens.models import Token
from api.auth import requires_auth
from api import db, socketio
locations = Blueprint('locations', __name__)
@locations.route('/')
def all():
"""Get all locations"""
locations = Location.query.all()
locations = [location.serialize() for location in locations]
return jsonify(data=locations)
@locations.route('/<int:location_id>')
def status(location_id):
"""Get a location"""
location = Location.query.get(location_id)
if location:
return jsonify(data=location.serialize())
abort(404, 'Location {} not found.'.format(location_id))
@locations.route('/toggle', methods=['PUT'])
@requires_auth
def update():
"""Toggle the status of a location"""
hash = request.headers.get('authorization')
location = Location.query \
.join(Location.token) \
.filter_by(hash=hash) \
.first()
location.occupied = not location.occupied
db.session.commit()
socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws')
return jsonify(), 204
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from flask import jsonify, Blueprint, abort, request
from .models import Location
from api.tokens.models import Token
from api.auth import requires_auth
from api import db, socketio
locations = Blueprint('locations', __name__)
@locations.route('/')
def all():
"""Get all locations"""
locations = Location.query.all()
locations = [location.serialize() for location in locations]
return jsonify(data=locations)
@locations.route('/<int:location_id>')
def status(location_id):
"""Get a location"""
location = Location.query.get(location_id)
if location:
return jsonify(data=location.serialize())
abort(404, 'Location {} not found.'.format(location_id))
@locations.route('/toggle', methods=['PUT'])
@requires_auth
def update():
"""Toggle the status of a location"""
hash = request.headers.get('authorization')
location = Location.query \
.join(Location.token) \
.filter_by(hash=hash) \
.first()
location.occupied = not location.occupied
db.session.commit()
socketio.emit('location', {'occupied': location.occupied}, broadcast=True,
namespace='/ws')
return jsonify(), 204
|
Fix another use of the rbuilder postgres user
|
#!/usr/bin/python
#
# Copyright (c) 2009 rPath, Inc.
#
# All rights reserved.
#
import logging
from conary import dbstore
from mint.scripts.db2db import db2db
log = logging.getLogger(__name__)
def switchToPostgres(cfg):
if cfg.dbDriver in ('postgresql', 'pgpool'):
return
sourceTuple = (cfg.dbDriver, cfg.dbPath)
destTuple = ('postgresql', 'postgres@localhost:5439/mint')
finalTuple = ('pgpool', 'postgres@localhost.localdomain:6432/mint')
log.info("Migrating mint database from %s::%s to %s::%s",
*(sourceTuple + destTuple))
db2db.move_database(sourceTuple, destTuple)
# Update rbuilder-generated.conf
log.info("Changing configured mint database to %s::%s", *finalTuple)
cfg.dbDriver = finalTuple[0]
cfg.dbPath = finalTuple[1]
cfg.writeGeneratedConfig()
|
#!/usr/bin/python
#
# Copyright (c) 2009 rPath, Inc.
#
# All rights reserved.
#
import logging
from conary import dbstore
from mint.scripts.db2db import db2db
log = logging.getLogger(__name__)
def switchToPostgres(cfg):
if cfg.dbDriver in ('postgresql', 'pgpool'):
return
sourceTuple = (cfg.dbDriver, cfg.dbPath)
destTuple = ('postgresql', 'rbuilder@localhost:5439/mint')
finalTuple = ('pgpool', 'rbuilder@localhost.localdomain:6432/mint')
log.info("Migrating mint database from %s::%s to %s::%s",
*(sourceTuple + destTuple))
db2db.move_database(sourceTuple, destTuple)
# Update rbuilder-generated.conf
log.info("Changing configured mint database to %s::%s", *finalTuple)
cfg.dbDriver = finalTuple[0]
cfg.dbPath = finalTuple[1]
cfg.writeGeneratedConfig()
|
Add missing host field to Apple TV
|
"""Discover Apple TV media players."""
import ipaddress
from . import MDNSDiscoverable
# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
"""Add support for Apple TV devices."""
def __init__(self, nd):
super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')
def info_from_entry(self, entry):
"""Returns most important info from mDNS entries."""
props = entry.properties
info = {
'host': str(ipaddress.ip_address(entry.address)),
'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
'hsgid': props.get(b'hG').decode('utf-8')
}
return info
def get_info(self):
"""Get details from Apple TV instances."""
return [self.info_from_entry(entry) for entry in self.get_entries()]
|
"""Discover Apple TV media players."""
from . import MDNSDiscoverable
# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
"""Add support for Apple TV devices."""
def __init__(self, nd):
super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')
def info_from_entry(self, entry):
"""Returns most important info from mDNS entries."""
props = entry.properties
info = {
'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
'hsgid': props.get(b'hG').decode('utf-8')
}
return info
def get_info(self):
"""Get details from Apple TV instances."""
return [self.info_from_entry(entry) for entry in self.get_entries()]
|
Complete max subarray sum by DP
|
"""Leetcode 53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray
(containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using
the divide and conquer approach, which is more subtle.
"""
class SolutionDp(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
Maximum subarray sum by Kadane's algorithm.
"""
sums = [0] * len(nums)
sums[0] = nums[0]
max_sum = sums[0]
for i in range(1, len(sums)):
# Compute current max subarray sum before pos i.
sums[i] = max(sums[i - 1] + nums[i], nums[i])
# Track global max sum before pos i.
max_sum = max(max_sum, sums[i])
return max_sum
def main():
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
# Output: 6.
print SolutionDp().maxSubArray(nums)
if __name__ == '__main__':
main()
|
"""Leetcode 53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray
(containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using
the divide and conquer approach, which is more subtle.
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
pass
def main():
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
# Output: 6.
if __name__ == '__main__':
main()
|
Generalize controllers to abstract one
|
<?php
namespace EdpModuleLayouts;
class Module
{
public function onBootstrap($e)
{
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$config = $e->getApplication()->getServiceManager()->get('config');
if (isset($config['module_layouts'][$moduleNamespace])) {
$controller->layout($config['module_layouts'][$moduleNamespace]);
}
}, 100);
}
}
|
<?php
namespace EdpModuleLayouts;
class Module
{
public function onBootstrap($e)
{
$e->getApplication()->getEventManager()->getSharedManager()->attach(array('Zend\Mvc\Controller\AbstractRestfulController', 'Zend\Mvc\Controller\AbstractActionController'),
'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$config = $e->getApplication()->getServiceManager()->get('config');
if (isset($config['module_layouts'][$moduleNamespace])) {
$controller->layout($config['module_layouts'][$moduleNamespace]);
}
}, 100);
}
}
|
Use iOS cache instead of tmp
|
/**
* @title Open - cordova.plugins.bridge.open
* @overview Open documents with compatible apps.
* @copyright Β© 2014 cordova-bridge
* @license GPLv2
* @author Carlos Antonio
*/
var exec = require('cordova/exec');
/**
* open
*
* @param {String} args File URI
* @param {Function} success Success callback
* @param {Function} error Failure callback
*/
exports.open = function(uri, success, error) {
if (!uri || arguments.length === 0) return false;
function onSuccess(path) {
if (typeof success === 'function') success(path);
return path;
}
function onError(code) {
code = code || 0;
if (typeof error === 'function') error(code);
return code;
}
uri = encodeURI(uri);
function downloadAndOpen(url) {
var ft = new FileTransfer(),
ios = cordova.file.cacheDirectory,
ext = cordova.file.externalCacheDirectory,
dir = (ios) ? ios : ext,
name = url.substring(url.lastIndexOf('/') + 1),
path = dir + name;
ft.download(url, path,
function done(entry) {
var file = entry.toURL();
exec(onSuccess, onError, 'Open', 'open', [file]);
},
onError,
false
);
}
if (uri.match('http')) {
downloadAndOpen(uri);
} else {
exec(onSuccess, onError, 'Open', 'open', [uri]);
}
};
|
/**
* @title Open - cordova.plugins.bridge.open
* @overview Open documents with compatible apps.
* @copyright Β© 2014 cordova-bridge
* @license GPLv2
* @author Carlos Antonio
*/
var exec = require('cordova/exec');
/**
* open
*
* @param {String} args File URI
* @param {Function} success Success callback
* @param {Function} error Failure callback
*/
exports.open = function(uri, success, error) {
if (!uri || arguments.length === 0) return false;
function onSuccess(path) {
if (typeof success === 'function') success(path);
return path;
}
function onError(code) {
code = code || 0;
if (typeof error === 'function') error(code);
return code;
}
uri = encodeURI(uri);
function downloadAndOpen(url) {
var ft = new FileTransfer(),
tmp = cordova.file.tempDirectory,
ext = cordova.file.externalCacheDirectory,
dir = (tmp) ? tmp : ext,
name = url.substring(url.lastIndexOf('/') + 1),
path = dir + name;
ft.download(url, path,
function done(entry) {
var file = entry.toURL();
exec(onSuccess, onError, 'Open', 'open', [file]);
},
onError,
false
);
}
if (uri.match('http')) {
downloadAndOpen(uri);
} else {
exec(onSuccess, onError, 'Open', 'open', [uri]);
}
};
|
Change i18n angular filter to interpolate strings
|
/* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Indico is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/
var ndFilters = angular.module("ndFilters", []);
ndFilters.filter("i18n", function() {
return function(input) {
var str = $T.gettext(input);
if (arguments.length > 1) {
str = str.format.apply(str, [].slice.call(arguments, 1));
}
return str;
};
});
ndFilters.filter("range", function() {
return function(input, min, max) {
min = parseInt(min, 10) || 0;
max = parseInt(max, 10);
for (var i=min; i<=max; i++) {
input.push(i);
}
return input;
};
});
|
/* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Indico is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/
var ndFilters = angular.module("ndFilters", []);
ndFilters.filter("i18n", function() {
return function(input) {
return $T(input);
};
});
ndFilters.filter("range", function() {
return function(input, min, max) {
min = parseInt(min, 10) || 0;
max = parseInt(max, 10);
for (var i=min; i<=max; i++) {
input.push(i);
}
return input;
};
});
|
Fix reading field value to model
|
import $ from 'jquery'
import template from '../../lib/environment.html'
export default function EnvironmentController(model) {
const $element = $(template)
$element.find(":input[name='ot_version']").change(toolkitVersionChangeHandler).change()
$element.find(":input[name='formatter']").change(formatterHandler).change()
$element.find(":input[name='override_shell']").change(overrideShellHandler).change()
return {
$element: $element
}
function toolkitVersionChangeHandler(event) {
model.ot_version = $(event.target).val()
toggleByClass($(event.target), 'v')
}
function formatterHandler(event) {
model.configuration.formatter = $(event.target).val()
toggleByClass($(event.target), 'f')
}
function overrideShellHandler(event) {
model.configuration.override_shell = $(event.target).is(':checked')
}
function toggleByClass(p, prefix) {
const val = p.val()
p.find('option').each(function() {
const s = $(this).attr('value')
const c = "." + prefix + s.replace(/\./g, '_')
$(c).addClass('disabled').find(":input").attr('disabled', true)
})
p.find('option').each(function() {
const s = $(this).attr('value')
const c = "." + prefix + s.replace(/\./g, '_')
if(val === s) {
$(c).removeClass('disabled').find(":input").removeAttr('disabled')
}
})
}
}
|
import $ from 'jquery'
import template from '../../lib/environment.html'
export default function EnvironmentController(model) {
const $element = $(template)
$element.find(":input[name='ot_version']").change(toolkitVersionChangeHandler).change()
$element.find(":input[name='formatter']").change(formatterHandler).change()
$element.find(":input[name='override_shell']").change(overrideShellHandler).change()
return {
$element: $element
}
function toolkitVersionChangeHandler(event) {
model.ot_version = $(':input[name=ot_version]').val()
toggleByClass($(event.target), 'v')
}
function formatterHandler(event) {
model.configuration.formatter = $(':input[name=formatter]').val()
toggleByClass($(event.target), 'f')
}
function overrideShellHandler(event) {
model.configuration.override_shell = $(event.target).is(':checked')
}
function toggleByClass(p, prefix) {
const val = p.val()
p.find('option').each(function() {
const s = $(this).attr('value')
const c = "." + prefix + s.replace(/\./g, '_')
$(c).addClass('disabled').find(":input").attr('disabled', true)
})
p.find('option').each(function() {
const s = $(this).attr('value')
const c = "." + prefix + s.replace(/\./g, '_')
if(val === s) {
$(c).removeClass('disabled').find(":input").removeAttr('disabled')
}
})
}
}
|
Use placeholder variable to fix error
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* Handles requests through the browser ie at the live site
*/
class WebController extends Controller
{
public function viewLinks($teamSlug)
{
$teamName="HngX";
$teamId="Txjrd24";
//parse $teamId and $teamName from $teamSlug
if (isset($_GET["query"])) {
$query=$_GET["query"];
//$results=search($teamId, $query);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
} else {
//$results=getAllLinks($teamId);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
}
}
/** Retrieves all a team's links
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function getAllLinks($team)
{
}
/** Searches for a team's links matching a given search query
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function search($team, $queryString)
{
//parse query string
//perform search
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* Handles requests through the browser ie at the live site
*/
class WebController extends Controller
{
public function viewLinks($teamSlug)
{
//parse $teamId and $teamName from $teamSlug
if (isset($_GET["query"])) {
$query=$_GET["query"];
//$results=search($teamId, $query);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
} else {
//$results=getAllLinks($teamId);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
}
}
/** Retrieves all a team's links
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function getAllLinks($team)
{
}
/** Searches for a team's links matching a given search query
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function search($team, $queryString)
{
//parse query string
//perform search
}
}
|
Use correct param for defaultValue
|
import PreferenceGroup from './PreferenceGroup';
import ChoicePreference from './ChoicePreference';
/**
* Preferences for containers
*
* This will build all the preferences a container can possess e.g lifetime.
* Other preferences like icon, color and exit rules are conceivable
*/
export default class ContainerPreference extends PreferenceGroup {
constructor({name, label, description}) {
super({name, label, description, preferences: [], toggleable: false});
this._preferences.push(new ChoicePreference({
name: `${name}.lifetime`,
label: 'Lifetime',
description: 'How long this container will live',
choices: [
{
'name': 'forever',
'label': 'Forever',
'description': 'Container will always be present after creation',
},
{
'name': 'untilLastTab',
'label': 'Until last tab is closed',
'description': 'Closing the last tab in the container will destroy the container',
},
],
defaultValue: 'forever',
}));
}
}
ContainerPreference.TYPE = 'container';
|
import PreferenceGroup from './PreferenceGroup';
import ChoicePreference from './ChoicePreference';
/**
* Preferences for containers
*
* This will build all the preferences a container can possess e.g lifetime.
* Other preferences like icon, color and exit rules are conceivable
*/
export default class ContainerPreference extends PreferenceGroup {
constructor({name, label, description}) {
super({name, label, description, preferences: [], toggleable: false});
this._preferences.push(new ChoicePreference({
name: `${name}.lifetime`,
label: 'Lifetime',
description: 'How long this container will live',
choices: [
{
'name': 'forever',
'label': 'Forever',
'description': 'Container will always be present after creation',
},
{
'name': 'untilLastTab',
'label': 'Until last tab is closed',
'description': 'Closing the last tab in the container will destroy the container',
},
],
defaultChoice: 'forever',
}));
}
}
ContainerPreference.TYPE = 'container';
|
Add fix for connection errors on localhost. Probably could be fixed by a setting in cURL but this works for now
|
<?php
/**
* Do not edit this file. Edit the config files found in the ../config/ dir instead.
* This file is required in the root directory so WordPress can find it.
* WP is hardcoded to look in its own directory or one directory up for wp-config.php.
*/
$host_config_dir = dirname(__FILE__) . '/../config/';
$host_config_file = $host_config_dir . preg_replace("/[^a-z0-9]+/", "-", strtolower($_SERVER['HTTP_HOST'])) . ".php";
$defaults_file = $host_config_dir . "defaults.php";
/** Include the host-specific config file if it exists. */
if (file_exists($host_config_file))
require_once($host_config_file);
/** Include the default fallbacks file. */
if (file_exists($defaults_file))
require_once($defaults_file);
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
/** Fix for connection errors on localhost. */
if( WP_ENV == 'development' ) {
add_filter( 'http_api_transports', function() {
return array( 'streams' );
});
}
|
<?php
/**
* Do not edit this file. Edit the config files found in the ../config/ dir instead.
* This file is required in the root directory so WordPress can find it.
* WP is hardcoded to look in its own directory or one directory up for wp-config.php.
*/
$host_config_dir = dirname(__FILE__) . '/../config/';
$host_config_file = $host_config_dir . preg_replace("/[^a-z0-9]+/", "-", strtolower($_SERVER['HTTP_HOST'])) . ".php";
$defaults_file = $host_config_dir . "defaults.php";
/** Include the host-specific config file if it exists. */
if (file_exists($host_config_file))
require_once($host_config_file);
/** Include the default fallbacks file. */
if (file_exists($defaults_file))
require_once($defaults_file);
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
|
Check if mt is None before spliting it
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2020-02-28 17:30
from __future__ import unicode_literals
from django.db import migrations
import mimetypes
def forward(apps, schema_editor):
AttachmentModel = apps.get_model('common', 'Attachment')
for attachment in AttachmentModel.objects.all():
mt = mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0]
if mt is not None and mt.split('/')[0].startswith('image'):
attachment.is_image = True
attachment.save()
class Migration(migrations.Migration):
dependencies = [
('common', '0010_attachment_is_image'),
]
operations = [
migrations.RunPython(forward),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2020-02-28 17:30
from __future__ import unicode_literals
from django.db import migrations
import mimetypes
def forward(apps, schema_editor):
AttachmentModel = apps.get_model('common', 'Attachment')
for attachment in AttachmentModel.objects.all():
if mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0].split('/')[0].startswith('image'):
attachment.is_image = True
attachment.save()
class Migration(migrations.Migration):
dependencies = [
('common', '0010_attachment_is_image'),
]
operations = [
migrations.RunPython(forward),
]
|
Add authSecret to config vars
|
var log = require('../lib/logger');
var allTheSettings = {
coinbaseApiKey: process.env.COINBASE_API_KEY,
coinbaseApiSec: process.env.COINBASE_API_SECRET,
coinbaseApiUri: process.env.COINBASE_API_URI,
coinbaseApiWallet: process.env.COINBASE_API_WALLET,
dbDb: process.env.DATABASE_DB,
dbHost: process.env.DATABASE_HOST,
dbPass: process.env.DATABASE_PASS,
dbUrl: process.env.DATABASE_URL,
dbUser: process.env.DATABASE_USER,
redisUrl: process.env.REDIS_URL,
secret: process.env.SECRET,
mailerUser: process.env.MG_USER,
mailerPass: process.env.MG_PASS,
authSecret: process.env.AUTH_SECRET
};
try {
var overrides = require('./configOverrides.js');
log.debug("Found overrides for", Object.keys(overrides));
for (var prop in overrides) {
if (overrides.hasOwnProperty(prop)) {
if (allTheSettings[prop]) {
allTheSettings[prop] = overrides[prop];
}
}
}
} catch (e) {
// if no override file is found
log.debug("no overrides found, reverting to env vars");
}
module.exports = allTheSettings;
|
var log = require('../lib/logger');
var allTheSettings = {
coinbaseApiKey: process.env.COINBASE_API_KEY,
coinbaseApiSec: process.env.COINBASE_API_SECRET,
coinbaseApiUri: process.env.COINBASE_API_URI,
coinbaseApiWallet: process.env.COINBASE_API_WALLET,
dbDb: process.env.DATABASE_DB,
dbHost: process.env.DATABASE_HOST,
dbPass: process.env.DATABASE_PASS,
dbUrl: process.env.DATABASE_URL,
dbUser: process.env.DATABASE_USER,
redisUrl: process.env.REDIS_URL,
secret: process.env.SECRET,
mailerUser: process.env.MG_USER,
mailerPass: process.env.MG_PASS
};
try {
var overrides = require('./configOverrides.js');
log.debug("Found overrides for", Object.keys(overrides));
for (var prop in overrides) {
if (overrides.hasOwnProperty(prop)) {
if (allTheSettings[prop]) {
allTheSettings[prop] = overrides[prop];
}
}
}
} catch (e) {
// if no override file is found
log.debug("no overrides found, reverting to env vars");
}
module.exports = allTheSettings;
|
Fix showing Cluster Template info on Cluster details
Cluster details view doesn't show Cluster Template
information. This patch fixes it.
Change-Id: I4eccda8cdd125f12bd536a3e7af670f1930ca884
Closes-Bug: #1624275
|
/*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
"use strict";
angular
.module('horizon.dashboard.container-infra.clusters')
.controller('ClusterOverviewController', ClusterOverviewController);
ClusterOverviewController.$inject = [
'$scope',
'horizon.app.core.openstack-service-api.magnum'
];
function ClusterOverviewController(
$scope,
magnum
) {
var ctrl = this;
ctrl.cluster = {};
ctrl.cluster_template = {};
$scope.context.loadPromise.then(onGetCluster);
function onGetCluster(cluster) {
ctrl.cluster = cluster.data;
magnum.getClusterTemplate(ctrl.cluster.cluster_template_id).success(onGetClusterTemplate);
}
function onGetClusterTemplate(clusterTemplate) {
ctrl.cluster_template = clusterTemplate;
}
}
})();
|
/*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
"use strict";
angular
.module('horizon.dashboard.container-infra.clusters')
.controller('ClusterOverviewController', ClusterOverviewController);
ClusterOverviewController.$inject = [
'$scope',
'horizon.app.core.openstack-service-api.magnum'
];
function ClusterOverviewController(
$scope,
magnum
) {
var ctrl = this;
ctrl.cluster = {};
ctrl.cluster_template = {};
$scope.context.loadPromise.then(onGetCluster);
function onGetCluster(cluster) {
ctrl.cluster = cluster.data;
magnum.getClusterTemplate(ctrl.cluster.cluster_template_id).success(onGetClusterTemplate);
}
function onGetClusterTemplate(clusteTemplate) {
ctrl.clusteTemplate = clusteTemplate;
}
}
})();
|
Add pre-release git paver task
|
from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
|
from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
|
Add trove classifier for license
The trove classifiers are listed on PyPI to help users know -- at a
glance -- what license the project uses. Helps users decide if the
library is appropriate for integration. A full list of available trove
classifiers can be found at:
https://pypi.org/pypi?%3Aaction=list_classifiers
The setuptools "license" argument is not intended to use trove
classifier notation. Simplify it to "MIT". Details can be found:
https://docs.python.org/3/distutils/setupscript.html#additional-meta-data
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import toml
with open("README.rst") as readme_file:
readme_string = readme_file.read()
setup(
name="toml",
version=toml.__version__,
description="Python Library for Tom's Obvious, Minimal Language",
author="Uiri Noyb",
author_email="uiri@xqz.ca",
url="https://github.com/uiri/toml",
packages=['toml'],
license="MIT",
long_description=readme_string,
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6']
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import toml
with open("README.rst") as readme_file:
readme_string = readme_file.read()
setup(
name="toml",
version=toml.__version__,
description="Python Library for Tom's Obvious, Minimal Language",
author="Uiri Noyb",
author_email="uiri@xqz.ca",
url="https://github.com/uiri/toml",
packages=['toml'],
license="License :: OSI Approved :: MIT License",
long_description=readme_string,
classifiers=[
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6']
)
|
Add processor (copy) implementation for tests
|
package imageserver
import (
"errors"
"testing"
)
type size struct {
width int
height int
}
type providerSize struct{}
func (provider *providerSize) Get(source interface{}, parameters Parameters) (*Image, error) {
size, ok := source.(size)
if !ok {
return nil, errors.New("Source is not a size")
}
return CreateImage(size.width, size.height), nil
}
type processorCopy struct{}
func (processor *processorCopy) Process(image *Image, parameters Parameters) (*Image, error) {
data := make([]byte, len(image.Data))
copy(image.Data, data)
return &Image{
Type: image.Type,
Data: data,
},
nil
}
func TestServerGet(t *testing.T) {
_, err := createServer().Get(Parameters{
"source": size{
width: 500,
height: 400,
},
})
if err != nil {
t.Fatal(err)
}
}
func TestServerGetErrorMissingSource(t *testing.T) {
parameters := make(Parameters)
_, err := createServer().Get(parameters)
if err == nil {
t.Fatal("No error")
}
}
func createServer() *Server {
return &Server{
Provider: new(providerSize),
Processor: new(processorCopy),
}
}
|
package imageserver
import (
"errors"
"testing"
)
type size struct {
width int
height int
}
type providerSize struct{}
func (provider *providerSize) Get(source interface{}, parameters Parameters) (*Image, error) {
size, ok := source.(size)
if !ok {
return nil, errors.New("Source is not a size")
}
return CreateImage(size.width, size.height), nil
}
func TestServerGet(t *testing.T) {
_, err := createServer().Get(Parameters{
"source": size{
width: 500,
height: 400,
},
})
if err != nil {
t.Fatal(err)
}
}
func TestServerGetErrorMissingSource(t *testing.T) {
parameters := make(Parameters)
_, err := createServer().Get(parameters)
if err == nil {
t.Fatal("No error")
}
}
func createServer() *Server {
return &Server{
Provider: new(providerSize),
}
}
|
Add json module as fallback for simplejson
|
import requests
try:
import simplejson as json
except ImportError:
import json
def getbaseurl(service='search', version='1', method='track',
format='json'):
"""Returns the base URL for a Spotify Web API query"""
baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}"
return baseurl.format(service, version, method, format)
def search(terms, method='track'):
if hasattr(terms, '__iter__'):
sterms = ' '.join(terms)
else:
sterms = terms
base = getbaseurl(method=method)
r = requests.get(base, params={'q': sterms})
if r.status_code != requests.codes.ok:
raise NotImplementedException("There was some problem. Exception"
"not defined yet")
data = r.json()
return data
|
import requests
import simplejson as json
def getbaseurl(service='search', version='1', method='track',
format='json'):
"""Returns the base URL for a Spotify Web API query"""
baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}"
return baseurl.format(service, version, method, format)
def search(terms, method='track'):
if hasattr(terms, '__iter__'):
sterms = ' '.join(terms)
else:
sterms = terms
base = getbaseurl(method=method)
r = requests.get(base, params={'q': sterms})
if r.status_code != requests.codes.ok:
raise NotImplementedException("There was some problem. Exception"
"not defined yet")
data = r.json()
return data
|
Build process now has source maps enabled.
|
//
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
// Emit 'end' as the stream wouldn't do it itself.
// Without this, the gulp task won't end and the watch stops working.
this.emit('end');
}
gulp.task('libs', function () {
return browserify({debug: true})
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js', {debug: true})
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
});
gulp.task('default', ['libs', 'scripts', 'watch']);
|
//
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
//var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
this.emit('end');
}
gulp.task('libs', function () {
return browserify()
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js')
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
});
gulp.task('default', ['libs', 'scripts', 'watch']);
|
Fix date issue and remove lower rule from output.
|
var content = jQuery('#content');
var grafs = content.text().split('\n\n');
var cx_date = new Date();
var monthNames = ["Jan. ","Feb. ","March ","April ","May ","June ","July ","Aug. ","Sept. ","Oct. ","Nov.","Dec. "];
var cx_month = monthNames[cx_date.getMonth()];
var amPm = ( cx_date.getHours() < 12 ) ? ' a.m.' : ' p.m.';
var cx_date_markup = cx_month + cx_date.getDate() + ', ' + cx_date.getFullYear() + ' at ' + cx_date.getHours() + ':' + cx_date.getMinutes() + amPm;
var cx_content = prompt('Type or paste the correction language here. The Update date and time and all other formatting will be included automatically.\n\n', '');
var markup = '<hr />\n\n\
<strong>Updated ' + cx_date_markup + '</strong> <em>' + cx_content + '</em>';
grafs.splice(grafs.length, 0, markup);
jQuery('#content').text(grafs.join('\n\n'));
|
var content = jQuery('#content');
var grafs = content.text().split('\n\n');
var cx_date = new Date();
var monthNames = ["Jan. ","Feb. ","March ","April ","May ","June ","July ","Aug. ","Sept. ","Oct. ","Nov.","Dec. "];
var cx_month = monthNames[cx_date.getMonth()];
var amPm = ( cx_date.getHours() < 12 ) ? ' a.m.' : ' p.m.';
var cx_date_markup = cx_month + cx_date.getDay() + ', ' + cx_date.getFullYear() + ' at ' + cx_date.getHours() + ':' + cx_date.getMinutes() + amPm;
var cx_content = prompt('Type or paste the correction language here. The Update date and time and all other formatting will be included automatically.\n\n', '');
var markup = '<hr />\n\n\
<strong>Updated ' + cx_date_markup + '</strong> <em>' + cx_content + '</em>\n\n\
<hr />';
grafs.splice(grafs.length, 0, markup);
jQuery('#content').text(grafs.join('\n\n'));
|
Use local upload for release
|
"""Utiltiy functions for workign on the NinaPro Databases (1 & 2)."""
from setuptools import setup, find_packages
setup(name='nina_helper',
version='2.2',
description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)',
author='Lif3line',
author_email='adamhartwell2@gmail.com',
license='MIT',
packages=find_packages(),
url='https://github.com/Lif3line/nina_helper_package_mk2', # use the URL to the github repo
# download_url='https://github.com/Lif3line/nina_helper_package_mk2/archive/2.2.tar.gz', # Hack github address
install_requires=[
'scipy',
'sklearn',
'numpy'
],
keywords='ninapro emg')
|
"""Utiltiy functions for workign on the NinaPro Databases (1 & 2)."""
from setuptools import setup, find_packages
setup(name='nina_helper',
version='2.1',
description='Utiltiy functions for workign on the NinaPro Databases (1 & 2)',
author='Lif3line',
author_email='adamhartwell2@gmail.com',
license='MIT',
packages=find_packages(),
url='https://github.com/Lif3line/nina_helper_package_mk2', # use the URL to the github repo
download_url='https://github.com/Lif3line/nina_helper_package_mk2/archive/2.1.tar.gz', # Hack github address
install_requires=[
'os',
'scipy',
'sklearn',
'itertools',
'numpy'
],
keywords='ninapro emg')
|
Handle invalid dates only as well
|
<?php
namespace Speicher210\Fastbill\Api\Serializer\Handler;
use JMS\Serializer\Context;
use JMS\Serializer\Handler\DateHandler as JMSDateHandler;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\VisitorInterface;
class DateHandler extends JMSDateHandler
{
/**
* {@inheritdoc}
*/
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context)
{
// All dates send to Fastbill should be in Europe/Berlin timezone.
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
return parent::serializeDateTime($visitor, $date, $type, $context);
}
/**
* {@inheritdoc}
*/
public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type)
{
// Handle empty or invalid date / datetime values.
if ('' === $data || null === $data || strpos($data, '0000-00-00') !== false) {
return null;
}
// We want to always show the response in the UTC timezone.
$dateTime = parent::deserializeDateTimeFromJson($visitor, $data, $type);
if ($dateTime instanceof \DateTime) {
$dateTime->setTimezone(new \DateTimeZone('UTC'));
}
return $dateTime;
}
}
|
<?php
namespace Speicher210\Fastbill\Api\Serializer\Handler;
use JMS\Serializer\Context;
use JMS\Serializer\Handler\DateHandler as JMSDateHandler;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\VisitorInterface;
class DateHandler extends JMSDateHandler
{
/**
* {@inheritdoc}
*/
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context)
{
// All dates send to Fastbill should be in Europe/Berlin timezone.
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
return parent::serializeDateTime($visitor, $date, $type, $context);
}
/**
* {@inheritdoc}
*/
public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type)
{
if ('' === $data || null === $data || '0000-00-00 00:00:00' === $data) {
return null;
}
// We want to always show the response in the UTC timezone.
$dateTime = parent::deserializeDateTimeFromJson($visitor, $data, $type);
if ($dateTime instanceof \DateTime) {
$dateTime->setTimezone(new \DateTimeZone('UTC'));
}
return $dateTime;
}
}
|
[FIX] event: Set default value for event_count
Fixes https://github.com/odoo/odoo/pull/39583
This commit adds a default value for event_count
Assigning default value for non-stored compute fields is required in 13.0
closes odoo/odoo#39974
X-original-commit: 9ca72b98f54d7686c0e6019870b40f14dbdd2881
Signed-off-by: Victor Feyens (vfe) <433cda6c0f0b5b2dac2ef769109a6da90db60157@odoo.com>
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has participated.")
def _compute_event_count(self):
self.event_count = 0
if not self.user_has_groups('event.group_event_user'):
return
for partner in self:
partner.event_count = self.env['event.event'].search_count([('registration_ids.partner_id', 'child_of', partner.ids)])
def action_event_view(self):
action = self.env.ref('event.action_event_view').read()[0]
action['context'] = {}
action['domain'] = [('registration_ids.partner_id', 'child_of', self.ids)]
return action
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has participated.")
def _compute_event_count(self):
if not self.user_has_groups('event.group_event_user'):
return
for partner in self:
partner.event_count = self.env['event.event'].search_count([('registration_ids.partner_id', 'child_of', partner.ids)])
def action_event_view(self):
action = self.env.ref('event.action_event_view').read()[0]
action['context'] = {}
action['domain'] = [('registration_ids.partner_id', 'child_of', self.ids)]
return action
|
Make it compatible with node 4.0
|
'use strict';
var OCL = require('openchemlib');
module.exports = function getConnectivityMatrix(options) {
var options = options || {};
var sdt=options.sdt;
var mass=options.mass;
this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours);
var nbAtoms=this.getAllAtoms();
var result=new Array(nbAtoms);
for (var i=0; i<nbAtoms; i++) {
result[i]=new Array(nbAtoms).fill(0);
result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1;
}
for (var i=0; i<nbAtoms; i++) {
for (var j=0; j<this.getAllConnAtoms(i); j++) {
result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1;
}
}
return result;
}
|
'use strict';
var OCL = require('openchemlib');
module.exports = function getConnectivityMatrix(options={}) {
var {
sdt,
mass
} = options;
this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours);
var nbAtoms=this.getAllAtoms();
var result=new Array(nbAtoms);
for (var i=0; i<nbAtoms; i++) {
result[i]=new Array(nbAtoms).fill(0);
result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1;
}
for (var i=0; i<nbAtoms; i++) {
for (var j=0; j<this.getAllConnAtoms(i); j++) {
result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1;
}
}
return result;
}
|
Fix a buggy url conf for heroku.
|
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
|
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
|
Switch to store GMT dates.
|
<?php
//This should be run on cron.
include_once('config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$timeNow = gmdate("Y-m-d H:i:s");
$saved = 0;
foreach( ['yes','limited','no','unknown'] as $wheelchair_filter ){
$json = json_decode(file_get_contents("https://wheelmap.org/api/nodes?api_key=$wheelmap_api_key&bbox=-2.413769,51.363902,-2.310473,51.415048&wheelchair=$wheelchair_filter"), true);
$item_count = $json['meta']['item_count_total'];
$success = $mysqli->query("INSERT INTO venue_counts (`category`,`wheelchair`,`time`,`count`) VALUES ('0','$wheelchair_filter','$timeNow','$item_count')");
if( !$success ){
die( $mysqli->error );
}
else{
$saved++;
}
}
echo "Saved $saved rows to DB.";
|
<?php
//This should be run on cron.
include_once('config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$timeNow = date("Y-m-d H:i:s");
$saved = 0;
foreach( ['yes','limited','no','unknown'] as $wheelchair_filter ){
$json = json_decode(file_get_contents("https://wheelmap.org/api/nodes?api_key=$wheelmap_api_key&bbox=-2.413769,51.363902,-2.310473,51.415048&wheelchair=$wheelchair_filter"), true);
$item_count = $json['meta']['item_count_total'];
$success = $mysqli->query("INSERT INTO venue_counts (`category`,`wheelchair`,`time`,`count`) VALUES ('0','$wheelchair_filter','$timeNow','$item_count')");
if( !$success ){
die( $mysqli->error );
}
else{
$saved++;
}
}
echo "Saved $saved rows to DB.";
|
Add a column in the search index for the list of projects.
|
import datetime
from haystack import indexes
from haystack import site
import mysite.profile.models
from django.db.models import Q
class PersonIndex(indexes.SearchIndex):
null_document = indexes.CharField(document=True)
all_tag_texts = indexes.MultiValueField()
all_public_projects_exact = indexes.MultiValueField()
def prepare_null_document(self, person_instance):
return '' # lollerskates
def prepare_all_tag_texts(self, person_instance):
return person_instance.get_tag_texts_for_map()
def prepare_all_public_projects_exact(self, person_instance):
return list(person_instance.get_list_of_project_names())
def get_queryset(self):
everybody = mysite.profile.models.Person.objects.all()
mappable_filter = ( ~Q(location_display_name='') &
Q(location_confirmed=True) )
return everybody.filter(mappable_filter)
site.register(mysite.profile.models.Person, PersonIndex)
|
import datetime
from haystack import indexes
from haystack import site
import mysite.profile.models
from django.db.models import Q
class PersonIndex(indexes.SearchIndex):
null_document = indexes.CharField(document=True)
all_tag_texts = indexes.MultiValueField()
def prepare_null_document(self, person_instance):
return '' # lollerskates
def prepare_all_tag_texts(self, person_instance):
return person_instance.get_tag_texts_for_map()
def get_queryset(self):
everybody = mysite.profile.models.Person.objects.all()
mappable_filter = ( ~Q(location_display_name='') &
Q(location_confirmed=True) )
return everybody.filter(mappable_filter)
site.register(mysite.profile.models.Person, PersonIndex)
|
Fix unicode error in subsection
|
"""
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration.middleware import MicrositeConfiguration
register = template.Library()
def page_title_breadcrumbs(*crumbs, **kwargs):
"""
This function creates a suitable page title in the form:
Specific | Less Specific | General | edX
It will output the correct platform name for the request.
Pass in a `separator` kwarg to override the default of " | "
"""
separator = kwargs.get("separator", " | ")
if crumbs:
return u'{}{}{}'.format(separator.join(crumbs), separator, platform_name())
else:
return platform_name()
@register.simple_tag(name="page_title_breadcrumbs", takes_context=True)
def page_title_breadcrumbs_tag(context, *crumbs):
"""
Django template that creates breadcrumbs for page titles:
{% page_title_breadcrumbs "Specific" "Less Specific" General %}
"""
return page_title_breadcrumbs(*crumbs)
@register.simple_tag(name="platform_name")
def platform_name():
"""
Django template tag that outputs the current platform name:
{% platform_name %}
"""
return MicrositeConfiguration.get_microsite_configuration_value('platform_name', settings.PLATFORM_NAME)
|
"""
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration.middleware import MicrositeConfiguration
register = template.Library()
def page_title_breadcrumbs(*crumbs, **kwargs):
"""
This function creates a suitable page title in the form:
Specific | Less Specific | General | edX
It will output the correct platform name for the request.
Pass in a `separator` kwarg to override the default of " | "
"""
separator = kwargs.get("separator", " | ")
if crumbs:
return '{}{}{}'.format(separator.join(crumbs), separator, platform_name())
else:
return platform_name()
@register.simple_tag(name="page_title_breadcrumbs", takes_context=True)
def page_title_breadcrumbs_tag(context, *crumbs):
"""
Django template that creates breadcrumbs for page titles:
{% page_title_breadcrumbs "Specific" "Less Specific" General %}
"""
return page_title_breadcrumbs(*crumbs)
@register.simple_tag(name="platform_name")
def platform_name():
"""
Django template tag that outputs the current platform name:
{% platform_name %}
"""
return MicrositeConfiguration.get_microsite_configuration_value('platform_name', settings.PLATFORM_NAME)
|
Make the called command to lowercase
|
package me.duncte123.skybot.utils;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.util.Arrays;
public class CommandParser {
public CommandContainer parse(String rw, MessageReceivedEvent e){
final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).split(" ");
final String invoke = split[0].toLowerCase();
final String[] args = Arrays.copyOfRange(split, 1, split.length);
return new CommandContainer(invoke, args, e);
}
public class CommandContainer {
public final String invoke;
public final String[] args;
public final MessageReceivedEvent event;
public CommandContainer(String invoke, String[] args, MessageReceivedEvent e){
this.invoke = invoke;
this.args = args;
this.event = e;
}
}
}
|
package me.duncte123.skybot.utils;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.util.Arrays;
public class CommandParser {
public CommandContainer parse(String rw, MessageReceivedEvent e){
final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).split(" ");
final String invoke = split[0];
final String[] args = Arrays.copyOfRange(split, 1, split.length);
return new CommandContainer(invoke, args, e);
}
public class CommandContainer {
public final String invoke;
public final String[] args;
public final MessageReceivedEvent event;
public CommandContainer(String invoke, String[] args, MessageReceivedEvent e){
this.invoke = invoke;
this.args = args;
this.event = e;
}
}
}
|
Complete a condition curly braces
|
<?php
class ModelPaymentOmiseOffsite extends Model {
public function getMethod($address, $total) {
if ($this->config->get('omise_status') != 1) {
return false;
}
$this->load->language('payment/omise_offsite');
if ($this->config->get('omise_offsite_payment_title') != "") {
$payment_title = $this->config->get('omise_offsite_payment_title');
} else {
$payment_title = $this->language->get('text_title');
}
return array(
'code' => 'omise_offsite',
'title' => $payment_title,
'terms' => '',
'sort_order' => $this->config->get('omise_offsite_sort_order')
);
}
}
|
<?php
class ModelPaymentOmiseOffsite extends Model {
public function getMethod($address, $total) {
if ($this->config->get('omise_status') != 1) {
return false;
}
$this->load->language('payment/omise_offsite');
if ($this->config->get('omise_offsite_payment_title') != "")
$payment_title = $this->config->get('omise_offsite_payment_title');
else
$payment_title = $this->language->get('text_title');
return array(
'code' => 'omise_offsite',
'title' => $payment_title,
'terms' => '',
'sort_order' => $this->config->get('omise_offsite_sort_order')
);
}
}
|
Return empty row, fixes bug when there are no skins
|
(function() {
exports.getEmptyRow = function() {
var row = Ti.UI.createTableViewRow({
editable: false,
isPlaceholder: true,
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY
});
var lbl_title = Ti.UI.createLabel({
text: I('main.noContent.title'),
font: {
fontWeight: 'bold',
fontSize: 17
},
top: 7,
left: 10,
right: 10,
width: Ti.UI.SIZE,
height: Ti.UI.SIZE
});
row.add(lbl_title);
var lbl_help = Ti.UI.createLabel({
text: I('main.noContent.help'),
top: 35,
bottom: 10,
left: 10,
right: 10,
font: {
fontSize: 15
},
height: Ti.UI.SIZE,
width: Ti.UI.FILL
});
row.add(lbl_help);
return row;
}
})();
|
(function() {
exports.getEmptyRow = function() {
var row = Ti.UI.createTableViewRow({
editable: false,
isPlaceholder: true,
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY
});
var lbl_title = Ti.UI.createLabel({
text: I('main.noContent.title'),
font: {
fontWeight: 'bold',
fontSize: 17
},
top: 7,
left: 10,
right: 10,
width: Ti.UI.SIZE,
height: Ti.UI.SIZE
});
row.add(lbl_title);
var lbl_help = Ti.UI.createLabel({
text: I('main.noContent.help'),
top: 35,
bottom: 10,
left: 10,
right: 10,
font: {
fontSize: 15
},
height: Ti.UI.SIZE,
width: Ti.UI.FILL
});
row.add(lbl_help);
}
})();
|
Allow lasers to damage cryopods
|
package com.ezardlabs.lostsector.objects.projectiles;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.objects.Entity;
public class Laser extends Script {
private final int damage;
public Laser(int damage) {
this.damage = damage;
}
@Override
public void start() {
gameObject.setTag("projectile");
}
@Override
public void update() {
transform.translate(gameObject.transform.scale.x * 15, 0);
if (transform.position.x <= 0) GameObject.destroy(gameObject);
}
@Override
public void onTriggerEnter(Collider other) {
if (other.gameObject.getTag() != null) {
if ("player".equals(other.gameObject.getTag()) || "cryopod".equals(other.gameObject.getTag())) {
//noinspection ConstantConditions
other.gameObject.getComponentOfType(Entity.class)
.applyDamage(damage, DamageType.NORMAL, transform.position);
gameObject.removeComponent(Collider.class);
GameObject.destroy(gameObject);
} else if (other.gameObject.getTag().equals("solid")) {
gameObject.removeComponent(Collider.class);
GameObject.destroy(gameObject);
}
}
}
}
|
package com.ezardlabs.lostsector.objects.projectiles;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.objects.Entity;
public class Laser extends Script {
private final int damage;
public Laser(int damage) {
this.damage = damage;
}
@Override
public void start() {
gameObject.setTag("projectile");
}
@Override
public void update() {
transform.translate(gameObject.transform.scale.x * 15, 0);
if (transform.position.x <= 0) GameObject.destroy(gameObject);
}
@Override
public void onTriggerEnter(Collider other) {
if (other.gameObject.getTag() != null) {
if (other.gameObject.getTag().equals("player")) {
//noinspection ConstantConditions
other.gameObject.getComponentOfType(Entity.class)
.applyDamage(damage, DamageType.NORMAL,
transform.position);
gameObject.removeComponent(Collider.class);
GameObject.destroy(gameObject);
} else if (other.gameObject.getTag().equals("solid")) {
gameObject.removeComponent(Collider.class);
GameObject.destroy(gameObject);
}
}
}
}
|
Refactor change βvarβ statement to βconstβ
|
import setCurrentScreenAction from "src/actions/ScreenActions.js";
import { SET_CURRENT_SCREEN, MENU_SCREEN,
GAME_SCREEN} from "src/actions/ScreenActions.js";
describe("Screen Actions", () => {
it("should exist", () => {
setCurrentScreenAction.should.exist;
});
it("should be a function", () => {
setCurrentScreenAction.should.be.function;
});
it("should create action of type SET_CURRENT_SCREEN", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
action.type.should.be.equal(SET_CURRENT_SCREEN);
});
it("should have parameter screen equal to function argument", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
const setMenuScreenAction = {
screen: MENU_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setMenuScreenAction);
action = setCurrentScreenAction(GAME_SCREEN);
const setGameScreenAction = {
screen: GAME_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setGameScreenAction);
});
});
|
import setCurrentScreenAction from "src/actions/ScreenActions.js";
import { SET_CURRENT_SCREEN, MENU_SCREEN,
GAME_SCREEN} from "src/actions/ScreenActions.js";
describe("Screen Actions", () => {
it("should exist", () => {
setCurrentScreenAction.should.exist;
});
it("should be a function", () => {
setCurrentScreenAction.should.be.function;
});
it("should create action of type SET_CURRENT_SCREEN", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
action.type.should.be.equal(SET_CURRENT_SCREEN);
});
it("should have parameter screen equal to function argument", () => {
var action = setCurrentScreenAction(MENU_SCREEN);
const setMenuScreenAction = {
screen: MENU_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setMenuScreenAction);
action = setCurrentScreenAction(GAME_SCREEN);
const setGameScreenAction = {
screen: GAME_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setGameScreenAction);
});
});
|
Change dummy video in video section
|
import React from 'react';
import styles from './videosection.css'
export default class VideoSection extends React.Component {
render() {
return (
<div className="wrapper style3 video-section">
<div className="row title">
<h1>About Rojak</h1>
</div>
<div className="row description">
<p>Watch this video to understand more about Rojak</p>
</div>
<div className="video-thumbnail">
<div className="container-video">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src="https://www.youtube.com/embed/3tmd-ClpJxA"></iframe>
</div>
</div>
</div>
</div>
);
}
}
|
import React from 'react';
import styles from './videosection.css'
export default class VideoSection extends React.Component {
render() {
return (
<div className="wrapper style3 video-section">
<div className="row title">
<h1>About Rojak</h1>
</div>
<div className="row description">
<p>Watch this video to understand more about Rojak</p>
</div>
<div className="video-thumbnail">
<div className="container-video">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src="https://www.youtube.com/embed/UtjFu8c_goE"></iframe>
</div>
</div>
</div>
</div>
);
}
}
|
Remove requirement on python > 2.7
|
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
The MIT License (MIT)
Copyright (c) 2014 Jarl Stefansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# Prepare for deprication of versions < 2.7
#from __future__ import print_function # This API requires Python 2.7 or more recent
#import sys
#if sys.version < "2.7.0":
# print("listen requires Python 2.7 or more recent")
# sys.exit(1)
from listen.signal_handler import SignalHandler
__all__ = ["listen"]
__version__ = "0.1.1"
|
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
The MIT License (MIT)
Copyright (c) 2014 Jarl Stefansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import print_function # This API requires Python 2.7 or more recent
import sys
if sys.version < "2.7.0":
print("listen requires Python 2.7 or more recent")
sys.exit(1)
from listen.signal_handler import SignalHandler
__all__ = ["listen"]
__version__ = "0.1.0"
|
Add datas as parameter for v0.2.4
|
'use strict';
/**
* Upload `contact` (containing contact data) onto Cluestr.
*
*
* @param {Object} contact Contact to upload, plus cluestrClient
* @param {Object} cluestrClient Client for upload
* @param {Object} datas Datas about the current account
* @param {Object} contact Contact to upload, plus cluestrClient
* @param {Function} cb Callback to call once contacts has been uploaded.
*/
module.exports = function(contact, cluestrClient, datas, cb) {
console.log("Uploading ", contact.url);
var identifier = contact.url;
if(contact.deleted) {
return cluestrClient.deleteDocument(identifier, cb);
}
// Build contact "the right way"
contact = {
identifier: identifier,
metadatas: contact,
semantic_document_type: 'contact',
actions: {
'show': contact.url
},
user_access: [cluestrClient.accessToken]
};
delete contact.metadatas.url;
delete contact.metadatas.id;
cluestrClient.sendDocument(contact, cb);
};
|
'use strict';
/**
* Upload `contact` (containing contact data) onto Cluestr.
*
*
* @param {Object} contact Contact to upload, plus cluestrClient
* @param {Function} cb Callback to call once contacts has been uploaded.
*/
module.exports = function(contact, cluestrClient, cb) {
console.log("Uploading ", contact.url);
var identifier = contact.url;
if(contact.deleted) {
return cluestrClient.deleteDocument(identifier, cb);
}
// Build contact "the right way"
contact = {
identifier: identifier,
metadatas: contact,
semantic_document_type: 'contact',
actions: {
'show': contact.url
},
user_access: [cluestrClient.accessToken]
};
delete contact.metadatas.url;
delete contact.metadatas.id;
cluestrClient.sendDocument(contact, cb);
};
|
Test on thumbnail update to new reference naming
|
# -*- coding: utf-8 -*-
# Author: Γscar NΓ‘jera
# License: 3-clause BSD
"""
Testing the rst files generator
"""
from __future__ import division, absolute_import, print_function
import sphinxgallery.backreferences as sg
from nose.tools import assert_equals
def test_thumbnail_div():
"""Test if the thumbnail div generates the correct string"""
html_div = sg._thumbnail_div('fake_dir', 'test_file.py', 'test formating')
reference = """
.. raw:: html
<div class="sphx-glr-thumbContainer" tooltip="test formating">
.. figure:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
:ref:`sphx_glr_fake_dir_test_file.py`
.. raw:: html
</div>
"""
assert_equals(html_div, reference)
|
# -*- coding: utf-8 -*-
# Author: Γscar NΓ‘jera
# License: 3-clause BSD
"""
Testing the rst files generator
"""
from __future__ import division, absolute_import, print_function
import sphinxgallery.backreferences as sg
from nose.tools import assert_equals
def test_thumbnail_div():
"""Test if the thumbnail div generates the correct string"""
html_div = sg._thumbnail_div('fake_dir', 'test_file.py', 'test formating')
reference = """
.. raw:: html
<div class="sphx-glr-thumbContainer" tooltip="test formating">
.. figure:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
:ref:`example_fake_dir_test_file.py`
.. raw:: html
</div>
"""
assert_equals(html_div, reference)
|
Fix timezone in submitted data
SimpleDateFormat uses the system's default time zone by default.
|
package org.mozilla.mozstumbler;
import android.annotation.SuppressLint;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
final class DateTimeUtils {
private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
static final long MILLISECONDS_PER_DAY = 86400000; // milliseconds/day
static {
mISO8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private DateTimeUtils() {
}
@SuppressLint("SimpleDateFormat")
static String formatDate(Date date) {
return mISO8601Format.format(date);
}
static String formatTime(long time) {
return formatDate(new Date(time));
}
static String formatTimeForLocale(long time) {
return DateFormat.getDateTimeInstance().format(time);
}
static String formatCurrentTime() {
return formatTime(System.currentTimeMillis());
}
}
|
package org.mozilla.mozstumbler;
import android.annotation.SuppressLint;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
final class DateTimeUtils {
private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
static final long MILLISECONDS_PER_DAY = 86400000; // milliseconds/day
private DateTimeUtils() {
}
@SuppressLint("SimpleDateFormat")
static String formatDate(Date date) {
return mISO8601Format.format(date);
}
static String formatTime(long time) {
return formatDate(new Date(time));
}
static String formatTimeForLocale(long time) {
return DateFormat.getDateTimeInstance().format(time);
}
static String formatCurrentTime() {
return formatTime(System.currentTimeMillis());
}
}
|
Add hasUser
Returns true/false if a room contains a user
|
var mongoose = require('mongoose');
var Message = new mongoose.Schema({
message: String,
sender: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
mime: {type: String, default: "text/plain"},
});
var Member = new mongoose.Schema({
id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
permissions: {
operator: {type: Boolean, default: false},
addUser: {type: Boolean, default: false},
removeUser: {type: Boolean, default: false},
sendMessage: {type: Boolean, default: true},
sendPriorityMessage: {type: Boolean, default: false},
changeTopic: {type: Boolean, default: false}
}
});
var Room = new mongoose.Schema({
messages: [Message],
members: [Member],
topic: String,
encryption: String
},
{timestamps: {createdAt: 'created_at'}}
);
Room.methods.findMemberById = function (id, callback) {
for (var i = 0; i < this.members.length; i++) {
var member = this.members[i];
if (member.id.toString() == id.toString()) {
callback(member);
}
}
};
Room.methods.hasUser = function (id) {
for (var i = 0; i < this.members.length; i++) {
if (this.members[i].id.toString() == id.toString()) {
return true;
}
}
return false;
};
module.exports = mongoose.model('Room', Room);
|
var mongoose = require('mongoose');
var Message = new mongoose.Schema({
message: String,
sender: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
mime: {type: String, default: "text/plain"},
});
var Member = new mongoose.Schema({
id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
permissions: {
operator: {type: Boolean, default: false},
addUser: {type: Boolean, default: false},
removeUser: {type: Boolean, default: false},
sendMessage: {type: Boolean, default: true},
sendPriorityMessage: {type: Boolean, default: false},
changeTopic: {type: Boolean, default: false}
}
});
var Room = new mongoose.Schema({
messages: [Message],
members: [Member],
topic: String,
encryption: String
},
{timestamps: {createdAt: 'created_at'}}
);
Room.methods.findMemberById = function (id, callback) {
for (var i = 0; i < this.members.length; i++) {
var member = this.members[i];
if (member.id.toString() == id.toString()) {
callback(member);
}
}
};
module.exports = mongoose.model('Room', Room);
|
Change MESSAGE_SUCCESS string to be non-static
|
/**
*
*/
package tars.logic.commands;
/**
* @author Johnervan
* Changes the directory of the Tars storage file, tars.xml
*/
public class CdCommand extends Command {
public static final String COMMAND_WORD = "cd";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the directory of the "
+ "TARS storage file, tars.xml";
public final String MESSAGE_SUCCESS = "Directory of tars.xml changed to: " + this.toString();
private final String filePath;
public CdCommand(String filepath) {
this.filePath = filepath;
}
@Override
public String toString() {
return this.filePath;
}
@Override
public CommandResult execute() {
// TODO Auto-generated method stub
return new CommandResult(MESSAGE_SUCCESS);
}
}
|
/**
*
*/
package tars.logic.commands;
/**
* @author Johnervan
* Changes the directory of the Tars storage file, tars.xml
*/
public class CdCommand extends Command {
public static final String COMMAND_WORD = "cd";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the directory of the "
+ "TARS storage file, tars.xml";
public static final String MESSAGE_SUCCESS = "Directory of tars.xml changed to: ";
private final String filepath;
public CdCommand(String filepath) {
this.filepath = filepath;
}
@Override
public CommandResult execute() {
// TODO Auto-generated method stub
return null;
}
}
|
Make sure Essential information is not double tracked
|
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) {
"use strict";
var analytics = new Analytics();
if (window.lp.hasOwnProperty("tracking") && window.lp.tracking.hasOwnProperty("eVar12") && window.lp.tracking.eVar12 !== "dest essential information") {
analytics.trackView();
}
// Set up Omniture event handlers
var windowUnloadedFromSubmitClick = false;
// If the user clicks anywhere else on the page, reset the click tracker
$(document).on("click", function() {
windowUnloadedFromSubmitClick = false;
});
// When the user clicks on the submit button, track that it's what
// is causing the onbeforeunload event to fire (below)
$(document).on("click", "button.cta-button-primary", function(e) {
windowUnloadedFromSubmitClick = true;
e.stopPropagation();
});
// Before redirection (which the WN widget does, it's not a form submit)
// if the user clicked on the submit button, track click with Omniture
window.onbeforeunload = function() {
if (windowUnloadedFromSubmitClick) {
window.s.events = "event42";
window.s.t();
}
};
});
|
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) {
"use strict";
var analytics = new Analytics();
analytics.trackView();
// Set up Omniture event handlers
var windowUnloadedFromSubmitClick = false;
// If the user clicks anywhere else on the page, reset the click tracker
$(document).on("click", function() {
windowUnloadedFromSubmitClick = false;
});
// When the user clicks on the submit button, track that it's what
// is causing the onbeforeunload event to fire (below)
$(document).on("click", "button.cta-button-primary", function(e) {
windowUnloadedFromSubmitClick = true;
e.stopPropagation();
});
// Before redirection (which the WN widget does, it's not a form submit)
// if the user clicked on the submit button, track click with Omniture
window.onbeforeunload = function() {
if (windowUnloadedFromSubmitClick) {
window.s.events = "event42";
window.s.t();
}
};
});
|
Add lpeg.c to _ppeg.c dependencies
|
from distutils.core import setup, Extension
setup (
name='PPeg',
version='0.9',
description="A Python port of Lua's LPeg pattern matching library",
url='https://bitbucket.org/pmoore/ppeg',
author='Paul Moore',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2 :: Only',
'Topic :: Text Processing :: General',
],
keywords='parsing peg grammar regex',
ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']),
Extension('_cpeg', ['_cpeg.c'])],
py_modules=[
'PythonImpl',
'pegmatcher',
],
)
|
from distutils.core import setup, Extension
setup (
name='PPeg',
version='0.9',
description="A Python port of Lua's LPeg pattern matching library",
url='https://bitbucket.org/pmoore/ppeg',
author='Paul Moore',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2 :: Only',
'Topic :: Text Processing :: General',
],
keywords='parsing peg grammar regex',
ext_modules = [Extension('_ppeg', ['_ppeg.c']),
Extension('_cpeg', ['_cpeg.c'])],
py_modules=[
'PythonImpl',
'pegmatcher',
],
)
|
Allow creation of a no metric symptom
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This program is made available under the terms of the MIT License.
* See the LICENSE file in the project root for more information.
*/
package com.microsoft.dhalion.detector;
import java.util.HashMap;
import java.util.Map;
import com.microsoft.dhalion.metrics.ComponentMetrics;
/**
* A {@link Symptom} identifies an anomaly or a potential health issue in a specific component of a
* distributed application. For e.g. identification of irregular processing latency.
*/
public class Symptom {
private String name;
private Map<String, ComponentMetrics> metrics = new HashMap<>();
public Symptom(String symptomName) {
this.name = symptomName;
}
public Symptom(String symptomName, ComponentMetrics metrics) {
this.name = symptomName;
addComponentMetrics(metrics);
}
public synchronized void addComponentMetrics(ComponentMetrics metrics) {
this.metrics.put(metrics.getName(), metrics);
}
public String getName() {
return name;
}
public Map<String, ComponentMetrics> getComponents() {
return metrics;
}
/**
* @return the only component exhibiting this symptom
*/
public synchronized ComponentMetrics getComponent() {
if (metrics.size() > 1) {
throw new IllegalStateException();
}
return metrics.values().iterator().next();
}
@Override
public String toString() {
return "Symptom{" +
"name=" + name +
", metrics=" + metrics +
'}';
}
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This program is made available under the terms of the MIT License.
* See the LICENSE file in the project root for more information.
*/
package com.microsoft.dhalion.detector;
import java.util.HashMap;
import java.util.Map;
import com.microsoft.dhalion.metrics.ComponentMetrics;
/**
* A {@link Symptom} identifies an anomaly or a potential health issue in a specific component of a
* distributed application. For e.g. identification of irregular processing latency.
*/
public class Symptom {
private String name;
private Map<String, ComponentMetrics> metrics = new HashMap<>();
public Symptom(String symptomName, ComponentMetrics metrics) {
this.name = symptomName;
addComponentMetrics(metrics);
}
public synchronized void addComponentMetrics(ComponentMetrics metrics) {
this.metrics.put(metrics.getName(), metrics);
}
public String getName() {
return name;
}
public Map<String, ComponentMetrics> getComponents() {
return metrics;
}
/**
* @return the only component exhibiting this symptom
*/
public synchronized ComponentMetrics getComponent() {
if (metrics.size() > 1) {
throw new IllegalStateException();
}
return metrics.values().iterator().next();
}
@Override
public String toString() {
return "Symptom{" +
"name=" + name +
", metrics=" + metrics +
'}';
}
}
|
Remove Python 3.4 from classifiers
|
from setuptools import setup, find_packages
from django_s3_storage import __version__
version_str = ".".join(str(n) for n in __version__)
setup(
name="django-s3-storage",
version=version_str,
license="BSD",
description="Django Amazon S3 file storage.",
author="Dave Hall",
author_email="dave@etianen.com",
url="https://github.com/etianen/django-s3-storage",
packages=find_packages(),
install_requires=[
"django>=1.11",
"boto3>=1.4.4,<2",
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Framework :: Django",
],
)
|
from setuptools import setup, find_packages
from django_s3_storage import __version__
version_str = ".".join(str(n) for n in __version__)
setup(
name="django-s3-storage",
version=version_str,
license="BSD",
description="Django Amazon S3 file storage.",
author="Dave Hall",
author_email="dave@etianen.com",
url="https://github.com/etianen/django-s3-storage",
packages=find_packages(),
install_requires=[
"django>=1.11",
"boto3>=1.4.4,<2",
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Framework :: Django",
],
)
|
Add highlighting for outline files
|
define(function(require, exports, module) {
var modesByName = require("ace/ext/modelist").modesByName;
modesByName.javascript.extensions += "|run|build|outline";
var primaryModes = ["c_cpp","clojure","coffee","csharp","css","dart","golang",
"html","jade","java","javascript","json","less","lua","perl","php","python",
"ruby","scala","scss","sh","stylus","sql","text","typescript","xml","xquery",
"yaml"];
var hiddenModes = ["text", "snippets"];
var fileExtensions = Object.create(null);
var modesByCaption = Object.create(null);
var customExtensions = Object.create(null);
Object.keys(modesByName).forEach(function(name) {
var mode = modesByName[name];
modesByCaption[mode.caption] = mode;
mode.id = name;
if (primaryModes.indexOf(mode.name) != -1)
mode.order = 100000;
else if (hiddenModes.indexOf(mode.name) != -1)
mode.order = -1;
else
mode.order = 0;
mode.extensions.split("|").forEach(function(ext) {
if (!fileExtensions[ext])
fileExtensions[ext] = name;
});
});
module.exports = {
byName: modesByName,
extensions: fileExtensions,
customExtensions: customExtensions,
byCaption: modesByCaption
}
});
|
define(function(require, exports, module) {
var modesByName = require("ace/ext/modelist").modesByName;
modesByName.javascript.extensions += "|run|build";
var primaryModes = ["c_cpp","clojure","coffee","csharp","css","dart","golang",
"html","jade","java","javascript","json","less","lua","perl","php","python",
"ruby","scala","scss","sh","stylus","sql","text","typescript","xml","xquery",
"yaml"];
var hiddenModes = ["text", "snippets"];
var fileExtensions = Object.create(null);
var modesByCaption = Object.create(null);
var customExtensions = Object.create(null);
Object.keys(modesByName).forEach(function(name) {
var mode = modesByName[name];
modesByCaption[mode.caption] = mode;
mode.id = name;
if (primaryModes.indexOf(mode.name) != -1)
mode.order = 100000;
else if (hiddenModes.indexOf(mode.name) != -1)
mode.order = -1;
else
mode.order = 0;
mode.extensions.split("|").forEach(function(ext) {
if (!fileExtensions[ext])
fileExtensions[ext] = name;
});
});
module.exports = {
byName: modesByName,
extensions: fileExtensions,
customExtensions: customExtensions,
byCaption: modesByCaption
}
});
|
Use safe_load to avoid warning
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
|
Enable filenameMode option in CLI
|
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var minimist = require('minimist')
var fasta = require('./')
var argv = minimist(process.argv.slice(2), {
boolean: ['path', 'file'],
alias: {
file: 'f',
path: 'p'
}
})
if (argv.help) {
return console.log(
'Usage: bionode-ncbi <options> <fasta file [required]> <output file>\n\n' +
'You can also use fasta files compressed with gzip\n' +
'If no output is provided, the result will be printed to stdout\n\n' +
'Options: -p, --path: Includes the path of the original file as a property of the output objects\n\n'
)
}
var options = {
includePath: argv.path,
filenameMode: argv.file && !argv.write
}
var output = argv._[1] ? fs.createWriteStream(argv._[1]) : process.stdout
var parser = argv.write ? fasta.write() : fasta(options, argv._[0])
parser.pipe(output)
process.stdin.setEncoding('utf8');
if (!process.stdin.isTTY) {
process.stdin.on('data', function(data) {
if (data.trim() === '') { return }
parser.write(data.trim())
})
}
|
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var minimist = require('minimist')
var fasta = require('./')
var argv = minimist(process.argv.slice(2), { boolean: ['p', 'path'] });
if (argv.help) {
return console.log(
'Usage: bionode-ncbi <options> <fasta file [required]> <output file>\n\n' +
'You can also use fasta files compressed with gzip\n' +
'If no output is provided, the result will be printed to stdout\n\n' +
'Options: -p, --path: Includes the path of the original file as a property of the output objects\n\n'
)
}
var options = {}
if (argv.p || argv.path) { options.includePath = true }
var output = argv._[1] ? fs.createWriteStream(argv._[1]) : process.stdout
var parser = argv.write ? fasta.write() : fasta(options, argv._[0])
parser.pipe(output)
process.stdin.setEncoding('utf8');
if (!process.stdin.isTTY) {
process.stdin.on('data', function(data) {
if (data.trim() === '') { return }
parser.write(data.trim())
})
}
|
Use current host name for redirect url
|
<?php
use TOL\PhotoHack\Youtube;
function hostName()
{
$protocol = $_SERVER['HTTPS'] ? 'https://' : 'http://';
$serverName = $_SERVER['SERVER_NAME'];
return $protocol . $serverName;
}
return function($app) {
$twigView = new \Slim\Views\Twig();
$twigView->parserOptions = ['autoescape' => false];
$app->config('templates.path', __DIR__ . '/templates');
$view = $app->view($twigView);
$view->parserExtensions = [new \Slim\Views\TwigExtension()];
$app->container->singleton('youtube', function() use($app) {
return new Youtube($app->client);
});
$app->container->singleton('client', function() use($app) {
$client = new Google_Client();
$client->setClientId(getenv('YOUTUBE_CLIENT_ID'));
$client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET'));
$client->setScopes('https://www.googleapis.com/auth/youtube');
$serverName = hostName();
$client->setRedirectUri("{$serverName}/share");
$token = $app->getCookie('token');
if ($token) {
$client->setAccessToken($token);
}
return $client;
});
};
|
<?php
use TOL\PhotoHack\Youtube;
return function($app) {
$twigView = new \Slim\Views\Twig();
$twigView->parserOptions = ['autoescape' => false];
$app->config('templates.path', __DIR__ . '/templates');
$view = $app->view($twigView);
$view->parserExtensions = [new \Slim\Views\TwigExtension()];
$app->container->singleton('youtube', function() use($app) {
return new Youtube($app->client);
});
$app->container->singleton('client', function() use($app) {
$client = new Google_Client();
$client->setClientId(getenv('YOUTUBE_CLIENT_ID'));
$client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET'));
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri('http://local.photohack.com/share');
$token = $app->getCookie('token');
if ($token) {
$client->setAccessToken($token);
}
return $client;
});
};
|
Add comment about future work in confUrl
|
'use strict';
// Handles params concerning configuration files in the $routeProvider phase
angular.module('arethusa.core').factory('confUrl', [
'CONF_PATH',
'$route',
function (CONF_PATH, $route) {
// The default route is deprectated and can be refactored away
return function (useDefault) {
var params = $route.current.params;
var confPath = CONF_PATH + '/';
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
return confPath + params.conf + '.json';
} else if (params.conf_file) {
return params.conf_file;
} else {
if (useDefault) {
return confPath + 'default.json';
}
}
};
}
]);
|
'use strict';
// Handles params concerning configuration files in the $routeProvider phase
angular.module('arethusa.core').factory('confUrl', [
'CONF_PATH',
'$route',
function (CONF_PATH, $route) {
return function (useDefault) {
var params = $route.current.params;
var confPath = CONF_PATH + '/';
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
return confPath + params.conf + '.json';
} else if (params.conf_file) {
return params.conf_file;
} else {
if (useDefault) {
return confPath + 'default.json';
}
}
};
}
]);
|
Add addServiceUrl attribute to result from findServices and findAllServices
|
/*
* Copyright (C) 2013 ickStream GmbH
* All rights reserved
*/
package com.ickstream.protocol.service.core;
public class ServiceResponse {
private String id;
private String name;
private String type;
private String url;
private String addServiceUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAddServiceUrl() {
return addServiceUrl;
}
public void setAddServiceUrl(String addServiceUrl) {
this.addServiceUrl = addServiceUrl;
}
}
|
/*
* Copyright (C) 2013 ickStream GmbH
* All rights reserved
*/
package com.ickstream.protocol.service.core;
public class ServiceResponse {
private String id;
private String name;
private String type;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
Fix Call to pass in options
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"gopkg.in/jcelliott/turnpike.v2"
)
func main() {
turnpike.Debug()
c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil)
if err != nil {
log.Fatal(err)
}
_, err = c.JoinRealm("turnpike.examples", nil)
if err != nil {
log.Fatal(err)
}
quit := make(chan bool)
c.Subscribe("alarm.ring", func([]interface{}, map[string]interface{}) {
fmt.Println("The alarm rang!")
c.Close()
quit <- true
})
fmt.Print("Enter the timer duration: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
if err := scanner.Err(); err != nil {
log.Fatalln("reading stdin:", err)
}
text := scanner.Text()
if duration, err := strconv.Atoi(text); err != nil {
log.Fatalln("invalid integer input:", err)
} else {
if _, err := c.Call("alarm.set", nil, []interface{}{duration}, nil); err != nil {
log.Fatalln("error setting alarm:", err)
}
}
<-quit
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"gopkg.in/jcelliott/turnpike.v2"
)
func main() {
turnpike.Debug()
c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil)
if err != nil {
log.Fatal(err)
}
_, err = c.JoinRealm("turnpike.examples", nil)
if err != nil {
log.Fatal(err)
}
quit := make(chan bool)
c.Subscribe("alarm.ring", func([]interface{}, map[string]interface{}) {
fmt.Println("The alarm rang!")
c.Close()
quit <- true
})
fmt.Print("Enter the timer duration: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
if err := scanner.Err(); err != nil {
log.Fatalln("reading stdin:", err)
}
text := scanner.Text()
if duration, err := strconv.Atoi(text); err != nil {
log.Fatalln("invalid integer input:", err)
} else {
if _, err := c.Call("alarm.set", []interface{}{duration}, nil); err != nil {
log.Fatalln("error setting alarm:", err)
}
}
<-quit
}
|
Move AuthProvider into first config block
|
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap'])
.config(['$routeProvider', 'AuthProvider', function($routeProvider, AuthProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'SignupCtrl'
})
.when('/logout', {
template: null,
controller: 'LogoutCtrl'
})
.when('/protected', {
templateUrl: 'views/protected.html',
controller: 'ProtectedCtrl'
})
.otherwise({
redirectTo: '/'
});
AuthProvider.configure({
apiUrl: '/api'
});
}]);
|
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'SignupCtrl'
})
.when('/logout', {
template: null,
controller: 'LogoutCtrl'
})
.when('/protected', {
templateUrl: 'views/protected.html',
controller: 'ProtectedCtrl'
})
.otherwise({
redirectTo: '/'
});
}])
.config(['AuthProvider', function(AuthProvider) {
AuthProvider.configure({
apiUrl: '/api'
});
}]);
|
Python: Add example of QuerySet chain (django)
|
from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
cursor.execute(sql="some sql") # $getSql="some sql"
class User(models.Model):
pass
def test_model():
User.objects.raw("some sql") # $getSql="some sql"
User.objects.annotate(RawSQL("some sql")) # $getSql="some sql"
User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar"
User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql"
User.objects.extra("some sql") # $getSql="some sql"
User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by"
raw = RawSQL("so raw")
User.objects.annotate(val=raw) # $getSql="so raw"
# chaining QuerySet calls
User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql"
|
from django.db import connection, models
from django.db.models.expressions import RawSQL
def test_plain():
cursor = connection.cursor()
cursor.execute("some sql") # $getSql="some sql"
def test_context():
with connection.cursor() as cursor:
cursor.execute("some sql") # $getSql="some sql"
cursor.execute(sql="some sql") # $getSql="some sql"
class User(models.Model):
pass
def test_model():
User.objects.raw("some sql") # $getSql="some sql"
User.objects.annotate(RawSQL("some sql")) # $getSql="some sql"
User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar"
User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql"
User.objects.extra("some sql") # $getSql="some sql"
User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by"
raw = RawSQL("so raw")
User.objects.annotate(val=raw) # $getSql="so raw"
|
Remove unneeded import, fix bare except
The `os` module isn't needed, so we need not import it.
Additionally, a bare `except` clause is pretty much never desired, since
it includes all exceptions, including sigkills.
Instead, just check for an `ImportError`, since that's what we're really
trying to do: fall back on `distutils` if `setuptools` is not present.
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.0.2",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar==0.1.3',
'mock==2.0.0',
'nose==1.3.7',
'numpy==1.10.1',
'preconditions==0.1',
'pyfasta==0.5.2',
'pysam==0.10.0',
],
license = "Apache-2.0",
)
|
import os
try:
from setuptools import setup
except:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.0.2",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar==0.1.3',
'mock==2.0.0',
'nose==1.3.7',
'numpy==1.10.1',
'preconditions==0.1',
'pyfasta==0.5.2',
'pysam==0.10.0',
],
license = "Apache-2.0",
)
|
Update the test connection value
|
<?php
namespace Leezy\PheanstalkBundle\Tests;
use Leezy\PheanstalkBundle\ConnectionLocator;
class ConnectionLocatorTest extends \PHPUnit_Framework_TestCase {
public function testDefaultConnections()
{
$connectionLocator = new ConnectionLocator();
$this->assertNotNull($connectionLocator->getConnections());
}
public function testGetDefaultConnection()
{
$connection = new \Pheanstalk_Pheanstalk('localhost', '11300');
$connectionLocator = new ConnectionLocator();
$connectionLocator->addConnection('default', $connection);
$this->assertEquals($connection, $connectionLocator->getConnection(null));
}
public function testGetNoDefinedConnection()
{
$connection = new \Pheanstalk_Pheanstalk('localhost', '11300');
$connectionLocator = new ConnectionLocator();
$connectionLocator->addConnection('default', $connection);
$this->assertNull($connectionLocator->getConnection('john.doe'));
}
}
|
<?php
namespace Leezy\PheanstalkBundle\Tests;
use Leezy\PheanstalkBundle\ConnectionLocator;
class ConnectionLocatorTest extends \PHPUnit_Framework_TestCase {
public function testDefaultConnections()
{
$connectionLocator = new ConnectionLocator();
$this->assertNotNull($connectionLocator->getConnections());
}
public function testGetDefaultConnection()
{
$connection = new \Pheanstalk_Pheanstalk('localhost', '11300');
$connectionLocator = new ConnectionLocator();
$connectionLocator->addConnection('default', $connection);
$this->assertEquals($connection, $connectionLocator->getConnection('default'));
}
public function testGetNoDefinedConnection()
{
$connection = new \Pheanstalk_Pheanstalk('localhost', '11300');
$connectionLocator = new ConnectionLocator();
$connectionLocator->addConnection('default', $connection);
$this->assertNull($connectionLocator->getConnection('john.doe'));
}
}
|
Fix lexicographic order in install_requires
|
#!/usr/bin/env python
from setuptools import setup
install_requires = [
'argparse',
'jsonschema',
'M2Crypto',
'mock',
'pycrypto',
'python-augeas',
'python2-pythondialog',
'requests',
]
docs_extras = [
'Sphinx',
]
testing_extras = [
'coverage',
'nose',
'nosexcover',
'pylint',
'tox',
]
setup(
name="letsencrypt",
version="0.1",
description="Let's Encrypt",
author="Let's Encrypt Project",
license="",
url="https://letsencrypt.org",
packages=[
'letsencrypt',
'letsencrypt.client',
'letsencrypt.scripts',
],
install_requires=install_requires,
tests_require=install_requires,
test_suite='letsencrypt',
extras_require={
'docs': docs_extras,
'testing': testing_extras,
},
entry_points={
'console_scripts': [
'letsencrypt = letsencrypt.scripts.main:main',
],
},
zip_safe=False,
include_package_data=True,
)
|
#!/usr/bin/env python
from setuptools import setup
install_requires = [
'argparse',
'jsonschema',
'mock',
'M2Crypto',
'pycrypto',
'python-augeas',
'python2-pythondialog',
'requests',
]
docs_extras = [
'Sphinx',
]
testing_extras = [
'coverage',
'nose',
'nosexcover',
'pylint',
'tox',
]
setup(
name="letsencrypt",
version="0.1",
description="Let's Encrypt",
author="Let's Encrypt Project",
license="",
url="https://letsencrypt.org",
packages=[
'letsencrypt',
'letsencrypt.client',
'letsencrypt.scripts',
],
install_requires=install_requires,
tests_require=install_requires,
test_suite='letsencrypt',
extras_require={
'docs': docs_extras,
'testing': testing_extras,
},
entry_points={
'console_scripts': [
'letsencrypt = letsencrypt.scripts.main:main',
],
},
zip_safe=False,
include_package_data=True,
)
|
Remove redundant ugettext_lazy from non-text labels
|
from django import forms
from django.core import validators
from django.forms.widgets import TextInput
class URLOrAbsolutePathValidator(validators.URLValidator):
@staticmethod
def is_absolute_path(value):
return value.startswith('/')
def __call__(self, value):
if URLOrAbsolutePathValidator.is_absolute_path(value):
return None
else:
return super().__call__(value)
class URLOrAbsolutePathField(forms.URLField):
widget = TextInput
default_validators = [URLOrAbsolutePathValidator()]
def to_python(self, value):
if not URLOrAbsolutePathValidator.is_absolute_path(value):
value = super().to_python(value)
return value
class ExternalLinkChooserForm(forms.Form):
url = URLOrAbsolutePathField(required=True, label="")
link_text = forms.CharField(required=False)
class AnchorLinkChooserForm(forms.Form):
url = forms.CharField(required=True, label="#")
link_text = forms.CharField(required=False)
class EmailLinkChooserForm(forms.Form):
email_address = forms.EmailField(required=True)
link_text = forms.CharField(required=False)
class PhoneLinkChooserForm(forms.Form):
phone_number = forms.CharField(required=True)
link_text = forms.CharField(required=False)
|
from django import forms
from django.core import validators
from django.forms.widgets import TextInput
from django.utils.translation import ugettext_lazy
class URLOrAbsolutePathValidator(validators.URLValidator):
@staticmethod
def is_absolute_path(value):
return value.startswith('/')
def __call__(self, value):
if URLOrAbsolutePathValidator.is_absolute_path(value):
return None
else:
return super().__call__(value)
class URLOrAbsolutePathField(forms.URLField):
widget = TextInput
default_validators = [URLOrAbsolutePathValidator()]
def to_python(self, value):
if not URLOrAbsolutePathValidator.is_absolute_path(value):
value = super().to_python(value)
return value
class ExternalLinkChooserForm(forms.Form):
url = URLOrAbsolutePathField(required=True, label=ugettext_lazy(""))
link_text = forms.CharField(required=False)
class AnchorLinkChooserForm(forms.Form):
url = forms.CharField(required=True, label=ugettext_lazy("#"))
link_text = forms.CharField(required=False)
class EmailLinkChooserForm(forms.Form):
email_address = forms.EmailField(required=True)
link_text = forms.CharField(required=False)
class PhoneLinkChooserForm(forms.Form):
phone_number = forms.CharField(required=True)
link_text = forms.CharField(required=False)
|
Fix terrible error when filter_horizontal of admin class has not existed.
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
def register(cls, admin_cls):
cls.add_to_class('code', models.ForeignKey('profiles.Code',
verbose_name=_('Registration code'), null=True, blank=True))
if admin_cls:
admin_cls.list_display_filter += ['code', ]
if admin_cls.fieldsets:
admin_cls.fieldsets.append((_('Registration code'), {
'fields': ['code',],
'classes': ('collapse',),
}))
if admin_cls.filter_horizontal:
admin_cls.filter_horizontal = admin_cls.filter_horizontal + ('code',)
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
def register(cls, admin_cls):
cls.add_to_class('code', models.ForeignKey('profiles.Code',
verbose_name=_('Registration code'), null=True, blank=True))
if admin_cls:
admin_cls.list_display_filter += ['code', ]
if admin_cls.fieldsets:
admin_cls.fieldsets.append((_('Registration code'), {
'fields': ['code',],
'classes': ('collapse',),
}))
admin_cls.filter_horizontal = admin_cls.filter_horizontal + ('code',)
|
Fix capitalization method in class_names
|
HEADER = """/**
{file_name}
Auto-generated code - do not modify.
thinglang C++ transpiler, 0.0.0
**/
"""
FOUNDATION_ENUM = HEADER + """
#pragma once
#include <string>
{imports}
enum class {name} {{
{values}
}};
"""
FOUNDATION_SWITCH = """
inline auto {func_name}({name} val){{
switch (val){{
{cases}
}}
}}
"""
ENUM_CASE = """
case {enum_class}::{name}:
return {value};"""
TYPE_INSTANTIATION = HEADER + """
{imports}
enum PrimitiveType {{
{primitives}
}};
inline Type create_type(const std::string& type_name){{
{conditions}
throw RuntimeError("Unknown type name: " + type_name);
}}
"""
TYPE_CONDITIONAL = """if(type_name == "{name}") return new {cls_name}();"""
def class_names(name):
name = name.transpile()
formatted_name = name[0].upper() + name[1:]
return '{}Type'.format(formatted_name), '{}Instance'.format(formatted_name)
|
HEADER = """/**
{file_name}
Auto-generated code - do not modify.
thinglang C++ transpiler, 0.0.0
**/
"""
FOUNDATION_ENUM = HEADER + """
#pragma once
#include <string>
{imports}
enum class {name} {{
{values}
}};
"""
FOUNDATION_SWITCH = """
inline auto {func_name}({name} val){{
switch (val){{
{cases}
}}
}}
"""
ENUM_CASE = """
case {enum_class}::{name}:
return {value};"""
TYPE_INSTANTIATION = HEADER + """
{imports}
enum PrimitiveType {{
{primitives}
}};
inline Type create_type(const std::string& type_name){{
{conditions}
throw RuntimeError("Unknown type name: " + type_name);
}}
"""
TYPE_CONDITIONAL = """if(type_name == "{name}") return new {cls_name}();"""
def class_names(name):
name = name.transpile().capitalize()
return '{}Type'.format(name), '{}Instance'.format(name)
|
Fix for the goto command actions
|
$(document).ready(function() {
var publishCommand = function(notificationName) {
return function(tokens) { $.publish(notificationName); };
}
window.TerminalCommands = {
next : publishCommand('presentation:slide:next'),
previous : publishCommand('presentation:slide:previous'),
goto : function(tokens) {
var gotoSlideNumber = undefined;
if ( parseInt(tokens[0]) > 0 && parseInt(tokens[0]) < presentation.slideTotal()) {
gotoSlideNumber = parseInt(tokens[0]) - 1;
} else if (tokens[0] == 'start') {
gotoSlideNumber = 0;
} else if (tokens[0] == 'end') {
gotoSlideNumber = presentation.slideTotal() - 1;
} else {
gotoSlideNumber = presentation.slides.findClosestToQuery(presentation.currentSlide.sequence,tokens[0]) - 1;
}
$.publish('presentation:slide:location:change',gotoSlideNumber);
}
};
});
|
$(document).ready(function() {
var publishCommand = function(notificationName) {
return function(tokens) { $.publish(notificationName); };
}
window.TerminalCommands = {
next : publishCommand('presentation:slide:next'),
previous : publishCommand('presentation:slide:previous'),
goto : function(tokens) {
var gotoSlideNumber = undefined;
if ( parseInt(tokens) > 0 && parseInt(tokens) < presentation.slideTotal()) {
gotoSlideNumber = parseInt(tokens[0]) - 1;
} else if (gotoSlideNumber == 'start') {
gotoSlideNumber = 0;
} else if (gotoSlideNumber == 'end') {
gotoSlideNumber = presentation.slideTotal() - 1;
} else {
gotoSlideNumber = presentation.slides.findClosestToQuery(presentation.currentSlide.sequence,tokens[0]) - 1;
}
$.publish('presentation:slide:location:change',gotoSlideNumber);
}
};
});
|
Update the benchmark to use the document.readyState to measure page-completedness
rather than the onload event. Extensions were moved from the pre-onload state
to running at document idle some time ago.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/397013
git-svn-id: http://src.chromium.org/svn/trunk/src@32076 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: e079f6bc95496920f7c70cd95adf734203430f47
|
// The port for communicating back to the extension.
var benchmarkExtensionPort = chrome.extension.connect();
// The url is what this page is known to the benchmark as.
// The benchmark uses this id to differentiate the benchmark's
// results from random pages being browsed.
// TODO(mbelshe): If the page redirects, the location changed and the
// benchmark stalls.
var benchmarkExtensionUrl = window.location.toString();
function sendTimesToExtension() {
if (window.parent != window) {
return;
}
var times = window.chrome.loadTimes();
// If the load is not finished yet, schedule a timer to check again in a
// little bit.
if (times.finishLoadTime != 0) {
benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times});
} else {
window.setTimeout(sendTimesToExtension, 100);
}
}
// We can't use the onload event because this script runs at document idle,
// which may run after the onload has completed.
sendTimesToExtension();
|
// The port for communicating back to the extension.
var benchmarkExtensionPort = chrome.extension.connect();
// The url is what this page is known to the benchmark as.
// The benchmark uses this id to differentiate the benchmark's
// results from random pages being browsed.
// TODO(mbelshe): If the page redirects, the location changed and the
// benchmark stalls.
var benchmarkExtensionUrl = window.location.toString();
function sendTimesToExtension() {
var times = window.chrome.loadTimes();
if (times.finishLoadTime != 0) {
benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times});
} else {
window.setTimeout(sendTimesToExtension, 100);
}
}
function loadComplete() {
// Only trigger for top-level frames (e.g. the one we benchmarked)
if (window.parent == window) {
sendTimesToExtension();
}
}
window.addEventListener("load", loadComplete);
|
Update JSON object sent for login
|
import {Router} from 'express'
import models from '../models';
export default () => {
let app = Router()
app.get('/new', (req, res) => {
res.render('sessions/new')
})
app.post('/', (req, res) => {
var email = req.body.email
models.User.find({
attributes: ['id', 'first_name', 'last_name', 'email'],
where: {
email
}
}).then((user) => {
// REFACTOR THIS
var token;
var id;
var authenticated;
var err;
if (userExists(user) && req.body.password_hash === user.password_hash){
authenticated = true
token = Math.random().toString(36).substring(7)
} else {
authenticated = false
token = null
if (userExists(user)) {
err = {type: "nil-user"}
} else {
err = {type: "incorrect-password"}
}
}
res.send({
user,
authenticated,
token,
err
});
})
})
app.delete('/', (req, res) => {
req.session.userId = null
res.redirect('/')
})
function userExists(user) {
return user !== null
}
return app
}
|
import {Router} from 'express'
import models from '../models';
export default () => {
let app = Router()
app.get('/new', (req, res) => {
res.render('sessions/new')
})
app.post('/', (req, res) => {
var email = req.body.email
models.User.find({
where: {
email: email
}
}).then((user) => {
let token;
let authenticated;
let err;
console.log(user)
if (userExists(user) && req.body.password_hash === user.password_hash){
authenticated = true
token = Math.random().toString(36).substring(7)
} else {
authenticated = false
token = null
if (userExists(user)) {
err = {type: "nil-user"}
} else {
err = {type: "incorrect-password"}
}
}
res.send({
authenticated,
token,
err
});
})
})
app.delete('/', (req, res) => {
req.session.userId = null
res.redirect('/')
})
function userExists(user) {
return user !== null
}
return app
}
|
Change the hide function to work in a better way to not brake other functionallity.
|
/* Magic Mirror
* Node Helper: MotionEye
*
* By Cato Antonsen (https://github.com/CatoAntonsen)
* MIT Licensed.
*/
var NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function() {
console.log("Starting module: " + this.name);
},
socketNotificationReceived: function(notification, config) {
var self = this;
if (notification === "CONFIG") {
self.config = config;
if (config.autoHide) {
this.expressApp.get('/motioneye/hide/:id*?', function (req, res) {
console.log("Hide registered");
res.send('Hide registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeHide", req.params.id);
});
this.expressApp.get('/motioneye/:id*?', function (req, res) {
console.log("Motion registered");
res.send('Motion registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeShow", req.params.id);
});
} else {
self.sendSocketNotification("MotionEyeShow", undefined);
}
return;
}
},
});
|
/* Magic Mirror
* Node Helper: MotionEye
*
* By Cato Antonsen (https://github.com/CatoAntonsen)
* MIT Licensed.
*/
var NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function() {
console.log("Starting module: " + this.name);
},
socketNotificationReceived: function(notification, config) {
var self = this;
if (notification === "CONFIG") {
self.config = config;
if (config.autoHide) {
this.expressApp.get('/motioneye/:id', function (req, res) {
console.log("Motion registered");
res.send('Motion registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeShow", req.params.id);
});
this.expressApp.get('/motioneye/:id/hide', function (req, res) {
console.log("Hide registered");
res.send('Hide registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeHide", req.params.id);
});
} else {
self.sendSocketNotification("MotionEyeShow", undefined);
}
return;
}
},
});
|
Return app passwords as string
|
import os
import random
import uuid
from django.utils import timezone
from datetime import timedelta
WORDLIST_FILE = os.path.join(os.path.dirname(__file__), 'wordlist.txt')
def make_token():
"""
Generate a random token suitable for activation/confirmation via email
A hex-encoded random UUID has plenty of entropy to be secure enough for our
needs.
"""
return uuid.uuid4().hex
def expiration_date():
"""
AuthToken objects expire 1 hour after creation by default
"""
return timezone.now() + timedelta(hours=1)
def new_app_password(size=6):
f = open(WORDLIST_FILE, 'r')
words = []
for i in range(size):
words.append(next(f).strip())
for num,line in enumerate(f):
j = random.randrange(size+num)
if j < size:
words[j] = line.strip()
return ' '.join(words)
|
import os
import random
import uuid
from django.contrib.auth.hashers import make_password,is_password_usable
from django.utils import timezone
from datetime import timedelta
WORDLIST_FILE = os.path.join(os.path.dirname(__file__), 'wordlist.txt')
def make_token():
"""
Generate a random token suitable for activation/confirmation via email
A hex-encoded random UUID has plenty of entropy to be secure enough for our
needs.
"""
return uuid.uuid4().hex
def expiration_date():
"""
AuthToken objects expire 1 hour after creation by default
"""
return timezone.now() + timedelta(hours=1)
def new_app_password(size=6):
f = open(WORDLIST_FILE, 'r')
words = []
for i in range(size):
words.append(next(f).strip())
for num,line in enumerate(f):
j = random.randrange(size+num)
if j < size:
words[j] = line.strip()
return words
|
Use admin interface by default
|
# -*- coding: utf-8 -*-
"""onserver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^', admin.site.urls),
]
|
# -*- coding: utf-8 -*-
"""onserver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
Use green for console intro instead
|
var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
c = require( 'ansicolors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:CLI/testcases/title',
clear: true
};
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function session( err, content ) {
params.content = content;
console.log( c.green('* The module exports are available as the variable "p", including unsaved modifications.' ) );
console.log( c.green('* Precede a line with "=" to evaluate it as an expression, or use print().' ) );
console.log( c.green('* Use mw.log() in module code to send messages to this console.' ) );
rl.on( 'line', cli );
}
client.getArticle( params.title, session );
|
var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
c = require( 'ansi-colors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:CLI/testcases/title',
clear: true
};
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function session( err, content ) {
params.content = content;
console.log( c.gray('* The module exports are available as the variable "p", including unsaved modifications.' ) );
console.log( c.gray('* Precede a line with "=" to evaluate it as an expression, or use print().' ) );
console.log( c.gray('* Use mw.log() in module code to send messages to this console.' ) );
rl.on( 'line', cli );
}
client.getArticle( params.title, session );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.