text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use no_async api to query if a chat member is a group admin | from bot.action.core.action import IntermediateAction
from bot.api.domain import Message
class GroupAdminAction(IntermediateAction):
def process(self, event):
chat = event.message.chat
if chat.type == "private":
# lets consider private chat members are admins :)
self._continue(event)
else:
user = event.message.from_
if user is not None:
chat_member = self.api.no_async.getChatMember(chat_id=chat.id, user_id=user.id)
if chat_member.status in ("creator", "administrator"):
self._continue(event)
else:
error_response = "Sorry, this command is only available to group admins."
self.api.send_message(Message.create_reply(event.message, error_response))
| from bot.action.core.action import IntermediateAction
from bot.api.domain import Message
class GroupAdminAction(IntermediateAction):
def process(self, event):
chat = event.message.chat
if chat.type == "private":
# lets consider private chat members are admins :)
self._continue(event)
else:
user = event.message.from_
if user is not None:
chat_member = self.api.getChatMember(chat_id=chat.id, user_id=user.id)
if chat_member.status in ("creator", "administrator"):
self._continue(event)
else:
error_response = "Sorry, this command is only available to group admins."
self.api.send_message(Message.create_reply(event.message, error_response))
|
Add ping route for testing | import express from 'express';
import locations from './routes/locations';
import tripLocations from './routes/trip-locations';
import distances from './routes/distances';
import admin from './routes/admin';
const router = express.Router();
router.route( '/ping' )
.get( ( req, res ) => {
res.status( 200 ).json( { ping: 'pong' } );
} );
router.route( '/secured/locations' )
.get( locations.list )
.post( locations.create )
.put( locations.updateList );
router.route( '/secured/locations/:locationId' )
.get( locations.get )
.put( locations.update )
.delete( locations.delete );
router.route( '/secured/trip-locations' )
.get( tripLocations.list )
.delete( tripLocations.deleteAll )
.put( tripLocations.updateList );
router.route( '/secured/distance' )
.get( distances.get );
router.route( '/secured/distances' )
.post( distances.post );
router.route( '/admin/events' )
.get( admin.get );
export default router;
| import express from 'express';
import locations from './routes/locations';
import tripLocations from './routes/trip-locations';
import distances from './routes/distances';
import admin from './routes/admin';
const router = express.Router();
router.route( '/secured/locations' )
.get( locations.list )
.post( locations.create )
.put( locations.updateList );
router.route( '/secured/locations/:locationId' )
.get( locations.get )
.put( locations.update )
.delete( locations.delete );
router.route( '/secured/trip-locations' )
.get( tripLocations.list )
.delete( tripLocations.deleteAll )
.put( tripLocations.updateList );
router.route( '/secured/distance' )
.get( distances.get );
router.route( '/secured/distances' )
.post( distances.post );
router.route( '/admin/events' )
.get( admin.get );
export default router;
|
Fix Prolific UDP listener print line. | /*
___ usage ___ en_US ___
node stdout.udp.bin.js --bind ip:port
options:
--help display help message
-p, --port <integer> port to listen to
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.param.help)
program.required('port')
var dgram = require('dgram')
var socket = dgram.createSocket('udp4')
socket.on('message', function (buffer) {
program.stdout.write(buffer)
program.stdout.write('\n')
})
program.on('SIGINT', socket.close.bind(socket))
async(function () {
// TODO Bind should be port or port and address.
socket.bind(+program.param.port, async())
}, function () {
return 0
})
}))
| /*
___ usage ___ en_US ___
node stdout.udp.bin.js --bind ip:port
options:
--help display help message
-p, --port <integer> port to listen to
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.param.help)
program.required('port')
var dgram = require('dgram')
var socket = dgram.createSocket('udp4')
socket.on('message', function (buffer) {
console.log('called')
program.stdout.write(buffer)
})
program.on('SIGINT', socket.close.bind(socket))
async(function () {
// TODO Bind should be port or port and address.
socket.bind(+program.param.port, async())
}, function () {
return 0
})
}))
|
Remove lint failure for multiple classes in same file | /* eslint-disable max-classes-per-file */
const { static: staticContent } = require('@feathersjs/express');
const path = require('path');
const hooks = require('./hooks');
const merlinHooks = require('./hooks/merlin.hooks');
const EduSharingConnector = require('./logic/connector');
const MerlinTokenGenerator = require('./logic/MerlinTokenGenerator');
class EduSearch {
find(data) {
return EduSharingConnector.FIND(data);
}
get(id, params) {
return EduSharingConnector.GET(id, params);
}
}
class MerlinToken {
find(data) {
return MerlinTokenGenerator.FIND(data);
}
}
module.exports = (app) => {
const merlinRoute = 'edu-sharing/merlinToken';
app.use(merlinRoute, new MerlinToken(), (req, res) => {
res.send(res.data);
});
const merlinService = app.service(merlinRoute);
merlinService.hooks(merlinHooks);
const eduRoute = '/edu-sharing';
app.use(eduRoute, new EduSearch(), (req, res) => {
res.send(res.data);
});
const eduService = app.service(eduRoute);
eduService.hooks(hooks);
app.use(`${eduRoute}/api`, staticContent(path.join(__dirname, '/docs')));
};
| const { static: staticContent } = require('@feathersjs/express');
const path = require('path');
const hooks = require('./hooks');
const merlinHooks = require('./hooks/merlin.hooks');
const EduSharingConnector = require('./logic/connector');
const MerlinTokenGenerator = require('./logic/MerlinTokenGenerator');
class EduSearch {
find(data) {
return EduSharingConnector.FIND(data);
}
get(id, params) {
return EduSharingConnector.GET(id, params);
}
}
class MerlinToken {
find(data) {
return MerlinTokenGenerator.FIND(data);
}
}
module.exports = (app) => {
const merlinRoute = 'edu-sharing/merlinToken';
app.use(merlinRoute, new MerlinToken(), (req, res) => {
res.send(res.data);
});
const merlinService = app.service(merlinRoute);
merlinService.hooks(merlinHooks);
const eduRoute = '/edu-sharing';
app.use(eduRoute, new EduSearch(), (req, res) => {
res.send(res.data);
});
const eduService = app.service(eduRoute);
eduService.hooks(hooks);
app.use(`${eduRoute}/api`, staticContent(path.join(__dirname, '/docs')));
};
|
Change default mccabe complexity to 12
See comments at code | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
# TODO (evvers@ya.ru): Change complexity to 11 when mccabe=0.2.2 released
# https://github.com/flintwork/mccabe/issues/5
'complexity': '12'
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
|
Change global vars to CAPS | var PAGE = new WebPage();
var URL = '';
var RETRYCOUNT = 100;
// TODO - Calculate URL based on current date
URL = 'https://offthegrid.com/event/the-lot/2017-9-20-11am';
PAGE.open(URL, function(status) {
if (status === 'success') {
var vendors;
var count = 0;
while (!vendors) {
vendors = PAGE.evaluate(function() {
return $("li.grid-item-card div.content-wrap").map(function() {
var name = $("h3", this)[0].innerText;
var cat = $("span", this)[0].innerText;
return '* ' + name + " (" + cat + ")";
}).toArray().join('\n');
});
count++;
if (count > RETRYCOUNT && !vendors) {
vendors = "Couldn't load anything after " + RETRYCOUNT + " tries.";
}
};
console.log('Food trucks at The Lot today:');
console.log(vendors);
} else {
console.log('Something bad happened: ' + status);
};
phantom.exit();
});
PAGE.onConsoleMessage = function (msg, line, source) {
console.log('console> ' + msg);
}; | var page = new WebPage();
var url = '';
var retryCount = 100;
// TODO - Calculate url based on current date
url = 'https://offthegrid.com/event/the-lot/2017-9-20-11am';
page.open(url, function(status) {
if (status === 'success') {
var vendors;
var count = 0;
while (!vendors) {
vendors = page.evaluate(function() {
return $("li.grid-item-card div.content-wrap").map(function() {
var name = $("h3", this)[0].innerText;
var cat = $("span", this)[0].innerText;
return '* ' + name + " (" + cat + ")";
}).toArray().join('\n');
});
count++;
if (count > retryCount && !vendors) {
vendors = "Couldn't load anything after " + retryCount + " tries.";
}
};
console.log('Food trucks at The Lot today:');
console.log(vendors);
} else {
console.log('Something bad happened: ' + status);
};
phantom.exit();
});
page.onConsoleMessage = function (msg, line, source) {
console.log('console> ' + msg);
}; |
Rename 'square' to 'path' in example script |
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.render import GerberRenderer, SVGRenderer
if __name__ == "__main__":
layer = Layer()
aperture1 = CircleAperture("10", 0.1)
layer.add_aperture(aperture1)
aperture2 = CircleAperture("11", 0.2, 0.1)
layer.add_aperture(aperture2)
path = PointList(aperture1)
path.add_point(Point(2.5, 0))
path.add_point(Point(5, 0))
path.add_point(Point(5, 5))
path.add_point(Point(0, 5))
path.add_point(Point(0, 2.5))
path.add_point(Point(2.5, 0))
layer.add_shape(path)
donut = ApertureFlash(aperture2, Point(0, 5))
layer.add_shape(donut)
gr = GerberRenderer(layer)
gr.write_file("out.grb")
sr = SVGRenderer(layer)
sr.write_file("out.svg")
|
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.render import GerberRenderer, SVGRenderer
if __name__ == "__main__":
layer = Layer()
aperture1 = CircleAperture("10", 0.1)
layer.add_aperture(aperture1)
aperture2 = CircleAperture("11", 0.2, 0.1)
layer.add_aperture(aperture2)
square = PointList(aperture1)
square.add_point(Point(2.5, 0))
square.add_point(Point(5, 0))
square.add_point(Point(5, 5))
square.add_point(Point(0, 5))
square.add_point(Point(0, 2.5))
square.add_point(Point(2.5, 0))
layer.add_shape(square)
donut = ApertureFlash(aperture2, Point(0, 5))
layer.add_shape(donut)
gr = GerberRenderer(layer)
gr.write_file("out.grb")
sr = SVGRenderer(layer)
sr.write_file("out.svg")
|
Fix the comparison to work more robustly. | from django.apps import AppConfig
from django.db.models.signals import post_delete, post_save
from wagtail.wagtailsearch.backends import get_search_backends
from wagtail.wagtailsearch.index import get_indexed_models
from wagtail.wagtailsearch.signal_handlers import (get_indexed_instance,
post_delete_signal_handler)
def post_save_signal_handler(instance, **kwargs):
update_fields = kwargs.get('update_fields')
social_fields = frozenset(('cached_facebook_count', 'cached_last_updated'))
if update_fields == social_fields:
return # Don't update the search index if we are just updating facebook page counts
indexed_instance = get_indexed_instance(instance)
if indexed_instance:
for backend in get_search_backends(with_auto_update=True):
backend.add(indexed_instance)
def register_signal_handlers():
# Loop through list and register signal handlers for each one
for model in get_indexed_models():
post_save.connect(post_save_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
class CustomWagtailSearchAppConfig(AppConfig):
name = 'wagtail.wagtailsearch'
label = 'wagtailsearch'
verbose_name = "Wagtail search"
def ready(self):
register_signal_handlers()
| from django.apps import AppConfig
from django.db.models.signals import post_delete, post_save
from wagtail.wagtailsearch.backends import get_search_backends
from wagtail.wagtailsearch.index import get_indexed_models
from wagtail.wagtailsearch.signal_handlers import (get_indexed_instance,
post_delete_signal_handler)
def post_save_signal_handler(instance, **kwargs):
update_fields = kwargs.get('update_fields')
if 'cached_last_updated' in update_fields and 'cached_facebook_count' in update_fields:
return # Don't update the search index if we are just updating facebook page counts
indexed_instance = get_indexed_instance(instance)
if indexed_instance:
for backend in get_search_backends(with_auto_update=True):
backend.add(indexed_instance)
def register_signal_handlers():
# Loop through list and register signal handlers for each one
for model in get_indexed_models():
post_save.connect(post_save_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
class CustomWagtailSearchAppConfig(AppConfig):
name = 'wagtail.wagtailsearch'
label = 'wagtailsearch'
verbose_name = "Wagtail search"
def ready(self):
register_signal_handlers()
|
Add to download links ng-csv | var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3030',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3030
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
| var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3051',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3051
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
|
Add corrected locale support for languages | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import moment from 'moment';
import french from 'moment/locale/fr';
import english from 'moment/locale/en-nz';
import {
authStrings,
buttonStrings,
generalStrings,
modalStrings,
navStrings,
pageInfoStrings,
programStrings,
syncStrings,
tableStrings,
LANGUAGE_CODES,
formInputStrings,
dispensingStrings,
} from './index';
const DATE_CONFIGS = {
DEFAULT: english,
[LANGUAGE_CODES.FRENCH]: french,
};
const SUPPORTED_DATE_LOCALES = {
DEFAULT: 'en-nz',
[LANGUAGE_CODES.ENGLISH]: 'en-nz',
[LANGUAGE_CODES.FRENCH]: 'fr',
};
export const setDateLocale = languageCode =>
moment.updateLocale(
SUPPORTED_DATE_LOCALES[languageCode] ?? SUPPORTED_DATE_LOCALES.DEFAULT,
DATE_CONFIGS[languageCode] ?? DATE_CONFIGS.DEFAULT
);
export function setCurrentLanguage(language) {
authStrings.setLanguage(language);
buttonStrings.setLanguage(language);
generalStrings.setLanguage(language);
modalStrings.setLanguage(language);
navStrings.setLanguage(language);
pageInfoStrings.setLanguage(language);
tableStrings.setLanguage(language);
syncStrings.setLanguage(language);
programStrings.setLanguage(language);
formInputStrings.setLanguage(language);
dispensingStrings.setLanguage(language);
}
export default setCurrentLanguage;
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import moment from 'moment';
import french from 'moment/locale/fr';
import english from 'moment/locale/en-nz';
import {
authStrings,
buttonStrings,
generalStrings,
modalStrings,
navStrings,
pageInfoStrings,
programStrings,
syncStrings,
tableStrings,
LANGUAGE_CODES,
formInputStrings,
dispensingStrings,
} from './index';
const DATE_CONFIGS = {
DEFAULT: english,
[LANGUAGE_CODES.FRENCH]: french,
};
export const setDateLocale = languageCode =>
moment.updateLocale(languageCode, DATE_CONFIGS[languageCode] || DATE_CONFIGS.DEFAULT);
export function setCurrentLanguage(language) {
authStrings.setLanguage(language);
buttonStrings.setLanguage(language);
generalStrings.setLanguage(language);
modalStrings.setLanguage(language);
navStrings.setLanguage(language);
pageInfoStrings.setLanguage(language);
tableStrings.setLanguage(language);
syncStrings.setLanguage(language);
programStrings.setLanguage(language);
formInputStrings.setLanguage(language);
dispensingStrings.setLanguage(language);
}
export default setCurrentLanguage;
|
Reorder struct fields by relevance
The first 3 can uniquely identify a post. | package model
import (
"time"
"gopkg.in/mgo.v2/bson"
)
const OfferGroupPostCollectionName = "offer_group_post"
type (
OfferGroupPost struct {
ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
RestaurantID bson.ObjectId `json:"restaurant_id" bson:"restaurant_id"`
Date DateWithoutTime `json:"date" bson:"date"`
MessageTemplate string `json:"message_template" bson:"message_template"`
FBPostID string `json:"fb_post_id,omitempty" bson:"fb_post_id,omitempty"`
}
DateWithoutTime string
)
const dateWithoutTimeLayout = "2006-01-02"
func DateFromTime(t time.Time) DateWithoutTime {
dateString := t.Format(dateWithoutTimeLayout)
return DateWithoutTime(dateString)
}
func (d DateWithoutTime) IsValid() bool {
_, err := time.Parse(dateWithoutTimeLayout, string(d))
return err == nil
}
| package model
import (
"time"
"gopkg.in/mgo.v2/bson"
)
const OfferGroupPostCollectionName = "offer_group_post"
type (
OfferGroupPost struct {
ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
RestaurantID bson.ObjectId `json:"restaurant_id" bson:"restaurant_id"`
MessageTemplate string `json:"message_template" bson:"message_template"`
Date DateWithoutTime `json:"date" bson:"date"`
FBPostID string `json:"fb_post_id,omitempty" bson:"fb_post_id,omitempty"`
}
DateWithoutTime string
)
const dateWithoutTimeLayout = "2006-01-02"
func DateFromTime(t time.Time) DateWithoutTime {
dateString := t.Format(dateWithoutTimeLayout)
return DateWithoutTime(dateString)
}
func (d DateWithoutTime) IsValid() bool {
_, err := time.Parse(dateWithoutTimeLayout, string(d))
return err == nil
}
|
Make role_id & bypass opt args in Policy __init__ | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False)
capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False)
role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True)
bypass = db.Column(db.Boolean, nullable=False, default=False)
__table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),)
def __init__(self, id, domain_id, capability_id, role_id=None, bypass=False):
super(Policy, self).__init__(id)
self.domain_id = domain_id
self.capability_id = capability_id
self.role_id = role_id
self.bypass = bypass
| from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False)
capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False)
role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True)
bypass = db.Column(db.Boolean, nullable=False, default=False)
__table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),)
def __init__(self, id, domain_id, capability_id, role_id, bypass):
super(Policy, self).__init__(id)
self.domain_id = domain_id
self.capability_id = capability_id
self.role_id = role_id
self.bypass = bypass
|
:ambulance: Fix oversized images in carousel component | // @flow
// @jsx glam
import React from 'react';
import glam from 'glam';
import { Div, Img } from '../primitives';
import { type PropsWithStyles } from '../types';
import { className } from '../utils';
import { getSource } from './component-helpers';
import componentBaseClassNames from './componentBaseClassNames';
type Props = PropsWithStyles & {
data: Object,
isFullscreen: boolean,
isModal: boolean,
};
export const viewCSS = () => ({
lineHeight: 0,
position: 'relative',
textAlign: 'center',
});
const viewBaseClassName = componentBaseClassNames.View;
const View = (props: Props) => {
const { data, formatters, getStyles, index, isFullscreen, isModal } = props;
const innerProps = {
alt: formatters.getAltText({ data, index }),
src: getSource({ data, isFullscreen }),
};
return (
<Div
css={getStyles(viewBaseClassName, props)}
className={className(viewBaseClassName, { isFullscreen, isModal })}
>
<Img
{...innerProps}
className={className('view-image', { isFullscreen, isModal })}
css={{
height: 'auto',
maxHeight: '100%',
maxWidth: '100%',
userSelect: 'none',
}}
/>
</Div>
);
};
export default View;
| // @flow
// @jsx glam
import React from 'react';
import glam from 'glam';
import { Div, Img } from '../primitives';
import { type PropsWithStyles } from '../types';
import { className } from '../utils';
import { getSource } from './component-helpers';
import componentBaseClassNames from './componentBaseClassNames';
type Props = PropsWithStyles & {
data: Object,
isFullscreen: boolean,
isModal: boolean,
};
export const viewCSS = () => ({
lineHeight: 0,
position: 'relative',
textAlign: 'center',
});
const viewBaseClassName = componentBaseClassNames.View;
const View = (props: Props) => {
const { data, formatters, getStyles, index, isFullscreen, isModal } = props;
const innerProps = {
alt: formatters.getAltText({ data, index }),
src: getSource({ data, isFullscreen }),
};
return (
<Div
css={getStyles(viewBaseClassName, props)}
className={className(viewBaseClassName, { isFullscreen, isModal })}
>
<Img
{...innerProps}
className={className('view-image', { isFullscreen, isModal })}
css={{
height: 'auto',
maxHeight: '100vh',
maxWidth: '100vw',
userSelect: 'none',
}}
/>
</Div>
);
};
export default View;
|
Copy local URL to clipboard | // Packages
const {copy} = require('copy-paste')
const ip = require('ip')
const chalk = require('chalk')
const copyToClipboard = async text => {
try {
await copy(text)
return true
} catch (err) {
return false
}
}
module.exports = async (server, current, inUse) => {
const details = server.address()
const ipAddress = ip.address()
const url = `http://${ipAddress}:${details.port}`
process.on('SIGINT', () => {
server.close()
process.exit(0)
})
if (!process.env.NOW) {
let message = chalk.green('Micro is running!')
if (inUse) {
message += ' ' + chalk.red(`(on port ${inUse.old},` +
` because ${inUse.open} is already in use)`)
}
message += '\n\n'
const localURL = `http://localhost:${details.port}`
message += `• ${chalk.bold('Locally: ')} ${localURL}\n`
message += `• ${chalk.bold('On the Network: ')} ${url}\n\n`
const copied = await copyToClipboard(localURL)
if (copied) {
message += `${chalk.grey('Copied local address to clipboard!')}\n\n`
}
process.stdout.write('\x1Bc')
process.stdout.write(message)
}
}
| // Packages
const {copy} = require('copy-paste')
const ip = require('ip')
const chalk = require('chalk')
const copyToClipboard = async text => {
try {
await copy(text)
return true
} catch (err) {
return false
}
}
module.exports = async (server, current, inUse) => {
const details = server.address()
const ipAddress = ip.address()
const url = `http://${ipAddress}:${details.port}`
process.on('SIGINT', () => {
server.close()
process.exit(0)
})
if (!process.env.NOW) {
let message = chalk.green('Running!')
if (inUse) {
message += ' ' + chalk.red(`(on port ${inUse.old},` +
` because ${inUse.open} is already in use)`)
}
message += '\n\n'
const localURL = `http://localhost:${details.port}`
message += `• ${chalk.bold('Locally: ')} ${localURL}\n`
message += `• ${chalk.bold('On the Network: ')} ${url}\n\n`
const copied = await copyToClipboard(url)
if (copied) {
message += `${chalk.grey('Copied local address to clipboard!')}\n\n`
}
process.stdout.write('\x1Bc')
process.stdout.write(message)
}
}
|
Use php5.3 syntax for array | <?php
function redirect($url = '/') {
header('HTTP/1.1 302 Found');
header("Location: $url");
}
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect();
exit;
}
$quizJson = json_decode(file_get_contents('php://input'), true);
$grade = $quizJson['grade'];
$subject = $quizJson['subject'];
$chapter = $quizJson['chapter'];
$fileName = "json/$grade/$subject/$chapter.json";
if(file_exists($fileName)) {
$existingJson = json_decode(file_get_contents($fileName));
} else {
$existingJson = array();
}
$quizJson['quiz']['type'] = 'quiz';
array_push($existingJson, $quizJson['quiz']);
file_put_contents($fileName, json_encode($existingJson));
header('HTTP/1.1 201 Created');
header('Content-Type: application/json');
echo json_encode($quizJson);
/*
* {grade:, subject: chapter: quiz: {}}
*/
?>
| <?php
function redirect($url = '/') {
header('HTTP/1.1 302 Found');
header("Location: $url");
}
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect();
exit;
}
$quizJson = json_decode(file_get_contents('php://input'), true);
$grade = $quizJson['grade'];
$subject = $quizJson['subject'];
$chapter = $quizJson['chapter'];
$fileName = "json/$grade/$subject/$chapter.json";
if(file_exists($fileName)) {
$existingJson = json_decode(file_get_contents($fileName));
} else {
$existingJson = [];
}
$quizJson['quiz']['type'] = 'quiz';
array_push($existingJson, $quizJson['quiz']);
file_put_contents($fileName, json_encode($existingJson));
header('HTTP/1.1 201 Created');
header('Content-Type: application/json');
echo json_encode($quizJson);
/*
* {grade:, subject: chapter: quiz: {}}
*/
?>
|
Fix docblock for public key route. | <?php
namespace Northstar\Http\Controllers;
class KeyController extends Controller
{
public function __construct()
{
$this->middleware('role:admin');
}
/**
* Return the public key, which can be used by other services
* to verify JWT access tokens.
* GET /key
*
* @return array
*/
public function show()
{
$path = base_path('storage/keys/public.key');
$publicKey = file_get_contents($path);
return [
'algorithm' => 'RS256',
'issuer' => url('/'),
'public_key' => $publicKey,
];
}
}
| <?php
namespace Northstar\Http\Controllers;
class KeyController extends Controller
{
public function __construct()
{
$this->middleware('role:admin');
}
/**
* Return the public key, which can be used by other services
* to verify JWT access tokens.
* GET /key
*
* @return \Illuminate\Http\Response
*/
public function show()
{
$path = base_path('storage/keys/public.key');
$publicKey = file_get_contents($path);
return [
'algorithm' => 'RS256',
'issuer' => url('/'),
'public_key' => $publicKey,
];
}
}
|
Correct bash completion file path | package main
import (
"github.com/spf13/cobra"
)
var cmdAutocomplete = &cobra.Command{
Use: "autocomplete",
Short: "Generate shell autocompletion script",
Long: `The "autocomplete" command generates a shell autocompletion script.
NOTE: The current version supports Bash only.
This should work for *nix systems with Bash installed.
By default, the file is written directly to /etc/bash_completion.d
for convenience, and the command may need superuser rights, e.g.:
$ sudo restic autocomplete`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
if err := cmdRoot.GenBashCompletionFile(autocompleteTarget); err != nil {
return err
}
return nil
},
}
var autocompleteTarget string
func init() {
cmdRoot.AddCommand(cmdAutocomplete)
cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/usr/share/bash-completion/completions/restic", "autocompletion file")
// For bash-completion
cmdAutocomplete.Flags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
}
| package main
import (
"github.com/spf13/cobra"
)
var autocompleteTarget string
var cmdAutocomplete = &cobra.Command{
Use: "autocomplete",
Short: "Generate shell autocompletion script",
Long: `The "autocomplete" command generates a shell autocompletion script.
NOTE: The current version supports Bash only.
This should work for *nix systems with Bash installed.
By default, the file is written directly to /etc/bash_completion.d
for convenience, and the command may need superuser rights, e.g.:
$ sudo restic autocomplete`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
if err := cmdRoot.GenBashCompletionFile(autocompleteTarget); err != nil {
return err
}
return nil
},
}
func init() {
cmdRoot.AddCommand(cmdAutocomplete)
cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/etc/bash_completion.d/restic.sh", "autocompletion file")
// For bash-completion
cmdAutocomplete.Flags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
}
|
Add ts statistics to the tests module. |
__author__ = 'To\xc3\xb1o G. Quintela (tgq.spm@gmail.com)'
__version__ = '0.0.0'
#from pyCausality.TimeSeries.TS import *
#from pyCausality.TimeSeries.automatic_thresholding import *
#from pyCausality.TimeSeries.distances import *
#from pyCausality.TimeSeries.measures import *
#from pyCausality.TimeSeries.smoothing import *
#from pyCausality.TimeSeries.transformations import *
from tests import test_artificial_data
from tests import test_utils
from tests import test_measures
from tests import test_transformations
from tests import test_burstdetection
from tests import test_tsstatistics
from tests import test_regimedetection
from tests import test_feature_extraction
from tests import test_similarities
## Administrative information
import release
import version
## Not inform about warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
warnings.simplefilter("ignore")
def test():
## Tests of modules
test_artificial_data.test()
# test_utils.test()
# test_measures.test()
test_transformations.test()
test_burstdetection.test()
test_tsstatistics.test()
# test_regimedetection.test()
# test_feature_extraction.test()
# test_similarities.test()
|
__author__ = 'To\xc3\xb1o G. Quintela (tgq.spm@gmail.com)'
__version__ = '0.0.0'
#from pyCausality.TimeSeries.TS import *
#from pyCausality.TimeSeries.automatic_thresholding import *
#from pyCausality.TimeSeries.distances import *
#from pyCausality.TimeSeries.measures import *
#from pyCausality.TimeSeries.smoothing import *
#from pyCausality.TimeSeries.transformations import *
from tests import test_artificial_data
from tests import test_utils
from tests import test_measures
from tests import test_transformations
from tests import test_burstdetection
from tests import test_tsstatistics
from tests import test_regimedetection
from tests import test_feature_extraction
from tests import test_similarities
## Administrative information
import release
import version
## Not inform about warnings
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
warnings.simplefilter("ignore")
def test():
## Tests of modules
test_artificial_data.test()
# test_utils.test()
# test_measures.test()
test_transformations.test()
test_burstdetection.test()
# test_tsstatistics.test()
# test_regimedetection.test()
# test_feature_extraction.test()
# test_similarities.test()
|
Add test case to parameter parselet test | <?php
namespace PhpBench\Tests\Unit\Expression\Parselet;
use Generator;
use PhpBench\Expression\Ast\ParameterNode;
use PhpBench\Tests\Unit\Expression\ParseletTestCase;
class ParameterParseletTest extends ParseletTestCase
{
/**
* @return Generator<mixed>
*/
public function provideParse(): Generator
{
yield 'property' => [
'foo.bar',
new ParameterNode(['foo', 'bar'])
];
}
/**
* {@inheritDoc}
*/
public function provideEvaluate(): Generator
{
yield [
'foo',
['foo' => 12],
'12'
];
yield [
'foo.bar',
['foo' => ['bar' => 12]],
'12'
];
}
/**
* {@inheritDoc}
*/
public function providePrint(): Generator
{
yield from $this->providePrintFromEvaluate();
}
}
| <?php
namespace PhpBench\Tests\Unit\Expression\Parselet;
use Generator;
use PhpBench\Expression\Ast\ParameterNode;
use PhpBench\Tests\Unit\Expression\ParseletTestCase;
class ParameterParseletTest extends ParseletTestCase
{
/**
* @return Generator<mixed>
*/
public function provideParse(): Generator
{
yield 'property' => [
'foo.bar',
new ParameterNode(['foo', 'bar'])
];
}
/**
* {@inheritDoc}
*/
public function provideEvaluate(): Generator
{
yield [
'foo',
['foo' => 12],
'12'
];
}
/**
* {@inheritDoc}
*/
public function providePrint(): Generator
{
yield from $this->providePrintFromEvaluate();
}
}
|
Add rep and sen from address fields to Preferences model | import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
rep_from_address = models.CharField(max_length=255, blank=True, null=True)
sen_from_address = models.CharField(max_length=255, blank=True, null=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
| import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
|
Make logs dir if missing | <?php
function debug_collectionInfoStart($debug, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Collecting data\n", $log);
}
}
function debug_collectionInfoEnd($debug, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Finished collecting data\n\n", $log);
}
}
function debug_collectionInterval($debug, $interval, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
}
}
function debug($echo, $log) {
if ($echo != "" && $echo !== NULL) {
echo $echo;
}
if ($log == TRUE) {
if (!file_exists("logs/debug.log")) {
mkdir("logs");
$dbglog = fopen("logs/debug.log", "w");
fclose($dbglog);
}
file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND);
}
}
?> | <?php
function debug_collectionInfoStart($debug, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Collecting data\n", $log);
}
}
function debug_collectionInfoEnd($debug, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Finished collecting data\n\n", $log);
}
}
function debug_collectionInterval($debug, $interval, $log) {
if ($debug == TRUE) {
debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
}
}
function debug($echo, $log) {
if ($echo != "" && $echo !== NULL) {
echo $echo;
}
if ($log == TRUE) {
if (!file_exists("logs/debug.log")) {
$dbglog = fopen("logs/debug.log", "w");
fclose($dbglog);
}
file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND);
}
}
?> |
Handle incoming card click event with simple logger | var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
app.get('/', function(req, res) {
var state0 = game.getInitialState()
res.render('index', state0);
})
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
socket.on('card click', function(click){
console.log('CARD CLICK', click.user, click.card);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
| var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
app.get('/', function(req, res) {
var state0 = game.getInitialState()
res.render('index', state0);
})
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
|
Add block ui to ajax call for creating new timeslot | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data },
beforeSend: customBlockUi(this)
}).done(function(response) {
swal({
title: "Great!",
text: "You have set up a tutoring availability!",
confirmButtonColor: "#66BB6A",
type: "success"
});
$('#tutor-cal').fullCalendar( 'refetchEvents' );
}).fail(function(response) {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
})
})
var createDate = function() {
var date = $('.timepicker').val();
var time = $('.datepicker').val();
var dateTime = date + " " + time;
return (new Date(dateTime));
} | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data }
}).done(function(response) {
swal({
title: "Great!",
text: "You have set up a tutoring availability!",
confirmButtonColor: "#66BB6A",
type: "success"
});
$('#tutor-cal').fullCalendar( 'refetchEvents' );
}).fail(function(response) {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
})
})
var createDate = function() {
var date = $('.timepicker').val();
var time = $('.datepicker').val();
var dateTime = date + " " + time;
return (new Date(dateTime));
} |
Remove version constraints on numpy/scipy | #!/usr/bin/env python
from setuptools import setup
version = "0.1.0"
setup(name='metric_learn',
version=version,
description='Python implementations of metric learning algorithms',
author='CJ Carey',
author_email='ccarey@cs.umass.edu',
url='http://github.com/all-umass/metric_learn',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
],
packages=['metric_learn'],
install_requires=[
'numpy',
'scipy',
'scikit-learn'
],
test_suite='test'
)
| #!/usr/bin/env python
from setuptools import setup
version = "0.1.0"
setup(name='metric_learn',
version=version,
description='Python implementations of metric learning algorithms',
author='CJ Carey',
author_email='ccarey@cs.umass.edu',
url='http://github.com/all-umass/metric_learn',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
],
packages=['metric_learn'],
install_requires=[
'numpy >= 1.5.1',
'scipy >= 0.8',
'scikit-learn'
],
test_suite='test'
)
|
Set minimal example to 'default' kineticsFamilies. | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = 'default',
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
saveEdgeSpecies=True,
saveConcentrationProfiles=True,
)
| # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
saveEdgeSpecies=True,
saveConcentrationProfiles=True,
)
|
Support of DAO'ing of Annotations | package org.orienteer.core.dao.handler;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.Optional;
import org.joor.Reflect;
import org.orienteer.core.dao.IMethodHandler;
/**
* {@link IMethodHandler} which invoke interfaces default method implementations
* @param <T> type of target/delegate object
*/
public class DefaultInterfaceMethodHandler<T> implements IMethodHandler<T> {
@Override
public Optional<Object> handle(T target, Object proxy, Method method, Object[] args, InvocationChain<T> chain) throws Throwable {
Class<?> declaringClass = method.getDeclaringClass();
if(method.isDefault()) {
MethodHandles.Lookup lookup = Reflect.onClass(MethodHandles.Lookup.class)
.create(declaringClass, MethodHandles.Lookup.PRIVATE).get();
return Optional.ofNullable(lookup.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args));
} else if(proxy instanceof Annotation
&& (args==null || args.length==0)
&& !method.getDeclaringClass().equals(Annotation.class)) {
Object defaultValue = method.getDefaultValue();
if(defaultValue!=null) return Optional.of(defaultValue);
}
return chain.handle(target, proxy, method, args);
}
}
| package org.orienteer.core.dao.handler;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.Optional;
import org.joor.Reflect;
import org.orienteer.core.dao.IMethodHandler;
/**
* {@link IMethodHandler} which invoke interfaces default method implementations
* @param <T> type of target/delegate object
*/
public class DefaultInterfaceMethodHandler<T> implements IMethodHandler<T> {
@Override
public Optional<Object> handle(T target, Object proxy, Method method, Object[] args, InvocationChain<T> chain) throws Throwable {
if(method.isDefault()) {
Class<?> declaringClass = method.getDeclaringClass();
MethodHandles.Lookup lookup = Reflect.onClass(MethodHandles.Lookup.class)
.create(declaringClass, MethodHandles.Lookup.PRIVATE).get();
return Optional.ofNullable(lookup.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args));
} else return chain.handle(target, proxy, method, args);
}
}
|
Increase build types cache life for one day | /*
* Copyright 2016 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.api.cache;
import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode;
import com.github.vase4kin.teamcityapp.runbuild.api.Branches;
import java.util.concurrent.TimeUnit;
import io.rx_cache.DynamicKey;
import io.rx_cache.EvictDynamicKey;
import io.rx_cache.LifeCache;
import rx.Observable;
/**
* Cache providers
*/
public interface CacheProviders {
@LifeCache(duration = 1, timeUnit = TimeUnit.DAYS)
Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey);
@LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES)
Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId);
}
| /*
* Copyright 2016 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.api.cache;
import com.github.vase4kin.teamcityapp.navigation.api.NavigationNode;
import com.github.vase4kin.teamcityapp.runbuild.api.Branches;
import java.util.concurrent.TimeUnit;
import io.rx_cache.DynamicKey;
import io.rx_cache.EvictDynamicKey;
import io.rx_cache.LifeCache;
import rx.Observable;
/**
* Cache providers
*/
public interface CacheProviders {
// TODO: Increase cache to 24 hours? Good idea, huh?
@LifeCache(duration = 1, timeUnit = TimeUnit.HOURS)
Observable<NavigationNode> listBuildTypes(Observable<NavigationNode> navigationNodeObservable, DynamicKey dynamicKey, EvictDynamicKey evictDynamicKey);
@LifeCache(duration = 1, timeUnit = TimeUnit.MINUTES)
Observable<Branches> listBranches(Observable<Branches> branchesObservable, DynamicKey buildTypeId);
}
|
Add link to Github commit page | <?php
$html->addBodyContent('<div class="footer">');
$githash = shell_exec('cd '. realpath(dirname(__FILE__)). '/../../ && git log --pretty="%H" -n1 HEAD');
$html->addBodyContent('<p>Commit: <a href="https://github.com/buralien/mat/commit/'. $githash. '">'. substr($githash, 0, 7). '</a></p>');
$html->addBodyContent('<p>MAT info a licence: <a href="https://github.com/buralien/mat">GitHub</a></p>');
$html->addBodyContent('<div><a href="https://responsivevoice.org">ResponsiveVoice-NonCommercial</a> licensed under <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">CC BY-NC-ND 4.0</a></div>');
$html->addBodyContent('<p>Příspěvek na provoz: <a href="https://paypal.me/buralien">PayPal</a></p>');
$html->addBodyContent('</div>');
?>
| <?php
$html->addBodyContent('<div class="footer">');
$html->addBodyContent('<p>Commit: '. shell_exec('cd '. realpath(dirname(__FILE__)). '/../../ && git log --pretty="%h" -n1 HEAD'). '</p>');
$html->addBodyContent('<p>MAT info a licence: <a href="https://github.com/buralien/mat">GitHub</a></p>');
$html->addBodyContent('<div><a href="https://responsivevoice.org">ResponsiveVoice-NonCommercial</a> licensed under <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">CC BY-NC-ND 4.0</a></div>');
$html->addBodyContent('<p>Příspěvek na provoz: <a href="https://paypal.me/buralien">PayPal</a></p>');
$html->addBodyContent('</div>');
?>
|
Add a test for the blog announcement | from gratipay.testing import Harness
class TestNotifications(Harness):
def test_add_single_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_add_multiple_notifications(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('1234')
assert alice.notifications == ["abcd", "1234"]
def test_add_same_notification_twice(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_remove_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('1234')
alice.add_notification('bcde')
alice.remove_notification('1234')
assert alice.notifications == ["abcd", "bcde"]
def test_blog_announcement(self):
assert 'blog/39c07bd031b">indefinitely' in self.client.GET('/').body
| from gratipay.testing import Harness
class TestNotifications(Harness):
def test_add_single_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_add_multiple_notifications(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('1234')
assert alice.notifications == ["abcd", "1234"]
def test_add_same_notification_twice(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_remove_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
alice.add_notification('1234')
alice.add_notification('bcde')
alice.remove_notification('1234')
assert alice.notifications == ["abcd", "bcde"]
|
Correct priority for STRONGINFO log level | import logging
import colorlog
logging.STRONGINFO = logging.INFO + 5
logging.addLevelName(logging.STRONGINFO, 'STRONGINFO')
def logStrongInfo(msg, *args, **kwargs):
"""Log a message with severity 'STRONGINFO' on the root logger. If the logger has
no handlers, call basicConfig() to add a console handler with a pre-defined
format."""
return logging.log(logging.STRONGINFO, msg, *args, **kwargs)
setattr(logging, 'stronginfo', logStrongInfo)
def logStrongInfoMethod(self, msg, *args, **kwargs):
"""Log 'msg % args' with severity 'STRONGINFO'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.stronginfo("Houston, we have a %s", "interesting problem", exc_info=1)
"""
return self.log(logging.STRONGINFO, msg, *args, **kwargs)
setattr(logging.getLoggerClass(), 'stronginfo', logStrongInfoMethod)
colorlog.default_log_colors['STRONGINFO'] = 'bold_green'
| import logging
import colorlog
logging.STRONGINFO = logging.DEBUG + 5
logging.addLevelName(logging.STRONGINFO, 'STRONGINFO')
def logStrongInfo(msg, *args, **kwargs):
"""Log a message with severity 'STRONGINFO' on the root logger. If the logger has
no handlers, call basicConfig() to add a console handler with a pre-defined
format."""
return logging.log(logging.STRONGINFO, msg, *args, **kwargs)
setattr(logging, 'stronginfo', logStrongInfo)
def logStrongInfoMethod(self, msg, *args, **kwargs):
"""Log 'msg % args' with severity 'STRONGINFO'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.stronginfo("Houston, we have a %s", "interesting problem", exc_info=1)
"""
return self.log(logging.STRONGINFO, msg, *args, **kwargs)
setattr(logging.getLoggerClass(), 'stronginfo', logStrongInfoMethod)
colorlog.default_log_colors['STRONGINFO'] = 'bold_green'
|
Fix the logging message in the nightly task | from datetime import datetime, timedelta
from flask import current_app
from notifications_utils.statsd_decorators import statsd
from app import notify_celery
from app.dao.fact_billing_dao import (
fetch_billing_data_for_day,
update_fact_billing
)
@notify_celery.task(name="create-nightly-billing")
@statsd(namespace="tasks")
def create_nightly_billing(day_start=None):
# day_start is a datetime.date() object. e.g.
# 3 days of data counting back from day_start is consolidated
if day_start is None:
day_start = datetime.today() - timedelta(days=1)
for i in range(0, 3):
process_day = day_start - timedelta(days=i)
transit_data = fetch_billing_data_for_day(process_day=process_day)
for data in transit_data:
update_fact_billing(data, process_day)
current_app.logger.info(
"create-nightly-billing task complete. {} rows updated for day: {}".format(len(transit_data, process_day)))
| from datetime import datetime, timedelta
from flask import current_app
from notifications_utils.statsd_decorators import statsd
from app import notify_celery
from app.dao.fact_billing_dao import (
fetch_billing_data_for_day,
update_fact_billing
)
@notify_celery.task(name="create-nightly-billing")
@statsd(namespace="tasks")
def create_nightly_billing(day_start=None):
# day_start is a datetime.date() object. e.g.
# 3 days of data counting back from day_start is consolidated
if day_start is None:
day_start = datetime.today() - timedelta(days=1)
for i in range(0, 3):
process_day = day_start - timedelta(days=i)
transit_data = fetch_billing_data_for_day(process_day=process_day)
for data in transit_data:
update_fact_billing(data, process_day)
current_app.logger.info("create-nightly-billing task complete. {} rows updated".format(len(transit_data)))
|
Fix all entities sharing common position, extract fitnessScenario | require("babel/register");
var Seeder = require('./app/seeder');
var Entity = require('./app/entity');
var simulateWorld = require('./app/simulator');
var fitnessScenario = {
startingPosition() {
return {
x: 100,
y: 100,
};
},
expectedEndPosition: {
x: 200,
y: 100,
},
duration: 60,
fitness(entity) {
var distance = {
x: Math.abs(this.expectedEndPosition.x - entity.position.x),
y: Math.abs(this.expectedEndPosition.y - entity.position.y),
}
return 1000 - (distance.x + distance.y);
}
};
function run(generations=100, population=32) {
var initialGeneration = Seeder.make(30);
var framesToSimulate = 60;
var entities = initialGeneration.map(individual => new Entity(individual, fitnessScenario.startingPosition()));
entities.forEach(entity => simulateWorld(entity, fitnessScenario.duration));
return entities.map(function (entity) {
return {
entity: entity,
fitness: fitnessScenario.fitness(entity),
};
});
}
module.exports = run;
| require("babel/register");
var Seeder = require('./app/seeder');
var Entity = require('./app/entity');
var simulateWorld = require('./app/simulator');
function run(generations=100, population=30) {
var initialGeneration = Seeder.make(30);
var framesToSimulate = 60;
var fitnessScenario = {
startingPosition: {
x: 100,
y: 100,
},
expectedEndPosition: {
x: 200,
y: 100,
},
duration: 60,
fitness(entity) {
var distance = {
x: Math.abs(this.expectedEndPosition.x - entity.position.x),
y: Math.abs(this.expectedEndPosition.y - entity.position.y),
}
return 1000 - (distance.x + distance.y);
}
};
var entities = initialGeneration.map(individual => new Entity(individual, fitnessScenario.startingPosition));
entities.forEach(entity => simulateWorld(entity, fitnessScenario.duration));
console.log(entities.map(e => e.position));
return entities.map(function (entity) {
return {
entity: entity,
fitness: fitnessScenario.fitness(entity),
};
});
}
module.exports = run;
|
Add tooltip to event meta | <?php
global $post;
$host = get_post(get_post_meta($post->ID, IT_PREFIX."event_host", true));
$location = get_post_meta($post->ID, IT_PREFIX."event_location", true);
?>
<ul class="meta event-meta">
<li class="icon-clock">
<?php echo date("j F", strtotime(get_post_meta($post->ID, IT_PREFIX."event_date", true)));?>,
<?php echo get_post_meta($post->ID, IT_PREFIX."event_start_time", true);?>
-<?php echo get_post_meta($post->ID, IT_PREFIX."event_end_time", true);?></li>
<?php if($location) : ?>
<li class="icon-map-pin-fill"><?php echo $location;?></li>
<?php endif;?>
<?php if($host):?>
<li rel="tooltip" title="Kommittée som anordnar detta arrangemang" class="icon-user"><a href="<?php echo get_permalink($host->ID);?>"><?php echo $host->post_title;?></a></li>
<?php endif;?>
</ul> | <?php
global $post;
$host = get_post(get_post_meta($post->ID, IT_PREFIX."event_host", true));
?>
<ul class="meta event-meta">
<li class="icon-clock">
<?php echo date("j F", strtotime(get_post_meta($post->ID, IT_PREFIX."event_date", true)));?>,
<?php echo get_post_meta($post->ID, IT_PREFIX."event_start_time", true);?>
-<?php echo get_post_meta($post->ID, IT_PREFIX."event_end_time", true);?></li>
<li class="icon-map-pin-fill"><?php echo get_post_meta($post->ID, IT_PREFIX."event_location", true);?></li>
<?php if($host):?>
<li class="icon-user"><a href="<?php echo get_permalink($host->ID);?>"><?php echo $host->post_title;?></a></li>
<?php endif;?>
</ul> |
Fix - Allow DSA to access bulk tag | <?php
class Bulk_tag extends MX_Controller {
function index(){
$data['title'] = 'Bulk Tagging Tool';
$data['scripts'] = array('bulk_tag_app');
$data['js_lib'] = array('core', 'angular', 'select2', 'location_capture_widget', 'googleapi', 'google_map');
$this->load->model("registry/data_source/data_sources","ds");
$this->load->model("registry/registry_object/registry_objects","ro");
$dataSources = $this->ds->getOwnedDataSources();
$items = array();
foreach($dataSources as $ds){
$item = array();
$item['title'] = $ds->title;
$item['key'] = $ds->key;
array_push($items, $item);
}
$data['dataSources'] = $items;
$data['themepages'] = $this->ro->getAllThemePages();
$this->load->view('bulk_tag_index', $data);
}
function __construct(){
parent::__construct();
acl_enforce('REGISTRY_USER');
}
} | <?php
class Bulk_tag extends MX_Controller {
function index(){
$data['title'] = 'Bulk Tagging Tool';
$data['scripts'] = array('bulk_tag_app');
$data['js_lib'] = array('core', 'angular', 'select2', 'location_capture_widget', 'googleapi', 'google_map');
$this->load->model("registry/data_source/data_sources","ds");
$this->load->model("registry/registry_object/registry_objects","ro");
$dataSources = $this->ds->getOwnedDataSources();
$items = array();
foreach($dataSources as $ds){
$item = array();
$item['title'] = $ds->title;
$item['key'] = $ds->key;
array_push($items, $item);
}
$data['dataSources'] = $items;
$data['themepages'] = $this->ro->getAllThemePages();
$this->load->view('bulk_tag_index', $data);
}
function __construct(){
parent::__construct();
acl_enforce('ORCA_SOURCE_ADMIN');
}
} |
Fix android build for RN 0.47
createJSModules is no longer present. In order to ensure backwards
compatibility, just remove the Override tag for now. | /**
* Twilio Video for React Native.
*
* Authors:
* Ralph Pina <ralph.pina@gmail.com>
* Jonathan Chang <slycoder@gmail.com>
*/
package com.twiliorn.library;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TwilioPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
// Deprecated by RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new CustomTwilioVideoViewManager(),
new TwilioRemotePreviewManager(),
new TwilioVideoPreviewManager()
);
}
}
| /**
* Twilio Video for React Native.
*
* Authors:
* Ralph Pina <ralph.pina@gmail.com>
* Jonathan Chang <slycoder@gmail.com>
*/
package com.twiliorn.library;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TwilioPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new CustomTwilioVideoViewManager(),
new TwilioRemotePreviewManager(),
new TwilioVideoPreviewManager()
);
}
}
|
Move rabbit vars to globals | import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
RABBIT_USER = 'guest'
RABBIT_HOST = 'localhost'
app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST))
@app.task
def multiscanner_celery(filelist, config=multiscanner.CONFIG):
'''
TODO: Figure out how to do batching.
TODO: Add other ars + config options...
This function essentially takes in a file list and runs
multiscanner on them. Results are stored in the
storage configured in storage.ini.
Usage:
from celery_worker import multiscanner_celery
multiscanner_celery.delay([list, of, files, to, scan])
'''
storage_conf = multiscanner.common.get_storage_config_path(config)
storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf)
resultlist = multiscanner.multiscan(filelist, configfile=config)
results = multiscanner.parse_reports(resultlist, python=True)
storage_handler.store(results, wait=False)
storage_handler.close()
return results
| import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
app = Celery('celery_worker', broker='pyamqp://guest@localhost//')
@app.task
def multiscanner_celery(filelist, config=multiscanner.CONFIG):
'''
TODO: Add other ars + config options...
This function essentially takes in a file list and runs
multiscanner on them. Results are stored in the
storage configured in storage.ini.
Usage:
from celery_worker import multiscanner_celery
multiscanner_celery.delay([list, of, files, to, scan])
'''
storage_conf = multiscanner.common.get_storage_config_path(config)
storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf)
resultlist = multiscanner.multiscan(filelist, configfile=config)
results = multiscanner.parse_reports(resultlist, python=True)
storage_handler.store(results, wait=False)
storage_handler.close()
return results
|
ui: Add keyboardShouldPersistTaps to Topic List screen
Now that we have a search field and potentially a keyboard popped
make sure to process the first tap on the topic list. | /* @flow */
import React, { PureComponent } from 'react';
import { FlatList, StyleSheet } from 'react-native';
import type { Topic } from '../types';
import TopicItem from '../streams/TopicItem';
import { LoadingIndicator, SectionSeparatorBetween, SearchEmptyState } from '../common';
const styles = StyleSheet.create({
list: {
flex: 1,
flexDirection: 'column',
},
});
type Props = {
topics: ?(Topic[]),
onPress: (stream: string, topic: string) => void,
};
export default class TopicList extends PureComponent<Props> {
props: Props;
static defaultProps = {
showDescriptions: false,
showSwitch: false,
selected: false,
streams: [],
};
render() {
const { topics, onPress } = this.props;
if (!topics) {
return <LoadingIndicator size={40} />;
}
if (topics.length === 0) {
return <SearchEmptyState text="No topics found" />;
}
return (
<FlatList
keyboardShouldPersistTaps="always"
style={styles.list}
data={topics}
keyExtractor={item => item.name}
renderItem={({ item }) => (
<TopicItem name={item.name} isMuted={false} unreadCount={0} onPress={onPress} />
)}
SectionSeparatorComponent={SectionSeparatorBetween}
/>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { FlatList, StyleSheet } from 'react-native';
import type { Topic } from '../types';
import TopicItem from '../streams/TopicItem';
import { LoadingIndicator, SectionSeparatorBetween, SearchEmptyState } from '../common';
const styles = StyleSheet.create({
list: {
flex: 1,
flexDirection: 'column',
},
});
type Props = {
topics: ?(Topic[]),
onPress: (stream: string, topic: string) => void,
};
export default class TopicList extends PureComponent<Props> {
props: Props;
static defaultProps = {
showDescriptions: false,
showSwitch: false,
selected: false,
streams: [],
};
render() {
const { topics, onPress } = this.props;
if (!topics) {
return <LoadingIndicator size={40} />;
}
if (topics.length === 0) {
return <SearchEmptyState text="No topics found" />;
}
return (
<FlatList
style={styles.list}
data={topics}
keyExtractor={item => item.name}
renderItem={({ item }) => (
<TopicItem name={item.name} isMuted={false} unreadCount={0} onPress={onPress} />
)}
SectionSeparatorComponent={SectionSeparatorBetween}
/>
);
}
}
|
Create angular Category $resource service for data handling | app.factory('Category', function($resource) {
return $resource('/api/categories/:id',
{ id: '@resource_id' }, {
'search': { method: 'GET', isArray: true }
});
});
app.factory('SessionService', function($http, $state, $location) {
var bogusSession = injectedSession
, pre
, status;
function init() { // Logged in : Logged out
pre = checkSession() ? bogusSession.user : { name: 'Logged out', uid: '0' };
status = pre.uid != "0" ? true : false;
}
function checkSession() {
if(bogusSession != null) return Object.keys(bogusSession).length !== 0;
else return false;
}
init();
return {
pre: function() { return pre; },
status: function() { return status; },
logout: function() {
$http.get("/logout").then(function (data, status, headers, config) {
bogusSession = null; init();
if($state.current.name != 'signin') $state.go("index");
})
},
checkAuth: function() {
if(this.status() == false && $state.current.name != 'signin')
$location.path('/');
else
$location.path('/home');
}
};
});
|
app.factory('SessionService', function($http, $state, $location) {
var bogusSession = injectedSession
, pre
, status;
function init() { // Logged in : Logged out
pre = checkSession() ? bogusSession.user : { name: 'Logged out', uid: '0' };
status = pre.uid != "0" ? true : false;
}
function checkSession() {
if(bogusSession != null) return Object.keys(bogusSession).length !== 0;
else return false;
}
init();
return {
pre: function() { return pre; },
status: function() { return status; },
logout: function() {
$http.get("/logout").then(function (data, status, headers, config) {
bogusSession = null; init();
if($state.current.name != 'signin') $state.go("index");
})
},
checkAuth: function() {
if(this.status() == false && $state.current.name != 'signin')
$location.path('/');
else
$location.path('/home');
}
};
});
|
Use ipc module. Check for existence of Electron. | 'use strict'
const app = require('app')
const BrowserWindow = require('browser-window')
const ipc = require('ipc')
const Menu = require('menu')
const menuTemplate = require('./menu-template.js')
require('electron-debug')()
let mainWindow = null
function onClosed () {
mainWindow = null
}
function createMainWindow () {
const win = new BrowserWindow({
width: 920,
height: 620,
center: true,
'standard-window': false,
frame: false,
title: 'Blox Party'
})
win.loadUrl('file://' + __dirname + '/index.html')
win.on('closed', onClosed)
return win
}
ipc.on('quit', function () {
app.quit()
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate-with-no-open-windows', () => {
if (!mainWindow) mainWindow = createMainWindow()
})
app.on('ready', () => {
// Build menu only for OSX
if (Menu.sendActionToFirstResponder) {
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate))
}
mainWindow = createMainWindow()
})
| 'use strict'
const app = require('app')
const BrowserWindow = require('browser-window')
const Menu = require('menu')
const menuTemplate = require('./menu-template.js')
require('electron-debug')()
let mainWindow = null
function onClosed () {
mainWindow = null
}
function createMainWindow () {
const win = new BrowserWindow({
width: 920,
height: 620,
center: true,
'standard-window': false,
frame: false,
title: 'Blox Party'
})
win.loadUrl('file://' + __dirname + '/index.html')
win.on('closed', onClosed)
return win
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate-with-no-open-windows', () => {
if (!mainWindow) mainWindow = createMainWindow()
})
app.on('ready', () => {
// Build menu only for OSX
if (Menu.sendActionToFirstResponder) {
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate))
}
mainWindow = createMainWindow()
})
|
Clean up some extra spacing | <?php
namespace Cascade\Tests\Exceptions;
use Cascade\Exceptions\ExceptionWithContext;
class ExceptionWithContextTest extends \PHPUnit_Framework_TestCase
{
public function testItShouldPassThroughStandardDataToTheBaseExceptionClass()
{
$previousException = new \Exception('previousMessage');
$exception = new ExceptionWithContext('message', [], 42, $previousException);
$this->assertEquals('message', $exception->getMessage());
$this->assertEquals(42, $exception->getCode());
$this->assertSame($previousException, $exception->getPrevious());
}
public function testItShouldAllowTheContextToBeRetrieved()
{
$context = new \stdClass();
$exception = new ExceptionWithContext('message', $context);
$this->assertSame($context, $exception->getContext());
}
}
| <?php
namespace Cascade\Tests\Exceptions;
use Cascade\Exceptions\ExceptionWithContext;
class ExceptionWithContextTest extends \PHPUnit_Framework_TestCase
{
public function testItShouldPassThroughStandardDataToTheBaseExceptionClass()
{
$previousException = new \Exception('previousMessage');
$exception = new ExceptionWithContext('message', [], 42, $previousException);
$this->assertEquals('message', $exception->getMessage());
$this->assertEquals(42, $exception->getCode());
$this->assertSame($previousException, $exception->getPrevious());
}
public function testItShouldAllowTheContextToBeRetrieved()
{
$context = new \stdClass();
$exception = new ExceptionWithContext('message', $context);
$this->assertSame($context, $exception->getContext());
}
}
|
Revert note to tag the version after publish | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py")
VERSION = None
for line in open(VERSIONFILE, "r").readlines():
if line.startswith('__version__'):
VERSION = line.split('"')[1]
if not VERSION:
raise RuntimeError('No version defined in textx.__init__.py')
if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep wheel"):
print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
sys.exit()
if os.system("pip list | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
print("You probably want to also tag the version now:")
print(" git tag -a {0} -m 'version {0}'".format(VERSION))
print(" git push --tags")
sys.exit()
setup(version=VERSION)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py")
VERSION = None
for line in open(VERSIONFILE, "r").readlines():
if line.startswith('__version__'):
VERSION = line.split('"')[1]
if not VERSION:
raise RuntimeError('No version defined in textx.__init__.py')
if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep wheel"):
print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
sys.exit()
if os.system("pip list | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
sys.exit()
setup(version=VERSION)
|
Test updated props passed through to a TextRegion | import { expect, json, stub } from '../../spec_helper'
import { parsePost } from '../../../src/components/parsers/PostParser'
describe('PostParser', () => {
it('#render', () => {
const post = stub('post', { authorId: '42' })
stub('user', { id: '42', username: 'forty_two' })
const cells = parsePost(post, json)
expect(cells.length).to.equal(3)
const header = cells[0]
expect(header.props.className).to.equal('PostHeader')
expect(header.key).to.equal('PostHeader_1')
const body = cells[1]
const textRegion = body.props.children[0]
expect(textRegion.key).to.equal('TextRegion_0')
expect(textRegion.props.content).to.contain('Text Region')
expect(textRegion.props.postDetailPath).to.equal('/forty_two/post/token')
const footer = cells[2]
expect(footer.props.author.username).to.equal('forty_two')
expect(footer.key).to.equal('PostTools_1')
})
})
| import { expect, json, stub } from '../../spec_helper'
import { parsePost } from '../../../src/components/parsers/PostParser'
describe('PostParser', () => {
it('#render', () => {
const post = stub('post', { authorId: '42' })
stub('user', { id: '42', username: 'forty_two' })
const cells = parsePost(post, json)
expect(cells.length).to.equal(3)
const header = cells[0]
expect(header.props.className).to.equal('PostHeader')
expect(header.key).to.equal('PostHeader_1')
const body = cells[1]
const textRegion = body.props.children[0]
expect(textRegion.props.className).to.equal('TextRegion')
expect(textRegion.key).to.equal('TextRegion_0')
const footer = cells[2]
expect(footer.props.author.username).to.equal('forty_two')
expect(footer.key).to.equal('PostTools_1')
})
})
|
Use temporary dir that can be fully deleted | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.testtools;
import java.io.*;
import static org.junit.Assert.fail;
/**
* Base class for testcases doing tests with files.
*/
public abstract class FileBasedTestCase {
private static volatile File testDir;
@SuppressWarnings("ResultOfMethodCallIgnored")
public static File getTestDirectory() {
if (testDir == null) {
testDir = new File("target/test_io/").getAbsoluteFile();
}
testDir.mkdirs();
if (!testDir.isDirectory()) {
fail("Could not create directory " + testDir);
}
return testDir;
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.testtools;
import java.io.*;
/**
* Base class for testcases doing tests with files.
*/
public abstract class FileBasedTestCase {
private static volatile File testDir;
@SuppressWarnings("ResultOfMethodCallIgnored")
public static File getTestDirectory() {
if (testDir == null) {
testDir = new File("test/io/").getAbsoluteFile();
}
testDir.mkdirs();
return testDir;
}
}
|
Fix OnAccess job link for JobConfig | """
Job metadata stored along side the code
"""
from yaml_model import LoadOnAccess, Model, OnAccess
def get_job(slug):
"""
Wrapper to import, and return a Job object for the JobConfig to avoid
cyclic import
"""
from dockci.models.job import Job
return Job.load(slug)
class JobConfig(Model): # pylint:disable=too-few-public-methods
"""
Job config, loaded from the repo
"""
slug = 'dockci.yaml'
job = OnAccess(lambda self: get_job(self.job_slug))
job_slug = OnAccess(lambda self: self.job.slug) # TODO infinite loop
job_output = LoadOnAccess(default=lambda _: {})
services = LoadOnAccess(default=lambda _: {})
utilities = LoadOnAccess(default=lambda _: [])
dockerfile = LoadOnAccess(default='Dockerfile')
repo_name = LoadOnAccess(default=lambda self: self.job.project.slug)
skip_tests = LoadOnAccess(default=False)
def __init__(self, job):
super(JobConfig, self).__init__()
assert job is not None, "Job is given"
self.job = job
self.job_slug = job.slug
def data_file_path(self):
# Our data file path is <job output>/<slug>
return self.job.job_output_path().join(JobConfig.slug)
| """
Job metadata stored along side the code
"""
from yaml_model import LoadOnAccess, Model, OnAccess
def get_job(slug):
"""
Wrapper to import, and return a Job object for the JobConfig to avoid
cyclic import
"""
from dockci.models.job import Job
return Job.query.filter_by(slug=slug).first()
class JobConfig(Model): # pylint:disable=too-few-public-methods
"""
Job config, loaded from the repo
"""
slug = 'dockci.yaml'
job = OnAccess(lambda self: get_job(self.job_slug))
job_slug = OnAccess(lambda self: self.job.slug) # TODO infinite loop
job_output = LoadOnAccess(default=lambda _: {})
services = LoadOnAccess(default=lambda _: {})
utilities = LoadOnAccess(default=lambda _: [])
dockerfile = LoadOnAccess(default='Dockerfile')
repo_name = LoadOnAccess(default=lambda self: self.job.project.slug)
skip_tests = LoadOnAccess(default=False)
def __init__(self, job):
super(JobConfig, self).__init__()
assert job is not None, "Job is given"
self.job = job
self.job_slug = job.slug
def data_file_path(self):
# Our data file path is <job output>/<slug>
return self.job.job_output_path().join(JobConfig.slug)
|
Set up old data conversion on update
- we'll probably remove this after the first update?
- either way, if it's left and runs a second time, it will still run fine without the data in local storage without doing anything | import tldjs from 'tldjs'
import 'src/activity-logger/background'
import 'src/omnibar'
import { installTimeStorageKey } from 'src/imports/background'
import convertOldData from 'src/util/old-data-converter'
async function openOverview() {
const [ currentTab ] = await browser.tabs.query({ active: true })
if (currentTab && currentTab.url) {
const validUrl = tldjs.isValid(currentTab.url)
if (validUrl) {
return browser.tabs.create({
url: '/overview/overview.html',
})
}
}
browser.tabs.update({
url: '/overview/overview.html',
})
}
// Open the overview when the extension's button is clicked
browser.browserAction.onClicked.addListener(() => {
openOverview()
})
browser.commands.onCommand.addListener(command => {
if (command === 'openOverview') {
openOverview()
}
})
browser.runtime.onInstalled.addListener(details => {
// Store the timestamp of when the extension was installed in local storage
if (details.reason === 'install') {
browser.storage.local.set({ [installTimeStorageKey]: Date.now() })
}
// Attempt convert of old extension data on extension update
if (details.reason === 'update') {
await convertOldData({ setAsStubs: true, concurrency: 15 })
}
})
| import tldjs from 'tldjs'
import 'src/activity-logger/background'
import 'src/omnibar'
import { installTimeStorageKey } from 'src/imports/background'
async function openOverview() {
const [ currentTab ] = await browser.tabs.query({ active: true })
if (currentTab && currentTab.url) {
const validUrl = tldjs.isValid(currentTab.url)
if (validUrl) {
return browser.tabs.create({
url: '/overview/overview.html',
})
}
}
browser.tabs.update({
url: '/overview/overview.html',
})
}
// Open the overview when the extension's button is clicked
browser.browserAction.onClicked.addListener(() => {
openOverview()
})
browser.commands.onCommand.addListener(command => {
if (command === 'openOverview') {
openOverview()
}
})
// Store the timestamp of when the extension was installed in local storage
browser.runtime.onInstalled.addListener(details => {
if (details.reason === 'install') {
browser.storage.local.set({ [installTimeStorageKey]: Date.now() })
}
})
|
Improve JavaScript for generating section listing | function create_section_listing() {
$('div#sidebar h3').click(function(e) {
window.scrollTo(0, 0);
});
$('.section_title').each(function (i, e) {
var content = e.innerText || e.textContent
$("div#sidebar #section_listing").append("<a id='" + e.id + "_link'>" + content + "</a>");
just_added = $("div#sidebar #section_listing").children().last();
if (e.tagName == "H2") {
just_added.addClass("major");
}
else {
just_added.addClass("minor");
}
});
$('#sidebar a').click(function(e) {
section_id = $(this).attr("id").replace("_link", "");
window.scrollTo(0, $("#" + section_id)[0].offsetTop);
})
} | function create_section_listing() {
$('div#sidebar h3').click(function(e) {
window.scrollTo(0, 0);
});
$('.section_title').each(function (i, e) {
$("div#sidebar #section_listing").append("<a id='" + e.id + "_link'>" + (e.innerText || e.innerContent) + "</a>");
just_added = $("div#sidebar #section_listing").children().last();
if (e.tagName == "H2") {
just_added.addClass("major");
}
else {
just_added.addClass("minor");
}
});
$('#sidebar a').click(function(e) {
section_id = $(this).attr("id").replace("_link", "");
window.scrollTo(0, $("#" + section_id)[0].offsetTop);
})
} |
Fix for object clone (defaultConfig was being overwritten from the settings) | 'use strict';
var copay = require('copay');
var _ = require('underscore');
var config = defaultConfig;
var localConfig = JSON.parse(localStorage.getItem('config'));
var defaults = JSON.parse(JSON.stringify(defaultConfig));
if (localConfig) {
var cmv = copay.version.split('.')[1];
var lmv = localConfig.version ? localConfig.version.split('.')[1] : '-1';
if (cmv === lmv) {
_.each(localConfig, function(value, key) {
config[key] = value;
});
}
}
var log = function() {
if (config.verbose) console.log(arguments);
}
var modules = [
'ngRoute',
'angularMoment',
'mm.foundation',
'monospaced.qrcode',
'ngIdle',
'gettext',
'copayApp.filters',
'copayApp.services',
'copayApp.controllers',
'copayApp.directives',
];
if (Object.keys(config.plugins).length)
modules.push('angularLoad');
var copayApp = window.copayApp = angular.module('copayApp', modules);
copayApp.value('defaults', defaults);
copayApp.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'mailto:**'
]);
});
angular.module('copayApp.filters', []);
angular.module('copayApp.services', []);
angular.module('copayApp.controllers', []);
angular.module('copayApp.directives', []);
| 'use strict';
var copay = require('copay');
var _ = require('underscore');
var config = defaultConfig;
var localConfig = JSON.parse(localStorage.getItem('config'));
if (localConfig) {
var cmv = copay.version.split('.')[1];
var lmv = localConfig.version ? localConfig.version.split('.')[1] : '-1';
if (cmv === lmv) {
_.each(localConfig, function(value, key) {
config[key] = value;
});
}
}
var log = function() {
if (config.verbose) console.log(arguments);
}
var modules = [
'ngRoute',
'angularMoment',
'mm.foundation',
'monospaced.qrcode',
'ngIdle',
'gettext',
'copayApp.filters',
'copayApp.services',
'copayApp.controllers',
'copayApp.directives',
];
if (Object.keys(config.plugins).length)
modules.push('angularLoad');
var copayApp = window.copayApp = angular.module('copayApp', modules);
copayApp.value('defaults', defaultConfig);
copayApp.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'mailto:**'
]);
});
angular.module('copayApp.filters', []);
angular.module('copayApp.services', []);
angular.module('copayApp.controllers', []);
angular.module('copayApp.directives', []);
|
OF-2148: Change to wider type to prevent information loss
Prevent a possible issue where a wider type gets added to narrower type.
Ideally, this is replaced by proper types (eg: Duration, Instant), but the cost/benefit of applying that larger change does not pay off. | /*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.database;
/**
* Simple class for tracking profiling stats for individual SQL queries.
*
* @author Jive Software
*/
public class ProfiledConnectionEntry {
/**
* The SQL query.
*/
public String sql;
/**
* Number of times the query has been executed.
*/
public int count;
/**
* The total time spent executing the query (in milliseconds).
*/
public long totalTime;
public ProfiledConnectionEntry(String sql) {
this.sql = sql;
count = 0;
totalTime = 0;
}
}
| /*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.database;
/**
* Simple class for tracking profiling stats for individual SQL queries.
*
* @author Jive Software
*/
public class ProfiledConnectionEntry {
/**
* The SQL query.
*/
public String sql;
/**
* Number of times the query has been executed.
*/
public int count;
/**
* The total time spent executing the query (in milliseconds).
*/
public int totalTime;
public ProfiledConnectionEntry(String sql) {
this.sql = sql;
count = 0;
totalTime = 0;
}
}
|
Use _.each instead of forEach
To be sure that IE8 and other older browers will not complain. | /**
*
* Displays a single property of an object.
*
* ## Examples
*
* <div
* data-hull-widget="property@hull"
* data-hull-id="me"
* data-hull-property="name"
* data-hull-default-text="Not found"
* ></div>
*
* ## Options
*
* - `id`: Required. The id of the object for which we want to display a property.
* - `property`: Required. The name of the property to be displayed. Can be a path
* if the property is nested (_eg_ `stats.likes`)
* - `default-text`: The text to be displayed if the value does not exist
*
* ## Template
*
* - `property`: Displays the property with no markup. Markup must be in the parents widget
* for easier customization
*
*/
define({
type: 'Hull',
templates: [
'property'
],
datasources: {
object: ':id'
},
refreshEvents: ['model.hull.me.change'],
beforeRender: function(data) {
"use strict";
var defaultText = this.options.defaultText || 'No value';
var value = this.findProp(data.object, this.options.property);
return {
property: value !== undefined ? value : defaultText
};
},
findProp: function (obj, prop) {
"use strict";
var parts = prop.split('.');
_.each(parts, function(p) {
obj = !obj ? undefined : obj[p];
});
return obj;
}
});
| /**
*
* Displays a single property of an object.
*
* ## Examples
*
* <div
* data-hull-widget="property@hull"
* data-hull-id="me"
* data-hull-property="name"
* data-hull-default-text="Not found"
* ></div>
*
* ## Options
*
* - `id`: Required. The id of the object for which we want to display a property.
* - `property`: Required. The name of the property to be displayed. Can be a path
* if the property is nested (_eg_ `stats.likes`)
* - `default-text`: The text to be displayed if the value does not exist
*
* ## Template
*
* - `property`: Displays the property with no markup. Markup must be in the parents widget
* for easier customization
*
*/
define({
type: 'Hull',
templates: [
'property'
],
datasources: {
object: ':id'
},
refreshEvents: ['model.hull.me.change'],
beforeRender: function(data) {
"use strict";
var defaultText = this.options.defaultText || 'No value';
var value = this.findProp(data.object, this.options.property);
return {
property: value !== undefined ? value : defaultText
};
},
findProp: function (obj, prop) {
"use strict";
prop.split('.').forEach(function (_p) {
obj = !obj ? undefined : obj[_p];
});
return obj;
}
});
|
Add data property for DataBroker class | import glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
| import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
|
Correct category lookup on url kwarg to use case insensitive. | from django.views.generic import DetailView, ListView
from django.shortcuts import get_object_or_404
from cjdata.models import Dataset, Category
from cjdata.search.query import sqs
class DatasetDetailView(DetailView):
model = Dataset
slug_field = 'uuid'
slug_url_kwarg = 'uuid'
def get_context_data(self, **kwargs):
context = super(DatasetDetailView, self).get_context_data(**kwargs)
context['more_like_this'] = sqs.more_like_this(self.object)[:100]
return context
class CategoryDatasetsView(ListView):
model = Dataset
paginate_by = 50
def get_queryset(self):
path_arg = self.kwargs.get('path', None)
self.category = get_object_or_404(Category, path__iexact=path_arg.replace('-', ' '))
return Dataset.objects.filter(categories__path=self.category.path)
def get_context_data(self, **kwargs):
context = super(CategoryDatasetsView, self).get_context_data(**kwargs)
context['category'] = self.category
return context
| from django.views.generic import DetailView, ListView
from django.shortcuts import get_object_or_404
from cjdata.models import Dataset, Category
from cjdata.search.query import sqs
class DatasetDetailView(DetailView):
model = Dataset
slug_field = 'uuid'
slug_url_kwarg = 'uuid'
def get_context_data(self, **kwargs):
context = super(DatasetDetailView, self).get_context_data(**kwargs)
context['more_like_this'] = sqs.more_like_this(self.object)[:100]
return context
class CategoryDatasetsView(ListView):
model = Dataset
paginate_by = 50
def get_queryset(self):
path_arg = self.kwargs.get('path', None)
self.category = get_object_or_404(Category, path=path_arg.replace('-', ' '))
return Dataset.objects.filter(categories__path__iexact=self.category.path)
def get_context_data(self, **kwargs):
context = super(CategoryDatasetsView, self).get_context_data(**kwargs)
context['category'] = self.category
return context
|
[Theme] Make debugging easier by not isolating test client | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ThemeBundle\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Client;
/**
* @author Kamil Kokot <kamil.kokot@lakion.com>
*/
class ThemeBundleTestCase extends WebTestCase
{
const TEST_CASE = 'DefaultTestCase';
protected function setUp()
{
parent::setUp();
$this->deleteTmpDir(self::TEST_CASE);
}
protected function tearDown()
{
parent::tearDown();
$this->deleteTmpDir(self::TEST_CASE);
}
/**
* @return Client
*/
protected function getClient()
{
return $this->createClient(['test_case' => self::TEST_CASE, 'root_config' => 'config.yml']);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ThemeBundle\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Client;
/**
* @author Kamil Kokot <kamil.kokot@lakion.com>
*/
class ThemeBundleTestCase extends WebTestCase
{
const TEST_CASE = 'DefaultTestCase';
protected function setUp()
{
parent::setUp();
$this->deleteTmpDir(self::TEST_CASE);
}
protected function tearDown()
{
parent::tearDown();
$this->deleteTmpDir(self::TEST_CASE);
}
/**
* @return Client
*/
protected function getClient()
{
$client = $this->createClient(['test_case' => self::TEST_CASE, 'root_config' => 'config.yml']);
try {
$client->insulate();
} catch (\RuntimeException $e) {
// Don't insulate requests if not possible to do so.
}
return $client;
}
}
|
Change logout-url to profile page. | 'use strict';
var config = require('./config.webgme'),
path = require('path'),
os = require('os');
config.server.port = 8001;
config.authentication.enable = true;
config.authentication.allowGuests = true;
config.authentication.guestAccount = 'demo';
//config.authentication.logOutUrl = 'http://' + os.hostname(); // FIXME: use config.server.https.enable to decide on protocol
config.authentication.jwt.privateKey = path.join(__dirname, '..', '..', '..', 'token_keys', 'private_key');
config.authentication.jwt.publicKey = path.join(__dirname, '..', '..', '..', 'token_keys', 'public_key');
config.rest.secure = true;
config.plugin.allowServerExecution = false;
config.executor.enable = false;
config.addOn.enable = false;
config.storage.emitCommittedCoreObjects = true;
config.mongo.uri = 'mongodb://127.0.0.1:27017/webgme';
config.seedProjects.basePaths.push('./seeds');
config.seedProjects.defaultProject = 'Boilerplate';
config.server.behindSecureProxy = true;
//TODO This should probably not be configured from here (for now it will do)
config.visualization.svgDirs.push('./node_modules/power/Icons');
module.exports = config; | 'use strict';
var config = require('./config.webgme'),
path = require('path'),
os = require('os');
config.server.port = 8001;
config.authentication.enable = true;
config.authentication.allowGuests = true;
config.authentication.guestAccount = 'demo';
config.authentication.logOutUrl = 'http://' + os.hostname(); // FIXME: use config.server.https.enable to decide on protocol
config.authentication.jwt.privateKey = path.join(__dirname, '..', '..', '..', 'token_keys', 'private_key');
config.authentication.jwt.publicKey = path.join(__dirname, '..', '..', '..', 'token_keys', 'public_key');
config.rest.secure = true;
config.plugin.allowServerExecution = false;
config.executor.enable = false;
config.addOn.enable = false;
config.storage.emitCommittedCoreObjects = true;
config.mongo.uri = 'mongodb://127.0.0.1:27017/webgme';
config.seedProjects.basePaths.push('./seeds');
config.seedProjects.defaultProject = 'Boilerplate';
config.server.behindSecureProxy = true;
//TODO This should probably not be configured from here (for now it will do)
config.visualization.svgDirs.push('./node_modules/power/Icons');
module.exports = config; |
Add haystack connections simples engine om opps | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
|
Update list of dead trackers | package uploadService
import (
"strings"
)
func CheckTrackers(trackers []string) bool {
// TODO: move to runtime configuration
var deadTrackers = []string{ // substring matches!
"://open.nyaatorrents.info:6544",
"://tracker.openbittorrent.com:80",
"://tracker.publicbt.com:80",
"://stats.anisource.net:2710",
"://exodus.desync.com",
"://open.demonii.com:1337",
"://tracker.istole.it:80",
"://tracker.ccc.de:80",
"://bt2.careland.com.cn:6969",
"://announce.torrentsmd.com:8080",
"://open.demonii.com:1337",
"://tracker.btcake.com",
"://tracker.prq.to",
"://bt.rghost.net"}
var numGood int
for _, t := range trackers {
good := true
for _, check := range deadTrackers {
if strings.Contains(t, check) {
good = false
}
}
if good {
numGood++
}
}
return numGood > 0
}
| package uploadService
import (
"strings"
)
func CheckTrackers(trackers []string) bool {
// TODO: move to runtime configuration
var deadTrackers = []string{ // substring matches!
"://open.nyaatorrents.info:6544",
"://tracker.openbittorrent.com:80",
"://tracker.publicbt.com:80",
"://stats.anisource.net:2710",
"://exodus.desync.com",
"://open.demonii.com:1337",
"://tracker.istole.it:80",
"://tracker.ccc.de:80",
"://bt2.careland.com.cn:6969",
"://announce.torrentsmd.com:8080"}
var numGood int
for _, t := range trackers {
good := true
for _, check := range deadTrackers {
if strings.Contains(t, check) {
good = false
}
}
if good {
numGood++
}
}
return numGood > 0
}
|
Fix bug in Pax Mininet node class | # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man"
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
def terminate(self):
# Remove iptables rules
for intf in self.intfList():
self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super(PaxNode, self).terminate()
| # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man"
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
def terminate( self ):
# Remove iptables rules
for intf in self.intfList():
runCmd(net, nat0, "iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super( NAT, self ).terminate()
|
Add new Flat UI Pro jquery.ui.button dependency and default bootstrap-on-rails requires | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.ui.button
//= require jquery.ui.datepicker
//= require jquery.ui.slider.js
//= require jquery.ui.spinner.js
//= require jquery.ui.tooltip.js
//= require jquery.ui.effect.js
//= require jquery_ujs
//= require flatuipro
//= require turbolinks
//= require bootstrap/affix
//= require bootstrap/alert
//= require bootstrap/button
//= require bootstrap/carousel
//= require bootstrap/collapse
//= require bootstrap/dropdown
//= require bootstrap/modal
//= require bootstrap/tooltip
//= require bootstrap/popover
//= require bootstrap/scrollspy
//= require bootstrap/tab
//= require bootstrap/transition
//= require_tree .
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery.ui.datepicker
//= require jquery.ui.slider.js
//= require jquery.ui.spinner.js
//= require jquery.ui.tooltip.js
//= require jquery.ui.effect.js
//= require jquery_ujs
//= require twitter/bootstrap
//= require flatuipro
//= require_tree .
|
Add child_class on list filter PublishableAdmin | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
|
Change to use new PSR-4 loaded libraries in development. | <?php
require 'vendor/autoload.php';
require_once 'config.php';
$sendgrid = new SendGrid\Client($sendgrid_api_key, ["turn_off_ssl_verification" => TRUE]);
$email = new SendGrid\Email();
$email->addTo($to)
->setFrom($to)
->setSubject('[sendgrid-php-example] Pachyderm named %yourname%')
->setText('The elephant in the room is blue!')
->setHtml('<strong>The %elephant% in the room is blue!</strong>')
->addSubstitution('%yourname%', ['Mr. ElePHPant'])
->addSubstitution('%elephant%', ['elephant'])
->addHeader('X-Sent-Using', 'SendGrid-API')
->addHeader('X-Transport', 'web')
->addAttachment('./phplogo.gif', 'php.gif');
$response = $sendgrid->send($email);
var_dump($response);
| <?php
require 'vendor/autoload.php';
require_once 'config.php';
$sendgrid = new SendGrid($sendgrid_api_key, ["turn_off_ssl_verification" => TRUE]);
$email = new SendGrid\Email();
$email->addTo($to)
->setFrom($to)
->setSubject('[sendgrid-php-example] Pachyderm named %yourname%')
->setText('The elephant in the room is blue!')
->setHtml('<strong>The %elephant% in the room is blue!</strong>')
->addSubstitution('%yourname%', ['Mr. ElePHPant'])
->addSubstitution('%elephant%', ['elephant'])
->addHeader('X-Sent-Using', 'SendGrid-API')
->addHeader('X-Transport', 'web')
->addAttachment('./phplogo.gif', 'php.gif');
$response = $sendgrid->send($email);
var_dump($response);
|
Add the <projectName> to the generate command's help | #! /usr/bin/env node
// __ _____ _____ _____ _____ _____
// | | | | | | __ | __| __ |
// | |__| | | | | | __ -| __| -|
// |_____|_____|_|_|_|_____|_____|__|__|
const program = require('commander');
const packagejson = require('./package.json');
program
.version(packagejson.version)
.command('generate <projectName>', 'generate your admin panel application based on your database schema')
.command('update', 'update your models\'s definition according to your database schema')
.command('deploy', 'deploy your admin panel application to production')
.command('user', 'show your current logged user')
.command('login', 'sign in to your Forest account')
.command('logout', 'sign out of your Forest account')
.parse(process.argv);
| #! /usr/bin/env node
// __ _____ _____ _____ _____ _____
// | | | | | | __ | __| __ |
// | |__| | | | | | __ -| __| -|
// |_____|_____|_|_|_|_____|_____|__|__|
const program = require('commander');
const packagejson = require('./package.json');
program
.version(packagejson.version)
.command('generate', 'generate your admin panel application based on your database schema')
.command('update', 'update your models\'s definition according to your database schema')
.command('deploy', 'deploy your admin panel application to production')
.command('user', 'show your current logged user')
.command('login', 'sign in to your Forest account')
.command('logout', 'sign out of your Forest account')
.parse(process.argv);
|
Use the correct redis connection in tests | import os
os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
| import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
settings.REDIS_URL = "redis://localhost:6379/5"
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
class BaseTestCase(TestCase):
def setUp(self):
models.create_db(True, True)
models.init_db()
def tearDown(self):
models.db.close_db(None)
models.create_db(False, True)
redis_connection.flushdb()
def assertResponseEqual(self, expected, actual):
for k, v in expected.iteritems():
if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime):
continue
if isinstance(v, list):
continue
if isinstance(v, dict):
self.assertResponseEqual(v, actual[k])
continue
self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
|
Fix download link in file settings dialog
Event listener on parent element prevented default. | /**
* Display view for a link to a URL, to be used like an input view.
*
* @param {string} [options.propertyName]
* Target URL for link
*
* @see {@link module:pageflow/ui.pageflow.inputView pageflow.inputView} for further options
* @class
* @memberof module:pageflow/ui
*/
pageflow.UrlDisplayView = Backbone.Marionette.ItemView.extend({
mixins: [pageflow.inputView],
template: 'pageflow/ui/templates/inputs/url_display',
ui: {
link: 'a'
},
modelEvents: {
'change': 'update'
},
events: {
'click a': function(event) {
// Ensure default is not prevented by parent event listener.
event.stopPropagation();
}
},
onRender: function() {
this.update();
},
update: function() {
this.ui.link.attr('href', this.model.get(this.options.propertyName));
this.ui.link.toggle(this.model.isUploaded() && !_.isEmpty(this.model.get('original_url')));
}
});
| /**
* Display view for a link to a URL, to be used like an input view.
*
* @param {string} [options.propertyName]
* Target URL for link
*
* @see {@link module:pageflow/ui.pageflow.inputView pageflow.inputView} for further options
* @class
* @memberof module:pageflow/ui
*/
pageflow.UrlDisplayView = Backbone.Marionette.ItemView.extend({
mixins: [pageflow.inputView],
template: 'pageflow/ui/templates/inputs/url_display',
ui: {
link: 'a'
},
modelEvents: {
'change': 'update'
},
onRender: function() {
this.update();
},
update: function() {
this.ui.link.attr('href', this.model.get(this.options.propertyName));
this.ui.link.toggle(this.model.isUploaded() && !_.isEmpty(this.model.get('original_url')));
}
});
|
Undo setting CI_DEBUG to true by default
Change-Id: I24ca35ada7591e93413cdda1905ee01f77131889
Signed-off-by: Romanos Skiadas <2ae8a933f732975064e7c256d0625d1633389b98@intracom-telecom.com> | import os
import re
default_envs = {
'NODE_NAME': 'unknown_pod',
'CI_DEBUG': 'false',
'DEPLOY_SCENARIO': 'os-nosdn-nofeature-noha',
'DEPLOY_TYPE': 'virt',
'INSTALLER_TYPE': None,
'INSTALLER_IP': None,
'BUILD_TAG': None,
'OS_ENDPOINT_TYPE': None,
'OS_AUTH_URL': None
}
class Environment(object):
def __init__(self):
for k, v in os.environ.iteritems():
self.__setattr__(k, v)
for k, v in default_envs.iteritems():
if k not in os.environ:
self.__setattr__(k, v)
self._set_ci_run()
self._set_ci_loop()
def _set_ci_run(self):
if self.BUILD_TAG:
self.IS_CI_RUN = True
else:
self.IS_CI_RUN = False
def _set_ci_loop(self):
if self.BUILD_TAG and re.search("daily", self.BUILD_TAG):
self.CI_LOOP = "daily"
else:
self.CI_LOOP = "weekly"
ENV = Environment()
| import os
import re
default_envs = {
'NODE_NAME': 'unknown_pod',
'CI_DEBUG': 'true',
'DEPLOY_SCENARIO': 'os-nosdn-nofeature-noha',
'DEPLOY_TYPE': 'virt',
'INSTALLER_TYPE': None,
'INSTALLER_IP': None,
'BUILD_TAG': None,
'OS_ENDPOINT_TYPE': None,
'OS_AUTH_URL': None
}
class Environment(object):
def __init__(self):
for k, v in os.environ.iteritems():
self.__setattr__(k, v)
for k, v in default_envs.iteritems():
if k not in os.environ:
self.__setattr__(k, v)
self._set_ci_run()
self._set_ci_loop()
def _set_ci_run(self):
if self.BUILD_TAG:
self.IS_CI_RUN = True
else:
self.IS_CI_RUN = False
def _set_ci_loop(self):
if self.BUILD_TAG and re.search("daily", self.BUILD_TAG):
self.CI_LOOP = "daily"
else:
self.CI_LOOP = "weekly"
ENV = Environment()
|
Fix comment - tooltips expand on hover | import assert from 'assert';
import { Tooltips } from './Tooltips';
import { Utils } from '../../tests/Utils';
const selectors = {
toggler: `.js-tooltip-toggle`,
toggleable: `.js-tooltip`,
collapsed: `.is-invisible`,
};
describe(`Tooltip`, () => {
beforeEach(() => {
const template = nunjucks.render(`tooltips/Tooltips.test.html`);
document.body.insertAdjacentHTML(`afterbegin`, template);
});
afterEach(() => {
const tooltips = document.querySelector(`#tooltips`);
tooltips.parentNode.removeChild(tooltips);
});
it(`should initialize with hidden tooltips`, () => {
const togglerSelector = selectors.toggler;
const tooltipSelector = selectors.toggleable;
const tooltips = document.querySelectorAll(tooltipSelector);
Tooltips.tooltip({ togglerSelector, tooltipSelector });
[...tooltips].forEach((tooltip) => {
assert(Utils.isHidden(tooltip));
});
});
it(`should expand on hover`, () => {
const firstToggler = document.querySelector(selectors.toggler);
const firstTooltip = firstToggler.parentNode.querySelector(selectors.toggleable);
Tooltips.tooltip({ togglerSelector: selectors.toggler, tooltipSelector: selectors.toggleable });
// simulate click
firstToggler.dispatchEvent(new Event(`pointerenter`));
assert(!Utils.isHidden(firstTooltip));
});
});
| import assert from 'assert';
import { Tooltips } from './Tooltips';
import { Utils } from '../../tests/Utils';
const selectors = {
toggler: `.js-tooltip-toggle`,
toggleable: `.js-tooltip`,
collapsed: `.is-invisible`,
};
describe(`Tooltip`, () => {
beforeEach(() => {
const template = nunjucks.render(`tooltips/Tooltips.test.html`);
document.body.insertAdjacentHTML(`afterbegin`, template);
});
afterEach(() => {
const tooltips = document.querySelector(`#tooltips`);
tooltips.parentNode.removeChild(tooltips);
});
it(`should initialize with hidden tooltips`, () => {
const togglerSelector = selectors.toggler;
const tooltipSelector = selectors.toggleable;
const tooltips = document.querySelectorAll(tooltipSelector);
Tooltips.tooltip({ togglerSelector, tooltipSelector });
[...tooltips].forEach((tooltip) => {
assert(Utils.isHidden(tooltip));
});
});
it(`should expand on click`, () => {
const firstToggler = document.querySelector(selectors.toggler);
const firstTooltip = firstToggler.parentNode.querySelector(selectors.toggleable);
Tooltips.tooltip({ togglerSelector: selectors.toggler, tooltipSelector: selectors.toggleable });
// simulate click
firstToggler.dispatchEvent(new Event(`pointerenter`));
assert(!Utils.isHidden(firstTooltip));
});
});
|
Use repr so it's more obvious what the problem is | import re
import os
from django.core import checks
from django.conf import settings
re_url = re.compile(r'\shref="(?P<url>/[^"]*)"')
@checks.register()
def hardcoded_urls(app_configs, **kwargs):
for x in settings.TEMPLATES:
for y in x['DIRS']:
for root, _, filenames in os.walk(y):
for z in filenames:
fullpath = os.path.join(root, z)
with open(fullpath) as f:
html = f.read()
for m in re_url.finditer(html):
yield checks.Error("%s contains hardcoded URL %r" % (
fullpath,
m.group('url'),
), id='takeyourmeds.utils.E001')
| import re
import os
from django.core import checks
from django.conf import settings
re_url = re.compile(r'\shref="(?P<url>/[^"]*)"')
@checks.register()
def hardcoded_urls(app_configs, **kwargs):
for x in settings.TEMPLATES:
for y in x['DIRS']:
for root, _, filenames in os.walk(y):
for z in filenames:
fullpath = os.path.join(root, z)
with open(fullpath) as f:
html = f.read()
for m in re_url.finditer(html):
yield checks.Error("%s contains hardcoded URL %s" % (
fullpath,
m.group('url'),
), id='takeyourmeds.utils.E001')
|
Drop the default number of backend connections to 4. | var path = require('path'),
fs = require('fs'),
log4js = require('log4js');
var config = {
DNODE_PORT: 0xC5EA,
SEARCH_REPO: path.join(__dirname, "../../linux"),
SEARCH_REF: "v3.0",
SEARCH_ARGS: [],
BACKEND_CONNECTIONS: 4,
BACKENDS: [
["localhost", 0xC5EA]
],
LOG4JS_CONFIG: path.join(__dirname, "log4js.json")
};
try {
fs.statSync(path.join(__dirname, 'config.local.js'));
var local = require('./config.local.js');
Object.keys(local).forEach(
function (k){
config[k] = local[k]
})
} catch (e) {
}
log4js.configure(config.LOG4JS_CONFIG);
module.exports = config;
| var path = require('path'),
fs = require('fs'),
log4js = require('log4js');
var config = {
DNODE_PORT: 0xC5EA,
SEARCH_REPO: path.join(__dirname, "../../linux"),
SEARCH_REF: "v3.0",
SEARCH_ARGS: [],
BACKEND_CONNECTIONS: 8,
BACKENDS: [
["localhost", 0xC5EA]
],
LOG4JS_CONFIG: path.join(__dirname, "log4js.json")
};
try {
fs.statSync(path.join(__dirname, 'config.local.js'));
var local = require('./config.local.js');
Object.keys(local).forEach(
function (k){
config[k] = local[k]
})
} catch (e) {
}
log4js.configure(config.LOG4JS_CONFIG);
module.exports = config;
|
Add origin to option setting failure | 'use strict'
var commentMarker = require('mdast-comment-marker')
module.exports = commentconfig
var origin = 'remark-comment-config:invalid-options'
// Modify `processor` to read configuration from comments.
function commentconfig() {
var proto = this.Parser && this.Parser.prototype
var Compiler = this.Compiler
var block = proto && proto.blockTokenizers
var inline = proto && proto.inlineTokenizers
var compiler = Compiler && Compiler.prototype && Compiler.prototype.visitors
if (block && block.html) {
block.html = factory(block.html)
}
if (inline && inline.html) {
inline.html = factory(inline.html)
}
if (compiler && compiler.html) {
compiler.html = factory(compiler.html)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = commentMarker(result && result.type ? result : node)
if (marker && marker.name === 'remark') {
try {
self.setOptions(marker.parameters)
} catch (error) {
self.file.fail(error.message, marker.node, origin)
}
}
return result
}
}
| 'use strict'
var commentMarker = require('mdast-comment-marker')
module.exports = commentconfig
// Modify `processor` to read configuration from comments.
function commentconfig() {
var proto = this.Parser && this.Parser.prototype
var Compiler = this.Compiler
var block = proto && proto.blockTokenizers
var inline = proto && proto.inlineTokenizers
var compiler = Compiler && Compiler.prototype && Compiler.prototype.visitors
if (block && block.html) {
block.html = factory(block.html)
}
if (inline && inline.html) {
inline.html = factory(inline.html)
}
if (compiler && compiler.html) {
compiler.html = factory(compiler.html)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = commentMarker(result && result.type ? result : node)
if (marker && marker.name === 'remark') {
try {
self.setOptions(marker.parameters)
} catch (error) {
self.file.fail(error.message, marker.node)
}
}
return result
}
}
|
Add test to check dummy url mime type | <?php
namespace AssetManager\Service;
use PHPUnit_Framework_TestCase;
class MimeResolverTest extends PHPUnit_Framework_TestCase
{
public function testGetMimeType()
{
//Fails
$mimeResolver = new MimeResolver;
$this->assertEquals('text/plain', $mimeResolver->getMimeType('bacon.porn'));
//Success
$this->assertEquals('application/x-httpd-php', $mimeResolver->getMimeType(__FILE__));
}
public function testGetExtension()
{
$mimeResolver = new MimeResolver;
$this->assertEquals('css', $mimeResolver->getExtension('text/css'));
$this->assertEquals('js', $mimeResolver->getExtension('application/javascript'));
}
public function testGetUrlMimeType()
{
$mimeResolver = new MimeResolver;
$this->assertEquals('js', $mimeResolver->getMimeType('http://foo.bar/file.js'));
}
}
| <?php
namespace AssetManager\Service;
use PHPUnit_Framework_TestCase;
class MimeResolverTest extends PHPUnit_Framework_TestCase
{
public function testGetMimeType()
{
//Fails
$mimeResolver = new MimeResolver;
$this->assertEquals('text/plain', $mimeResolver->getMimeType('bacon.porn'));
//Success
$this->assertEquals('application/x-httpd-php', $mimeResolver->getMimeType(__FILE__));
}
public function testGetExtension()
{
$mimeResolver = new MimeResolver;
$this->assertEquals('css', $mimeResolver->getExtension('text/css'));
$this->assertEquals('js', $mimeResolver->getExtension('application/javascript'));
}
}
|
Add a URL conf for the EpilogueView. | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import (AwayView, DiscussionView, EpilogueView, GameView,
PrologueView)
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Overlays.
url(r'^away/$', name='live-away', view=AwayView.as_view()),
url(r'^discussion/$', name='live-discussion', view=DiscussionView.as_view()),
url(r'^epilogue/$', name='live-epilogue', view=EpilogueView.as_view()),
url(r'^game/$', name='live-game', view=GameView.as_view()),
url(r'^prologue/$', name='live-prologue', view=PrologueView.as_view()),
)
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import AwayView, DiscussionView, GameView, PrologueView
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', view=RedirectView.as_view(url='http://twitch.tv/avalonstar')),
# Overlays.
url(r'^away/$', name='live-away', view=AwayView.as_view()),
url(r'^discussion/$', name='live-discussion', view=DiscussionView.as_view()),
url(r'^game/$', name='live-game', view=GameView.as_view()),
url(r'^prologue/$', name='live-prologue', view=PrologueView.as_view()),
)
|
Fix serialization of Dates in user and playlist objects | 'use strict';
/**
* @param {import('../models').Playlist} model
*/
function serializePlaylist(model) {
return {
_id: model.id || model._id.toString(),
name: model.name,
author: model.author.toString(),
createdAt: model.createdAt.toISOString(),
description: model.description,
size: model.media.length,
};
}
/**
* @param {Pick<import('../models').User,
* '_id' | 'username' | 'slug' | 'roles' | 'avatar' |
* 'createdAt' | 'updatedAt' | 'lastSeenAt'>} model
*/
function serializeUser(model) {
return {
_id: model._id.toString(),
username: model.username,
slug: model.slug,
roles: model.roles,
avatar: model.avatar,
createdAt: model.createdAt.toISOString(),
updatedAt: model.updatedAt.toISOString(),
lastSeenAt: model.lastSeenAt.toISOString(),
};
}
exports.serializePlaylist = serializePlaylist;
exports.serializeUser = serializeUser;
| 'use strict';
/**
* @param {import('../models').Playlist} model
*/
function serializePlaylist(model) {
return {
_id: model.id || model._id.toString(),
name: model.name,
author: model.author,
createdAt: model.createdAt,
description: model.description,
size: model.media.length,
};
}
/**
* @param {Pick<import('../models').User,
* '_id' | 'username' | 'slug' | 'roles' | 'avatar' |
* 'createdAt' | 'updatedAt' | 'lastSeenAt'>} model
*/
function serializeUser(model) {
return {
_id: model._id.toString(),
username: model.username,
slug: model.slug,
roles: model.roles,
avatar: model.avatar,
createdAt: model.createdAt.toString(),
updatedAt: model.updatedAt.toString(),
lastSeenAt: model.lastSeenAt.toString(),
};
}
exports.serializePlaylist = serializePlaylist;
exports.serializeUser = serializeUser;
|
Add event listener to back button | $().ready(loadContentSection);
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(".extended").removeClass("extended");
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$("body").on('click', '.level-name', function() {
const isThisExtended = $(this).parent().hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).parent().addClass("extended");
}
});
$("body").on('click', '#go-back', function() {
$("#body").off("click");
window.location.href = '/';
});
| $().ready(loadContentSection);
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(".extended").removeClass("extended");
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$("body").on('click', '.level-name', function() {
const isThisExtended = $(this).parent().hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).parent().addClass("extended");
}
});
|
Fix modal does not close bug | var shipment = $("#shipment-templ").html();
var template = Handlebars.compile(shipment);
//Sample - To be replaced by GET db content
// {
// author: "zachlatta",
// name: "Hack Club",
// timestamp: "11:09 PM - 7 Jul 2017",
// desc: "We help high schoolers start awesome after-school coding clubs!",
// link: "https://hackclub.com",
// code: "https://github.com/hackclub/hackclub",
// upvote: 255
// uuid: 125121
// }
function loadShipment(id) {
$("#shipped-placeholder").hide();
$("#shipped").prepend(template(id));
}
$("#launch").on("click", openShipper);
$(".modal-close").on("click", closeShipper);
function openShipper() {
$("#ship-modal").addClass("is-active");
}
function closeShipper() {
$(".modal").removeClass("is-active");
}
function shareShipment(uuid) {
$("#share-modal").addClass("is-active");
} | var shipment = $("#shipment-templ").html();
var template = Handlebars.compile(shipment);
//Sample - To be replaced by GET db content
// {
// author: "zachlatta",
// name: "Hack Club",
// timestamp: "11:09 PM - 7 Jul 2017",
// desc: "We help high schoolers start awesome after-school coding clubs!",
// link: "https://hackclub.com",
// code: "https://github.com/hackclub/hackclub",
// upvote: 255
// uuid: 125121
// }
function loadShipment(id) {
$("#shipped-placeholder").hide();
$("#shipped").prepend(template(id));
}
$("#launch").on("click", openShipper);
$("#unlaunch").on("click", closeShipper);
function openShipper() {
$("#ship-modal").addClass("is-active");
}
function closeShipper() {
$(".modal").removeClass("is-active");
}
function shareShipment(uuid) {
$("#share-modal").addClass("is-active");
} |
Add YAML serialization to ClientLocketConfig
[#139885407]
Signed-off-by: Edwin Xie <6bc24e9c160281972837d9e13287696d26612564@pivotal.io> | package locket
import (
"code.cloudfoundry.org/cfhttp"
"code.cloudfoundry.org/lager"
"code.cloudfoundry.org/locket/models"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type ClientLocketConfig struct {
LocketAddress string `json:"locket_address,omitempty" yaml:"locket_address,omitempty"`
LocketCACertFile string `json:"locket_ca_cert_file,omitempty" yaml:"locket_ca_cert_file,omitempty"`
LocketClientCertFile string `json:"locket_ca_cert_file,omitempty" yaml:"locket_client_cert_file,omitempty"`
LocketClientKeyFile string `json:"locket_client_key_file,omitempty" yaml:"locket_client_key_file,omitempty"`
}
func NewClient(logger lager.Logger, config ClientLocketConfig) (models.LocketClient, error) {
locketTLSConfig, err := cfhttp.NewTLSConfig(config.LocketClientCertFile, config.LocketClientKeyFile, config.LocketCACertFile)
if err != nil {
return nil, err
}
conn, err := grpc.Dial(config.LocketAddress, grpc.WithTransportCredentials(credentials.NewTLS(locketTLSConfig)))
if err != nil {
return nil, err
}
return models.NewLocketClient(conn), nil
}
| package locket
import (
"code.cloudfoundry.org/cfhttp"
"code.cloudfoundry.org/lager"
"code.cloudfoundry.org/locket/models"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type ClientLocketConfig struct {
LocketAddress string `json:"locket_address,omitempty"`
LocketCACertFile string `json:"locket_ca_cert_file,omitempty"`
LocketClientCertFile string `json:"locket_client_cert_file,omitempty"`
LocketClientKeyFile string `json:"locket_client_key_file,omitempty"`
}
func NewClient(logger lager.Logger, config ClientLocketConfig) (models.LocketClient, error) {
locketTLSConfig, err := cfhttp.NewTLSConfig(config.LocketClientCertFile, config.LocketClientKeyFile, config.LocketCACertFile)
if err != nil {
return nil, err
}
conn, err := grpc.Dial(config.LocketAddress, grpc.WithTransportCredentials(credentials.NewTLS(locketTLSConfig)))
if err != nil {
return nil, err
}
return models.NewLocketClient(conn), nil
}
|
Add ipaddress.IPv[46]Network to the supported types | # Copyright (c) 2005-2016 Stefanos Harhalakis <v13@v13.gr>
# Copyright (c) 2016-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Collection, Mapping, Union
import ipaddress
SupportedTypes = Union[str, int, float, bool, ipaddress.IPv4Interface, ipaddress.IPv6Interface,
ipaddress.IPv4Network, ipaddress.IPv6Network, dict, list, None]
# Convenience types
ResultDict = dict[str, SupportedTypes] # A result in dict form
ResultsDict = list[ResultDict] # A list of results
ValueParam = Mapping[str, SupportedTypes] # A parameter suitable for passing db values
WhereParam = Mapping[str, SupportedTypes] # A parameter suitable for WHERE
ParamDict = dict[str, SupportedTypes] # A concrete dict for values
OrderParam = Collection[str] # A parameter suitable for ORDER BY
class VDBError(Exception):
pass
| # Copyright (c) 2005-2016 Stefanos Harhalakis <v13@v13.gr>
# Copyright (c) 2016-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Collection, Mapping, Union
import ipaddress
SupportedTypes = Union[str, int, float, bool, ipaddress.IPv4Interface, ipaddress.IPv6Interface, dict, list, None]
# Convenience types
ResultDict = dict[str, SupportedTypes] # A result in dict form
ResultsDict = list[ResultDict] # A list of results
ValueParam = Mapping[str, SupportedTypes] # A parameter suitable for passing db values
WhereParam = Mapping[str, SupportedTypes] # A parameter suitable for WHERE
ParamDict = dict[str, SupportedTypes] # A concrete dict for values
OrderParam = Collection[str] # A parameter suitable for ORDER BY
class VDBError(Exception):
pass
|
Remove unicode literals to fix with_metaclass method | # -*- coding: utf-8 -*-
"""
Py27 Support
~~~~~~~~~~~~
Like odin this library will support Python 2.7 through to version 2.0.
From this point onwards Python 3.5+ will be required.
"""
import sys
__all__ = (
'PY2', 'PY3',
'string_types', 'integer_types', 'text_type', 'binary_type',
'range', 'with_metaclass'
)
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
text_type = str
binary_type = bytes
else:
string_types = basestring,
integer_types = (int, long)
text_type = unicode
binary_type = str
if PY2:
range = xrange
else:
range = range
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
| # -*- coding: utf-8 -*-
"""
Py27 Support
~~~~~~~~~~~~
Like odin this library will support Python 2.7 through to version 2.0.
From this point onwards Python 3.5+ will be required.
"""
from __future__ import unicode_literals
import sys
__all__ = (
'PY2', 'PY3',
'string_types', 'integer_types', 'text_type', 'binary_type',
'range', 'with_metaclass'
)
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
text_type = str
binary_type = bytes
else:
string_types = basestring,
integer_types = (int, long)
text_type = unicode
binary_type = str
if PY2:
range = xrange
else:
range = range
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
|
Test for transcript before scraping from PUA | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup archive poll for information'
def handle(self, *args, **options):
client = Client(
settings.PUA_KEY,
settings.PUA_SECRET,
)
for collection in client.get_collections():
logger.info('processing collection id: ' + str(collection['id']))
for item_id in collection['item_ids']:
logger.info('processing item id: ' + str(item_id))
try:
Transcript.objects.get(id_number=item_id)
except Transcript.DoesNotExist:
item = client.get_item(collection['id'], item_id)
process_transcript(item)
| import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup archive poll for information'
def handle(self, *args, **options):
client = Client(
settings.PUA_KEY,
settings.PUA_SECRET,
)
for collection in client.get_collections():
logger.info('collection id: ' + str(collection['id']))
for item_id in collection['item_ids']:
logger.info('item id: ' + str(item_id))
item = client.get_item(collection['id'], item_id)
process_transcript(item)
|
Rewrite FormattedMessage to fix react-docgen | import { createElement, isValidElement, Component } from 'react';
import PropTypes from 'prop-types';
import format from 'format-message';
export default class FormattedMessage extends Component {
render() {
const { message, values, tagName } = this.props;
const uid = Math.floor(Math.random() * 0x10000000000).toString(16);
const hashedParams = {};
const elements = {};
const tokenDelimeter = `@__${uid}__@`;
Object.keys(values).forEach((key) => {
if (isValidElement(values[key])) {
hashedParams[key] = `${tokenDelimeter}${key}${tokenDelimeter}`;
elements[key] = values[key];
} else {
hashedParams[key] = values[key];
}
});
const nodes = format(message, hashedParams)
.split(tokenDelimeter)
.filter(token => !!token)
.map(token => elements[token] || token);
return createElement(tagName, null, ...nodes);
}
}
FormattedMessage.propTypes = {
message: PropTypes.string.isRequired,
values: PropTypes.object,
tagName: PropTypes.string,
};
FormattedMessage.defaultProps = {
values: undefined,
tagName: 'span',
};
| import { createElement, isValidElement } from 'react';
import PropTypes from 'prop-types';
import format from 'format-message';
export default function FormattedMessage({ message, values, tagName }) {
const uid = Math.floor(Math.random() * 0x10000000000).toString(16);
const hashedParams = {};
const elements = {};
const tokenDelimeter = `@__${uid}__@`;
Object.keys(values).forEach((key) => {
if (isValidElement(values[key])) {
hashedParams[key] = `${tokenDelimeter}${key}${tokenDelimeter}`;
elements[key] = values[key];
} else {
hashedParams[key] = values[key];
}
});
const nodes = format(message, hashedParams)
.split(tokenDelimeter)
.filter(token => !!token)
.map(token => elements[token] || token);
return createElement(tagName, null, ...nodes);
}
FormattedMessage.propTypes = {
message: PropTypes.string.isRequired,
values: PropTypes.object,
tagName: PropTypes.string,
};
FormattedMessage.defaultProps = {
values: undefined,
tagName: 'span',
};
|
Add 'removed' to imperative blacklist | <?php
/**
* This file is part of CaptainHook.
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace sebastianfeldmann\CaptainHook\Hook\Message\Rule;
/**
* Class UseImperativeMood
*
* @package CaptainHook
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/sebastianfeldmann/captainhook
* @since Class available since Release 0.9.0
*/
class UseImperativeMood extends Blacklist
{
/**
* Constructor.
*/
public function __construct()
{
$this->hint = 'Subject should be written in imperative mood';
$this->setSubjectBlacklist(
[
'uploaded',
'updated',
'added',
'created',
'removed'
]
);
}
}
| <?php
/**
* This file is part of CaptainHook.
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace sebastianfeldmann\CaptainHook\Hook\Message\Rule;
/**
* Class UseImperativeMood
*
* @package CaptainHook
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/sebastianfeldmann/captainhook
* @since Class available since Release 0.9.0
*/
class UseImperativeMood extends Blacklist
{
/**
* Constructor.
*/
public function __construct()
{
$this->hint = 'Subject should be written in imperative mood';
$this->setSubjectBlacklist(
[
'uploaded',
'updated',
'added',
'created',
]
);
}
}
|
Add Cluster to Params struct. | package main
import (
"github.com/drone/drone-go/drone"
)
type Params struct {
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
Region string `json:"region"`
Family string `json:"family"`
Image string `json:"image_name"`
Tag string `json:"image_tag"`
Service string `json:"service"`
Cluster string `json:"cluster"`
Memory int64 `json:"memory"`
Environment drone.StringSlice `json:"environment_variables"`
PortMappings drone.StringSlice `json:"port_mappings"`
}
| package main
import (
"github.com/drone/drone-go/drone"
)
type Params struct {
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
Region string `json:"region"`
Family string `json:"family"`
Image string `json:"image_name"`
Tag string `json:"image_tag"`
Service string `json:"service"`
Memory int64 `json:"memory"`
Environment drone.StringSlice `json:"environment_variables"`
PortMappings drone.StringSlice `json:"port_mappings"`
}
|
Remove type when creating index | #!/usr/bin/python
import requests
import json
import os
myElasticServerIp = os.environ.get('ES_SERVER_IP', 'localhost')
myIndexName = os.environ.get('ES_INDEX_NAME', 'bestbuy-products')
def main():
deleteIndex()
createIndex()
def createIndex():
with open('mapping.json') as mappingFile:
jsonData = json.load(mappingFile)
type = 'product'
postUrl = 'http://' + myElasticServerIp + ':9200/' + myIndexName + '/'
print(postUrl)
response = requests.post(postUrl, data=json.dumps(jsonData))
print(response)
print(response.content)
def deleteIndex():
type = 'product'
response = requests.delete('http://' + myElasticServerIp + ':9200/' + myIndexName + '/')
print(response)
print(response.content)
main()
| #!/usr/bin/python
import requests
import json
import os
myElasticServerIp = os.environ.get('ES_SERVER_IP', 'localhost')
myIndexName = os.environ.get('ES_INDEX_NAME', 'bestbuy-products')
def main():
deleteIndex()
createIndex()
def createIndex():
with open('mapping.json') as mappingFile:
jsonData = json.load(mappingFile)
type = 'product'
postUrl = 'http://' + myElasticServerIp + ':9200/' + myIndexName + '/'+type+'/'
print(postUrl)
response = requests.post(postUrl, data=json.dumps(jsonData))
print(response)
print(response.content)
def deleteIndex():
type = 'product'
response = requests.delete('http://' + myElasticServerIp + ':9200/' + myIndexName + '/')
print(response)
print(response.content)
main()
|
Reconnect if connection is lost | /* -*- js2-basic-offset: 2; indent-tabs-mode: nil; -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80; */
"use strict";
require("sockjs");
let Sock = window.SockJS,
{addMethod} = require("genfun"),
{clone, init} = require("../../lib/proto"),
_ = require("lodash"),
can = require("../../shims/can");
/**
* Chatlog Model
*/
let Chatlog = clone();
/*
* Init
*/
addMethod(init, [Chatlog], function(log, url) {
initSocket(log, url);
initModelList(log);
});
function initSocket(log) {
log.socket = new Sock("http://localhost:8080/ws");
log.socket.onmessage = _.partial(onMessage, log);
// TODO - this is probably a pretty naive way to go about reconnecting...
log.socket.onclose = _.partial(initSocket, log);
}
function initModelList(log) {
log.lines = new LogLine.List([]);
}
function onMessage(log, message) {
log.lines.push(new LogLine({text: message.data}));
}
function addLine(log, line) {
log.socket.send(line);
}
/*
* Canjs Model
*/
var LogLine = can.Model.extend({},{});
module.exports.Chatlog = Chatlog;
module.exports.addLine = addLine;
| /* -*- js2-basic-offset: 2; indent-tabs-mode: nil; -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80; */
"use strict";
require("sockjs");
let Sock = window.SockJS,
{addMethod} = require("genfun"),
{clone, init} = require("../../lib/proto"),
_ = require("lodash"),
can = require("../../shims/can");
/**
* Chatlog Model
*/
let Chatlog = clone();
/*
* Init
*/
addMethod(init, [Chatlog], function(log, url) {
initSocket(log, url);
initModelList(log);
});
function initSocket(log) {
log.socket = new Sock("http://localhost:8080/ws");
log.socket.onmessage = _.partial(onMessage, log);
}
function initModelList(log) {
log.lines = new LogLine.List([]);
}
function onMessage(log, message) {
log.lines.push(new LogLine({text: message.data}));
}
function addLine(log, line) {
log.socket.send(line);
}
/*
* Canjs Model
*/
var LogLine = can.Model.extend({},{});
module.exports.Chatlog = Chatlog;
module.exports.addLine = addLine;
|
Replace @link with @see PHPDoc tag
As per proposed PSR-5, usage of @see PHPDoc tag is recommended instead
of @link PHPDoc tag. | <?php
namespace Berrybird\Cerberus\Credential;
/**
* Compares two credentials in a length-constant time.
*
* @see https://crackstation.net/hashing-security.htm?=rd#slowequals
*
* @package Berrybird\Cerberus\Credential
* @copyright Copyright (C) 2011-2014 Miodrag Tokić
* @license New BSD
*/
class SlowCredentialMatcher implements CredentialMatcher
{
/**
* {@inheritdoc}
*/
public function equals($credential1, $credential2)
{
$diff = strlen($credential1) ^ strlen($credential2);
for ($i = 0; $i < strlen($credential1) && $i < strlen($credential2); $i++) {
$diff |= ord($credential1[$i]) ^ ord($credential2[$i]);
}
return $diff === 0;
}
}
| <?php
namespace Berrybird\Cerberus\Credential;
/**
* Compares two credentials in a length-constant time.
*
* @link https://crackstation.net/hashing-security.htm?=rd#slowequals
*
* @package Berrybird\Cerberus\Credential
* @copyright Copyright (C) 2011-2014 Miodrag Tokić
* @license New BSD
*/
class SlowCredentialMatcher implements CredentialMatcher
{
/**
* {@inheritdoc}
*/
public function equals($credential1, $credential2)
{
$diff = strlen($credential1) ^ strlen($credential2);
for ($i = 0; $i < strlen($credential1) && $i < strlen($credential2); $i++) {
$diff |= ord($credential1[$i]) ^ ord($credential2[$i]);
}
return $diff === 0;
}
}
|
Update the build branch for stable to 0.7
TBR=ricow
Review URL: https://codereview.chromium.org/26993005
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 3),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/0.7', 2, '-stable', 1),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 3),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/0.6', 2, '-stable', 1),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
|
Use dispose rather than hide to unbind events. | Spree.ready(function(){
$('body').popover({selector: '.hint-tooltip', html: true, trigger: 'hover', placement: 'top'});
$('body').tooltip({selector: '.with-tip'});
/*
* Poll tooltips to hide them if they are no longer being hovered.
*
* This is necessary to fix tooltips hanging around after their attached
* element has been removed from the DOM (and will therefore receive no
* mouseleave event). This may be unnecessary in a future version of
* bootstrap, which intends to solve this using MutationObserver.
*/
var removeDesyncedTooltip = function(tooltip) {
var interval = setInterval(function(){
if(!$(tooltip.element).is(":hover")) {
tooltip.dispose();
clearInterval(interval);
}
}, 200);
$(tooltip.element).on('hidden.bs.tooltip', function(){
clearInterval(interval);
});
};
$('body').on('inserted.bs.tooltip', function(e){
var $target = $(e.target);
var tooltip = $target.data('bs.tooltip');
removeDesyncedTooltip(tooltip);
var $tooltip = $("#" + $target.attr("aria-describedby"));
$tooltip.addClass("action-" + $target.data("action"));
});
});
| Spree.ready(function(){
$('body').popover({selector: '.hint-tooltip', html: true, trigger: 'hover', placement: 'top'});
$('body').tooltip({selector: '.with-tip'});
/*
* Poll tooltips to hide them if they are no longer being hovered.
*
* This is necessary to fix tooltips hanging around after their attached
* element has been removed from the DOM (and will therefore receive no
* mouseleave event). This may be unnecessary in a future version of
* bootstrap, which intends to solve this using MutationObserver.
*/
var removeDesyncedTooltip = function(tooltip) {
var interval = setInterval(function(){
if(!$(tooltip.element).is(":hover")) {
tooltip.hide();
clearInterval(interval);
}
}, 200);
$(tooltip.element).on('hidden.bs.tooltip', function(){
clearInterval(interval);
});
};
$('body').on('inserted.bs.tooltip', function(e){
var $target = $(e.target);
var tooltip = $target.data('bs.tooltip');
removeDesyncedTooltip(tooltip);
var $tooltip = $("#" + $target.attr("aria-describedby"));
$tooltip.addClass("action-" + $target.data("action"));
});
});
|
Add jianfan to python package installation | from setuptools import setup
from distutils.core import Command
import os
import sys
class TestCommand(Command):
description = "Run tests"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import subprocess
errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s'])
raise SystemExit(errno)
setup(
name='mafan',
version='0.2.10',
author='Herman Schaaf',
author_email='herman@ironzebra.com',
packages=[
'mafan',
'mafan.hanzidentifier',
'mafan.third_party',
'mafan.third_party.jianfan'
],
scripts=['bin/convert.py'],
url='https://github.com/hermanschaaf/mafan',
license='LICENSE.txt',
description='A toolbox for working with the Chinese language in Python',
long_description=open('docs/README.md').read(),
cmdclass={
'test': TestCommand,
},
install_requires=[
"jieba == 0.29",
"argparse == 1.1",
"chardet == 2.1.1",
"wsgiref == 0.1.2",
],
)
| from setuptools import setup
from distutils.core import Command
import os
import sys
class TestCommand(Command):
description = "Run tests"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import subprocess
errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s'])
raise SystemExit(errno)
setup(
name='mafan',
version='0.2.7',
author='Herman Schaaf',
author_email='herman@ironzebra.com',
packages=['mafan', 'mafan.hanzidentifier'],
scripts=['bin/convert.py'],
url='https://github.com/hermanschaaf/mafan',
license='LICENSE.txt',
description='A toolbox for working with the Chinese language in Python',
long_description=open('docs/README.md').read(),
cmdclass={
'test': TestCommand,
},
install_requires=[
"jieba == 0.29",
"argparse == 1.1",
"chardet == 2.1.1",
"wsgiref == 0.1.2",
],
)
|
Return distance from sump pump sensor | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out')
echo=GPIO(24, 'in')
# Pulse to trigger sensor
trig.write(False)
time.sleep(0.00001)
trig.write(True)
time.sleep(0.00001)
trig.write(False)
while echo.read()==False:
pulse_start=time.time()
while echo.read()==True:
pulse_end= time.time()
pulse_duration=pulse_end-pulse_start
# Quick explaination of the formula:
# The pulse duration is to the object and back, so the
# distance is one half of the pulse duration. The speed of
# sound in air is 340 meters/second. There are 100 centimeters
# in a meter.
distance=pulse_duration*340/2*100
distance=round(distance, 2)
trig.close()
echo.close()
return distance
| import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out')
echo=GPIO(24, 'in')
# Pulse to trigger sensor
trig.write(False)
time.sleep(0.00001)
trig.write(True)
time.sleep(0.00001)
trig.write(False)
while echo.read()==False:
pulse_start=time.time()
while echo.read()==True:
pulse_end= time.time()
pulse_duration=pulse_end-pulse_start
# Quick explaination of the formula:
# The pulse duration is to the object and back, so the
# distance is one half of the pulse duration. The speed of
# sound in air is 340 meters/second. There are 100 centimeters
# in a meter.
distance=pulse_duration*340/2*100
distance=round(distance, 2)
trig.close()
echo.close()
|
Fix logging of stats collected by MemoryDebugger extension.
Stats are printed on spider_closed event;
engine_stopped signal is called after spider_closed signal,
so stats for MemoryDebugger extension were not printed to user. | """
MemoryDebugger extension
See documentation in docs/topics/extensions.rst
"""
import gc
from scrapy import signals
from scrapy.exceptions import NotConfigured
from scrapy.utils.trackref import live_refs
class MemoryDebugger(object):
def __init__(self, stats):
self.stats = stats
@classmethod
def from_crawler(cls, crawler):
if not crawler.settings.getbool('MEMDEBUG_ENABLED'):
raise NotConfigured
o = cls(crawler.stats)
crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)
return o
def spider_closed(self, spider, reason):
gc.collect()
self.stats.set_value('memdebug/gc_garbage_count', len(gc.garbage), spider=spider)
for cls, wdict in live_refs.iteritems():
if not wdict:
continue
self.stats.set_value('memdebug/live_refs/%s' % cls.__name__, len(wdict), spider=spider)
| """
MemoryDebugger extension
See documentation in docs/topics/extensions.rst
"""
import gc
from scrapy import signals
from scrapy.exceptions import NotConfigured
from scrapy.utils.trackref import live_refs
class MemoryDebugger(object):
def __init__(self, stats):
self.stats = stats
@classmethod
def from_crawler(cls, crawler):
if not crawler.settings.getbool('MEMDEBUG_ENABLED'):
raise NotConfigured
o = cls(crawler.stats)
crawler.signals.connect(o.engine_stopped, signals.engine_stopped)
return o
def engine_stopped(self):
gc.collect()
self.stats.set_value('memdebug/gc_garbage_count', len(gc.garbage))
for cls, wdict in live_refs.iteritems():
if not wdict:
continue
self.stats.set_value('memdebug/live_refs/%s' % cls.__name__, len(wdict))
|
Add extra widgets to db |
exports.up = async function (knex) {
await knex.schema.table('group_widgets', t => {
t.string('context')
})
const now = new Date().toISOString()
await knex.raw(`
INSERT INTO "public"."widgets"("id","name","created_at") VALUES
(15,E'opportunities_to_collaborate','${now}'),
(16,E'farm_map','${now}'),
(17,E'moderators','${now}'),
(18,E'privacy_settings','${now}'),
(19,E'mission','${now}'),
(20,E'topics','${now}'),
(21,E'join','${now}');
`)
return knex.raw(`
UPDATE group_widgets SET context = 'landing' WHERE context IS NULL;
`)
}
exports.down = async function (knex) {
await knex.raw(`
DELETE FROM widgets WHERE name IN ('opportunities_to_collaborate', 'farm_map', 'moderators', 'privacy_settings');
`)
return knex.schema.table('group_widgets', table => {
table.dropColumn('context')
})
}
|
exports.up = async function (knex) {
await knex.schema.table('group_widgets', t => {
t.string('context')
})
const now = new Date().toISOString()
await knex.raw(`
INSERT INTO "public"."widgets"("id","name","created_at") VALUES
(15,E'opportunities_to_collaborate','${now}'),
(16,E'farm_map','${now}'),
(17,E'moderators','${now}'),
(18,E'privacy_settings','${now}')
`)
return knex.raw(`
UPDATE group_widgets SET context = 'landing' WHERE context IS NULL;
`)
}
exports.down = async function (knex) {
await knex.raw(`
DELETE FROM widgets WHERE name IN ('opportunities_to_collaborate', 'farm_map', 'moderators', 'privacy_settings');
`)
return knex.schema.table('group_widgets', table => {
table.dropColumn('context')
})
}
|
Remove the apikey="" stuff from the unit tests. | // Helper functions used to test endpoints that are protected by authentication.
exports.APIKEY_ADMIN = process.env.ADMIN_APIKEY || '12345';
exports.AUTH_ADMIN = 'deconst ' + exports.APIKEY_ADMIN;
exports.APIKEY_USER = '54321';
exports.AUTH_USER = 'deconst ' + exports.APIKEY_USER;
/**
* @description Test helper to ensure that a route fails if no API key is given.
*/
exports.ensureAuthIsRequired = function (action, done) {
action
.expect(401)
.expect('Content-Type', 'application/json')
.expect({
code: 'UnauthorizedError',
message: 'An API key is required for this endpoint.'
}, done);
};
/**
* @description Test helper to ensure that a route fails if a non-admin API key is given.
*/
exports.ensureAdminIsRequired = function (action, done) {
action
.set('Authorization', exports.AUTH_USER)
.expect(401)
.expect('Content-Type', 'application/json')
.expect({
code: 'UnauthorizedError',
message: 'Only admins may access this endpoint.'
}, done);
};
| // Helper functions used to test endpoints that are protected by authentication.
exports.APIKEY_ADMIN = process.env.ADMIN_APIKEY || '12345';
exports.AUTH_ADMIN = 'deconst apikey="' + exports.APIKEY_ADMIN + '"';
exports.APIKEY_USER = '54321';
exports.AUTH_USER = 'deconst apikey="' + exports.APIKEY_USER + '"';
/**
* @description Test helper to ensure that a route fails if no API key is given.
*/
exports.ensureAuthIsRequired = function (action, done) {
action
.expect(401)
.expect('Content-Type', 'application/json')
.expect({
code: 'UnauthorizedError',
message: 'An API key is required for this endpoint.'
}, done);
};
/**
* @description Test helper to ensure that a route fails if a non-admin API key is given.
*/
exports.ensureAdminIsRequired = function (action, done) {
action
.set('Authorization', exports.AUTH_USER)
.expect(401)
.expect('Content-Type', 'application/json')
.expect({
code: 'UnauthorizedError',
message: 'Only admins may access this endpoint.'
}, done);
};
|
Return to list generator to enable pandas cmd output | __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
point.elevation, point.speed]
seg_frame = pd.DataFrame(data=seg_dict)
# Switch columns and rows s.t. timestamps are rows and gps data columns.
seg_frame = seg_frame.T
seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
return seg_frame
def track_segment_mapping(track):
segments = [data_frame_for_track_segment(segment)
for segment in track.segments]
return segments
def pandas_data_frame_for_gpx(gpx):
tracks_frames = [track_segment_mapping(track) for track in gpx.tracks]
# Create a hierarchical DataFrame by unstacking.
tracks_frame = pd.DataFrame(tracks_frames)
unstacked_frame = tracks_frame.unstack()
unstacked_frame.index.name = 'tracks'
assert gpx.name
d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T
d_frame.index.name = 'name'
return d_frame
| __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
point.elevation, point.speed]
seg_frame = pd.DataFrame(data=seg_dict)
# Switch columns and rows s.t. timestamps are rows and gps data columns.
seg_frame = seg_frame.T
seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
return seg_frame
def track_segment_mapping(track):
segments = (data_frame_for_track_segment(segment)
for segment in track.segments)
return segments
def pandas_data_frame_for_gpx(gpx):
tracks_frames = (track_segment_mapping(track) for track in gpx.tracks)
# Create a hierarchical DataFrame by unstacking.
tracks_frame = pd.DataFrame(tracks_frames)
unstacked_frame = tracks_frame.unstack()
unstacked_frame.index.name = 'tracks'
assert gpx.name
d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T
d_frame.index.name = 'name'
return d_frame
|
Add directory validation to argument parsing | # -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
Add external IP for Flask | # coding: utf-8
from pianette.utils import Debug
from flask import Flask, render_template, request
from threading import Thread
app = Flask(__name__, template_folder='../templates')
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/', methods = ['GET'])
def home():
return render_template('index.html', url_root=request.url_root)
@app.route('/console/play', methods = ['POST'])
def console_play():
command = "console.play %s" % (request.form.get('command'))
app.pianette.inputcmds(command, source="api")
return ('1', 200)
class PianetteApi:
def __init__(self, configobj=None, pianette=None, **kwargs):
super().__init__(**kwargs)
self.configobj = configobj
app.pianette = pianette
Debug.println("INFO", "Starting API thread")
t = Thread(target=self.startApi)
t.daemon = True
t.start()
def startApi(self):
app.run(debug=False, threaded=True, host=0.0.0.0)
| # coding: utf-8
from pianette.utils import Debug
from flask import Flask, render_template, request
from threading import Thread
app = Flask(__name__, template_folder='../templates')
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/', methods = ['GET'])
def home():
return render_template('index.html', url_root=request.url_root)
@app.route('/console/play', methods = ['POST'])
def console_play():
command = "console.play %s" % (request.form.get('command'))
app.pianette.inputcmds(command, source="api")
return ('1', 200)
class PianetteApi:
def __init__(self, configobj=None, pianette=None, **kwargs):
super().__init__(**kwargs)
self.configobj = configobj
app.pianette = pianette
Debug.println("INFO", "Starting API thread")
t = Thread(target=self.startApi)
t.daemon = True
t.start()
def startApi(self):
app.run(debug=False, threaded=True)
|
Change the case to match the actual ID value | {{--
$breadcrumbs => array // ['display_name', 'relative_url']
--}}
<nav class="mt-6 mb-2" aria-label="Breadcrumbs">
<ul class="text-sm">
@foreach($breadcrumbs as $key=>$crumb)
@if($key == 0)
<li class="inline">
<a href="/" aria-labelledby="home"><span class="text-black align-middle">@svg('home', 'w-4 h-4 inline align-baseline')</span></a>
<span class="icon-right-open px-2"></span>
@elseif($key == (count($breadcrumbs) - 1))
<li class="font-bold text-green inline">
{{ $crumb['display_name'] }}
@else
<li class="inline">
<a href="{{ $crumb['relative_url'] }}" class="text-green hover:underline">{{ $crumb['display_name'] }}</a>
<span class="icon-right-open px-2"></span>
@endif
</li>
@endforeach
</ul>
</nav>
| {{--
$breadcrumbs => array // ['display_name', 'relative_url']
--}}
<nav class="mt-6 mb-2" aria-label="Breadcrumbs">
<ul class="text-sm">
@foreach($breadcrumbs as $key=>$crumb)
@if($key == 0)
<li class="inline">
<a href="/" aria-labelledby="Home"><span class="text-black align-middle">@svg('home', 'w-4 h-4 inline align-baseline')</span></a>
<span class="icon-right-open px-2"></span>
@elseif($key == (count($breadcrumbs) - 1))
<li class="font-bold text-green inline">
{{ $crumb['display_name'] }}
@else
<li class="inline">
<a href="{{ $crumb['relative_url'] }}" class="text-green hover:underline">{{ $crumb['display_name'] }}</a>
<span class="icon-right-open px-2"></span>
@endif
</li>
@endforeach
</ul>
</nav>
|
Implement Announce Banner for /benefit | import React from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import AnnounceBanner from 'shared/components/announceBanner/announceBanner';
import WhatWeDo from './whatWeDo/whatWeDo';
import Membership from './membership/membership';
import MoreInformation from './moreInformation/moreInformation';
import SuccessStories from './successStories/successStories';
import Partners from './partners/partners';
import Donate from '../../../shared/components/donate/donate';
import Join from '../../../shared/components/join/join';
import BenefitBanner from '../../../images/benefit.jpg';
import MobileBenefitBanner from '../../../images/benefit-mobile.jpg';
import styles from './landing.css';
const Landing = () => (
<div className={styles.landing}>
<div className={styles.pageHeading}>
<h1>
The largest community dedicated to helping military veterans and families launch software
development careers.
</h1>
<LinkButton text="Join" theme="red" link="/signup" />
</div>
<AnnounceBanner
link="/benefit"
imageSource={BenefitBanner}
fallbackImage450pxWideSource={MobileBenefitBanner}
altText="Click here to find more information about our Benefit Dinner and Silent Auction on November 11th"
/>
<WhatWeDo />
<Membership />
<MoreInformation />
<SuccessStories />
<Partners />
<Donate />
<Join />
</div>
);
export default Landing;
| import React from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import Donate from 'shared/components/donate/donate';
import Join from 'shared/components/join/join';
import WhatWeDo from './whatWeDo/whatWeDo';
import Membership from './membership/membership';
import MoreInformation from './moreInformation/moreInformation';
import Partners from './partners/partners';
import SuccessStories from './successStories/successStories';
import styles from './landing.css';
const Landing = () => (
<div className={styles.landing}>
<div className={styles.pageHeading}>
<h1>The largest community dedicated to helping military veterans and
families launch software development careers.
</h1>
<LinkButton text="Join" theme="red" link="/signup" />
</div>
<WhatWeDo />
<Membership />
<MoreInformation />
<SuccessStories />
<Partners />
<Donate />
<Join />
</div>
);
export default Landing;
|
Fix Resource cannot be initialized without $metadata argument | <?php
namespace SensioLabs\Melody\Resource;
/**
* Metadata.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class Metadata
{
private $id;
private $owner;
private $createdAd;
private $updatedAt;
private $revision;
private $uri;
public function __construct($id = null, $owner = null, \DateTime $createdAd = null, \DateTime $updatedAt = null, $revision = null, $uri = null)
{
$this->id = $id;
$this->owner = $owner;
$this->createdAd = $createdAd;
$this->updatedAt = $updatedAt;
$this->revision = $revision;
$this->uri = $uri;
}
public function getId()
{
return $this->id;
}
public function getOwner()
{
return $this->owner;
}
public function getCreatedAt()
{
return $this->createdAd;
}
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function getRevision()
{
return $this->revision;
}
public function getUri()
{
return $this->uri;
}
}
| <?php
namespace SensioLabs\Melody\Resource;
/**
* Metadata.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class Metadata
{
private $id;
private $owner;
private $createdAd;
private $updatedAt;
private $revision;
private $uri;
public function __construct($id, $owner, \DateTime $createdAd, \DateTime $updatedAt, $revision, $uri)
{
$this->id = $id;
$this->owner = $owner;
$this->createdAd = $createdAd;
$this->updatedAt = $updatedAt;
$this->revision = $revision;
$this->uri = $uri;
}
public function getId()
{
return $this->id;
}
public function getOwner()
{
return $this->owner;
}
public function getCreatedAt()
{
return $this->createdAd;
}
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function getRevision()
{
return $this->revision;
}
public function getUri()
{
return $this->uri;
}
}
|
Switch to a truly unique key | import React from 'react';
import PropTypes from 'prop-types';
import Example from './Example';
import Props from './Props';
const ComponentPage = ({component}) => {
const {name, description, props, examples} = component;
return (
<div className="componentpage">
<h2>{name}</h2>
<p>{description}</p>
<h3>Example{examples.length > 1 && "s"}</h3>
{
examples.length > 0 ?
examples.map( example => <Example key={example.code} example={example} componentName={name} /> ) :
"No examples exist."
}
<h3>Props</h3>
{
props ?
<Props props={props} /> :
"This component accepts no props."
}
</div>
)
};
ComponentPage.propTypes = {
component: PropTypes.object.isRequired
};
export default ComponentPage;
| import React from 'react';
import PropTypes from 'prop-types';
import Example from './Example';
import Props from './Props';
const ComponentPage = ({component}) => {
const {name, description, props, examples} = component;
return (
<div className="componentpage">
<h2>{name}</h2>
<p>{description}</p>
<h3>Example{examples.length > 1 && "s"}</h3>
{
examples.length > 0 ?
examples.map( example => <Example key={example.name} example={example} componentName={name} /> ) :
"No examples exist."
}
<h3>Props</h3>
{
props ?
<Props props={props} /> :
"This component accepts no props."
}
</div>
)
};
ComponentPage.propTypes = {
component: PropTypes.object.isRequired
};
export default ComponentPage;
|
Test commit for bootcamp ssh | <?php
/**
* mailer-config.php
* This file contains your reCAPTCHA keys, and your recipients email addresses.
*
* @param string $siteKey your public reCAPTCHA API key
* @param string $secret your secret reCAPTCHA API key
* @param array $MAIL_RECIPIENTS array of email addresses and corresponding recipient names to send form responses to
*
* This file has been gitignored!
**/
// your Google reCAPTCHA keys here
$siteKey = '6Lce7iETAAAAAMMOWyA_2wlnlnRZ5tIXtobpYm74';
$secret = '6Lce7iETAAAAABVAWZ8MxXA2vSLD6DCxmzNmIZGF';
/**
* attach the recipients to the message
* notice this an array that can include or omit the the recipient's real name
* use the recipients' real name where possible; this reduces the probability of the Email being marked as spam
**/
$MAIL_RECIPIENTS = ["jordanv215@gmail.com" => "Jordan Vinson"];
// comment for test push
| <?php
/**
* mailer-config.php
* This file contains your reCAPTCHA keys, and your recipients email addresses.
*
* @param string $siteKey your public reCAPTCHA API key
* @param string $secret your secret reCAPTCHA API key
* @param array $MAIL_RECIPIENTS array of email addresses and corresponding recipient names to send form responses to
*
* This file has been gitignored!
**/
// your Google reCAPTCHA keys here
$siteKey = '6Lce7iETAAAAAMMOWyA_2wlnlnRZ5tIXtobpYm74';
$secret = '6Lce7iETAAAAABVAWZ8MxXA2vSLD6DCxmzNmIZGF';
/**
* attach the recipients to the message
* notice this an array that can include or omit the the recipient's real name
* use the recipients' real name where possible; this reduces the probability of the Email being marked as spam
**/
$MAIL_RECIPIENTS = ["jordanv215@gmail.com" => "Jordan Vinson"]; |
Bz1160269: Fix the location of the beans.xml file in the bean output message | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.jboss.as.quickstarts.cdi.alternative;
import javax.enterprise.inject.Alternative;
/**
* Alternative implementation for Tax
*
* @author Nevin Zhu
*
*/
@Alternative
public class TaxImpl_2 implements Tax {
@Override
public String getRate() {
// TODO Auto-generated method stub
return "Tax_2 Rate! To switch back to the default, comment out the 'alternatives' tag in the WEB-INF/beans.xml file";
}
}
| /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.jboss.as.quickstarts.cdi.alternative;
import javax.enterprise.inject.Alternative;
/**
* Alternative implementation for Tax
*
* @author Nevin Zhu
*
*/
@Alternative
public class TaxImpl_2 implements Tax {
@Override
public String getRate() {
// TODO Auto-generated method stub
return "Tax_2 Rate! To switch back to the default, go to /META-INF/beans.xml and comment out the 'alternatives' tag";
}
}
|
Fix syntax in featureCounts test | import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data("featurecounts") + "/rnaseq_undef"
RNASEQ_DIR_noconsensus = sequana_data("featurecounts") + "/rnaseq_noconsensus"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_0, tolerance=0.1) == "0"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_1, tolerance=0.1) == "1"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_2, tolerance=0.1) == "2"
assert (
fc.get_most_probable_strand_consensus(RNASEQ_DIR_undef, tolerance=0.1) == "NA"
)
try:
fc.get_most_probable_strand_consensus(RNASEQ_DIR_noconsensus, tolerance=0.1)
assert False
except IOError:
assert True
| import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data("featurecounts") + "/rnaseq_undef"
RNASEQ_DIR_noconsensus = sequana_data("featurecounts") + "/rnaseq_noconsensus"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_0, tolerance=0.1) == "0"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_1, tolerance=0.1) == "1"
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_2, tolerance=0.1) == "2"
try:
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_undef, tolerance=0.1) == "NA"
try:
fc.get_most_probable_strand_consensus(RNASEQ_DIR_noconsensus,
tolerance=0.1)
assert False
except IOError:
assert True
|
Increase fraction of non-dropout frames required. | #!/usr/bin/env python
import climate
import collections
import joblib
import database
def count(trial):
trial.load()
trial.reindex(100)
trial.mask_dropouts()
markers = []
for m in trial.marker_columns:
s = trial.df[m + '-c']
if s.count() > 0.1 * len(s):
markers.append(m)
return markers
def main(root):
trials = database.Experiment(root).trials_matching('*')
counts = collections.defaultdict(int)
f = joblib.delayed(count)
for markers in joblib.Parallel(-1)(f(t) for t in trials):
for m in markers:
counts[m] += 1
for m, c in sorted(counts.items(), key=lambda x: -x[1]):
print(c, m)
if __name__ == '__main__':
climate.call(main)
| #!/usr/bin/env python
import climate
import collections
import joblib
import database
def count(trial):
trial.load()
trial.reindex(100)
trial.mask_dropouts()
markers = []
for m in trial.marker_columns:
s = trial[m + '-c']
if s.count() > 0.01 * len(s):
markers.append(m)
return markers
def main(root):
trials = database.Experiment(root).trials_matching('*')
counts = collections.defaultdict(int)
f = joblib.delayed(count)
for markers in joblib.Parallel(-1)(f(t) for t in trials):
for m in markers:
counts[m] += 1
for m, c in sorted(counts.items(), key=lambda x: -x[1]):
print(c, m)
if __name__ == '__main__':
climate.call(main)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.