text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix on/off if there is no 'off' field.
|
# -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
|
# -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
|
Change the way to report bugs
|
//
// script.js
//
'use strict';
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
contexts: ['page', 'frame', 'selection', 'link', 'editable', 'image', 'video', 'audio'],
id: 'background_img',
title: chrome.i18n.getMessage('title')
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
chrome.tabs.sendMessage(tab.id, '', response => {
if (response) {
response.split(' ').map(image => {
chrome.tabs.create({
index: tab.index + 1,
url: image
});
});
} else if(confirm(chrome.i18n.getMessage('failure'))) {
chrome.tabs.create({
index: tab.index + 1,
url: 'https://chrome.google.com/webstore/detail/cegndknljaapfbnmfnagomhhgbajjibd/support'
});
}
});
});
|
//
// script.js
//
'use strict';
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
contexts: ['page', 'frame', 'selection', 'link', 'editable', 'image', 'video', 'audio'],
id: 'background_img',
title: chrome.i18n.getMessage('title')
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
chrome.tabs.sendMessage(tab.id, '', response => {
if (response) {
response.split(' ').map(image => {
chrome.tabs.create({
index: tab.index + 1,
url: image
});
});
} else if(confirm(chrome.i18n.getMessage('failure'))) {
const url = encodeURIComponent(info.frameUrl || info.pageUrl);
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://script.google.com/macros/s/AKfycbwtacVYsZHc_n4qkVdfvjJE_3__rKwfeqTNNgZKPhH00VoKTAA/exec?url=' + url);
xhr.send();
}
});
});
|
Fix title rendering in redux example
|
/* @flow */
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App, NotFound } from './components/App.js';
import Home, { Who, How } from './components/Pages.js';
import { LogIn, SignUp } from './components/SignUp.js';
/**
* The route configuration for the whole app.
*/
export const routes = (
<Route path='/' component={App}>
<IndexRoute title='Redux Example | Home' component={Home} />
{/* Pages */}
<Route path='who' title='Redux Example | Who' component={Who} />
<Route path='how' title='Redux Example | How' component={How} />
{/* Account */}
<Route path='log-in' title='Redux Example | Log In' component={LogIn} />
<Route path='sign-up' title='Redux Example | Sign Up' component={SignUp} />
{/* Not Found */}
<Route path='*' title='Redux Example | Not Found' component={NotFound} />
</Route>
);
export default routes;
|
/* @flow */
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App, NotFound } from './components/App.js';
import Home, { Who, How } from './components/Pages.js';
import { LogIn, SignUp } from './components/SignUp.js';
/**
* The route configuration for the whole app.
*/
export const routes = (
<Route path='/' title='Redux Example | Home' component={App}>
<IndexRoute component={Home} />
{/* Pages */}
<Route path='who' title='Redux Example | Who' component={Who} />
<Route path='how' title='Redux Example | How' component={How} />
{/* Account */}
<Route path='log-in' title='Redux Example | Log In' component={LogIn} />
<Route path='sign-up' title='Redux Example | Sign Up' component={SignUp} />
{/* Not Found */}
<Route path='*' title='Redux Example | Not Found' component={NotFound} />
</Route>
);
export default routes;
|
Make typeahead sort-- promoting identical matches, or just naturally.
|
$( document ).ready(function() {
var typer = $('.typeahead');
var genders = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json',
sorter: function(a, b) {
var i = typer.val().toLowerCase();
// If there's a complete match it wins.
if(i == a) { return -1; }
else if (i == b) { return 1; }
// Otherwise just sort it naturally.
else if (a < b) { return -1; }
else if (a > b) { return 1; }
else return 0;
}
});
typer.typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'genders',
source: genders
});
typer.bind('typeahead:select', function(ev, suggestion) {
var choices = $('#user-genders');
choices.html( choices.html() + "<li>" + suggestion + " </li>" ); //FIXME: i'm 100% certain there's a better way for this
});
});
|
$( document ).ready(function() {
var typer = $('.typeahead');
var genders = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'https://raw.githubusercontent.com/anne-decusatis/genderamender/master/genders.json'
});
typer.typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'genders',
source: genders
});
typer.bind('typeahead:select', function(ev, suggestion) {
var choices = $('#user-genders');
choices.html( choices.html() + "<li>" + suggestion + " </li>" ); //FIXME: i'm 100% certain there's a better way for this
});
});
|
Add service worker registration back
|
import * as HAWS from 'home-assistant-js-websocket';
window.HAWS = HAWS;
window.HASS_DEMO = __DEMO__;
const init = window.createHassConnection = function (password) {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const url = `${proto}://${window.location.host}/api/websocket`;
const options = {};
if (password !== undefined) {
options.authToken = password;
}
return HAWS.createConnection(url, options)
.then(function (conn) {
HAWS.subscribeEntities(conn);
HAWS.subscribeConfig(conn);
return conn;
});
};
if (window.noAuth) {
window.hassConnection = init();
} else if (window.localStorage.authToken) {
window.hassConnection = init(window.localStorage.authToken);
} else {
window.hassConnection = null;
}
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/service_worker.js');
});
}
|
import * as HAWS from 'home-assistant-js-websocket';
window.HAWS = HAWS;
window.HASS_DEMO = __DEMO__;
const init = window.createHassConnection = function (password) {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const url = `${proto}://${window.location.host}/api/websocket`;
const options = {};
if (password !== undefined) {
options.authToken = password;
}
return HAWS.createConnection(url, options)
.then(function (conn) {
HAWS.subscribeEntities(conn);
HAWS.subscribeConfig(conn);
return conn;
});
};
if (window.noAuth) {
window.hassConnection = init();
} else if (window.localStorage.authToken) {
window.hassConnection = init(window.localStorage.authToken);
} else {
window.hassConnection = null;
}
|
Optimize conditioning and improve truncation.
"tuj" and "ĝis" should not be replaced.
|
// Get selection and limit to only the first word, because vortaro.net
// doesn't support sentences.
function firstWord(text) {
return text.split(/\s+/, 1)[0].toLowerCase();
}
// Remove -n and -j and present verbs as infinitives
// (replacing -as/is/os with -i).
function normalize(text) {
if (text.endsWith("as") || text.endsWith("os")
|| (text.endsWith("is") && text !== "ĝis")) {
text = text.substring(0, text.length-2) + "i";
} else {
if (text.endsWith("n") && text !== "kun") {
text = text.substring(0, text.length-1);
}
if (text.endsWith("j") && text !== "kaj" && text !== "tuj") {
text = text.substring(0, text.length-1);
}
}
return text;
}
function getSelectionText() {
var text = window.getSelection().toString();
text = firstWord(text);
return normalize(text);
}
self.on("context", function () {
var text = getSelectionText();
return "Difinu \"" + text + "\"";
});
self.on("click", function () {
var text = getSelectionText();
self.postMessage(text);
});
|
// Get selection and limit to only the first word, because vortaro.net
// doesn't support sentences.
function firstWord(text) {
return text.split(/\s+/, 1)[0].toLowerCase();
}
// Remove -n and -j and present verbs as infinitives
// (replacing -as/is/os with -i).
function normalize(text) {
if (text.endsWith("n") && text !== "kun") {
text = text.substring(0, text.length-1);
}
if (text.endsWith("j")) {
text = text.substring(0, text.length-1);
}
if (text.endsWith("as") || text.endsWith("is") || text.endsWith("os")) {
text = text.substring(0, text.length-2) + "i";
};
return text;
}
function getSelectionText() {
var text = window.getSelection().toString();
text = firstWord(text);
return normalize(text);
}
self.on("context", function () {
var text = getSelectionText();
return "Difinu \"" + text + "\"";
});
self.on("click", function () {
var text = getSelectionText();
self.postMessage(text);
});
|
Add factory for Earning model
|
<?php
use Faker\Generator;
use App\User;
use App\Earning;
use App\Spending;
$factory->define(User::class, function (Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10)
];
});
$factory->define(Earning::class, function (Generator $faker) {
return [
'happened_on' => $faker->dateTimeBetween('-50 days', 'now')->format('Y-m-d'),
'description' => implode(' ', array_map('ucfirst', $faker->words(3))),
'amount' => $faker->randomNumber(3)
];
});
$factory->define(Spending::class, function (Generator $faker) {
return [
'happened_on' => $faker->dateTimeBetween('-50 days', 'now')->format('Y-m-d'),
'description' => implode(' ', array_map('ucfirst', $faker->words(3))),
'amount' => $faker->randomNumber(3)
];
});
|
<?php
use Faker\Generator;
use App\User;
use App\Spending;
$factory->define(User::class, function (Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10)
];
});
$factory->define(Spending::class, function (Generator $faker) {
return [
'happened_on' => $faker->dateTimeBetween('-50 days', 'now')->format('Y-m-d'),
'description' => implode(' ', array_map('ucfirst', $faker->words(3))),
'amount' => $faker->randomNumber(3)
];
});
|
Add default path to config
|
import argparse
from collections import OrderedDict
import json
import logger
import logging
from session import Session
from simulator import Simulator
from cache import Cache
from client_factory import ClientFactory
from keeper import Keeper
parser = argparse.ArgumentParser()
parser.add_argument('--pipe', dest='pipelines', default='/etc/spamostack/conf.json',
help='Path to the config file with pipes')
parser.add_argument('--db', dest='db', default='./db',
help='Path to the database directory')
args = parser.parse_args()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logger.SpamStreamHandler())
def main():
if args.pipelines:
with open(args.pipelines, 'r') as pipes_file:
pipelines = json.load(pipes_file, object_pairs_hook=OrderedDict)
simulators = []
cache = Cache(args.db)
admin_session = Session(cache)
admin_factory = ClientFactory(cache)
admin_keeper = Keeper(cache, admin_session, admin_factory)
for pipe_name, pipe in pipelines.iteritems():
simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))
for simulator in simulators:
simulator.simulate()
if __name__ == "__main__":
main()
|
import argparse
from collections import OrderedDict
import json
import logger
import logging
from session import Session
from simulator import Simulator
from cache import Cache
from client_factory import ClientFactory
from keeper import Keeper
parser = argparse.ArgumentParser()
parser.add_argument('--pipe', dest='pipelines', required=True,
help='Path to the config file with pipes')
parser.add_argument('--db', dest='db', default='./db',
help='Path to the database directory')
args = parser.parse_args()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logger.SpamStreamHandler())
def main():
if args.pipelines:
with open(args.pipelines, 'r') as pipes_file:
pipelines = json.load(pipes_file, object_pairs_hook=OrderedDict)
simulators = []
cache = Cache(args.db)
admin_session = Session(cache)
admin_factory = ClientFactory(cache)
admin_keeper = Keeper(cache, admin_session, admin_factory)
for pipe_name, pipe in pipelines.iteritems():
simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))
for simulator in simulators:
simulator.simulate()
if __name__ == "__main__":
main()
|
Add save xml name argument to TRIPS API
|
import sys
import trips_client
from processor import TripsProcessor
def process_text(text, save_xml_name='trips_output.xml'):
html = trips_client.send_query(text)
xml = trips_client.get_xml(html)
if save_xml_name:
trips_client.save_xml(xml, save_xml_name)
return process_xml(xml)
def process_xml(xml_string):
tp = TripsProcessor(xml_string)
tp.get_complexes()
tp.get_phosphorylation()
tp.get_activating_mods()
tp.get_activations()
return tp
if __name__ == '__main__':
input_fname = 'phosphorylate.xml'
if len(sys.argv) > 1:
input_fname = sys.argv[1]
try:
fh = open(input_fname, 'rt')
except IOError:
print 'Could not open file %s' % input_fname
sys.exit()
xml_string = fh.read()
tp = TripsProcessor(xml_string)
tp.get_complexes()
tp.get_phosphorylation()
|
import sys
import trips_client
from processor import TripsProcessor
def process_text(text):
html = trips_client.send_query(text)
xml = trips_client.get_xml(html)
trips_client.save_xml(xml, 'test.xml')
return process_xml(xml)
def process_xml(xml_string):
tp = TripsProcessor(xml_string)
tp.get_complexes()
tp.get_phosphorylation()
tp.get_activating_mods()
tp.get_activations()
return tp
if __name__ == '__main__':
input_fname = 'phosphorylate.xml'
if len(sys.argv) > 1:
input_fname = sys.argv[1]
try:
fh = open(input_fname, 'rt')
except IOError:
print 'Could not open file %s' % input_fname
sys.exit()
xml_string = fh.read()
tp = TripsProcessor(xml_string)
tp.get_complexes()
tp.get_phosphorylation()
|
Fix Spawner
Well, not really.
|
package com.hiagg.item;
import com.hiagg.creativetabs.ModTabs;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldSettings.GameType;
public class CurleSpawner extends Item {
public CurleSpawner() {
setUnlocalizedName("CurleSpawner");
setTextureName("hiaggium:CurleSpawner");
setCreativeTab(ModTabs.tabGear);
}
@Override
public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) {
if(world.isRemote) {
// player.setGameType(GameType.CREATIVE);
// Minecraft.getMinecraft().displayGuiScreen(new GuiInventory(player));
// player.setGameType(GameType.SURVIVAL);
}
return item;
}
}
|
package com.hiagg.item;
import com.hiagg.creativetabs.ModTabs;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldSettings.GameType;
public class CurleSpawner extends Item {
public CurleSpawner() {
setUnlocalizedName("CurleSpawner");
setTextureName("hiaggium:CurleSpawner");
setCreativeTab(ModTabs.tabGear);
}
@Override
public boolean onItemUse(ItemStack item, EntityPlayer player, World world, int x, int y, int z, int dim, float p, float ya, float r) {
player.setGameType(GameType.CREATIVE);
player.inventory.openInventory();
player.setGameType(GameType.SURVIVAL);
return true;
}
}
|
Remove foreign keys from paytrail_result table creation migration
The foreign keys are added through another migration that is run after this one
|
<?php
class m131125_152138_create_paytrail_result_table extends CDbMigration
{
public function up()
{
$this->execute(
"CREATE TABLE `paytrail_result` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`paymentId` INT UNSIGNED NOT NULL,
`orderNumber` VARCHAR(64) NOT NULL,
`token` VARCHAR(64) NOT NULL,
`url` TEXT NOT NULL,
`status` TINYINT(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
);
}
public function down()
{
$this->dropTable('paytrail_result');
}
}
|
<?php
class m131125_152138_create_paytrail_result_table extends CDbMigration
{
public function up()
{
$this->execute(
"CREATE TABLE `paytrail_result` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`paymentId` INT UNSIGNED NOT NULL,
`orderNumber` VARCHAR(64) NOT NULL,
`token` VARCHAR(64) NOT NULL,
`url` TEXT NOT NULL,
`status` TINYINT(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
);
$this->addForeignKey('paytrail_result_paymentId', 'paytrail_result', 'paymentId', 'paytrail_payment', 'id');
}
public function down()
{
$this->dropForeignKey('paytrail_result_paymentId', 'paytrail_result');
$this->dropTable('paytrail_result');
}
}
|
Use a better exec from shelljs
|
#!/usr/bin/env node
"use strict";
var chokidar = require('chokidar')
var child = require('child_process')
var command = process.argv[2]
var target = process.argv[3]
if (!command || !target) {
usage()
process.exit(1)
}
var watcher = chokidar.watch(target, {persistent: true})
var run = runner(command)
watcher
.on('error', logError)
.on('change', run)
console.log('Watching', target, 'and running command "' + command + '" on changes')
function runner(command) {
var running = false
return function() {
if (running) return
running = true
execAsync(command, function(err, output) {
if (err) logError(err, output)
running = false
})
}
}
function logError() {
console.error('chokidar-cmd error:', arguments)
}
function usage() {
console.log('Usage: chokidar-watch \'command\' file-or-dir')
}
function execAsync(cmd, callback) {
var output = ''
var c = child.exec(cmd, {env: process.env, maxBuffer: 20*1024*1024}, function(err) {
callback(err ? err : null, output)
})
c.stdout.on('data', function(data) {
output += data
});
c.stderr.on('data', function(data) {
output += data
process.stdout.write(data)
});
return c
}
|
#!/usr/bin/env node
"use strict";
var chokidar = require('chokidar')
var exec = require('child_process').exec
var command = process.argv[2]
var target = process.argv[3]
if (!command || !target) {
usage()
process.exit(1)
}
var watcher = chokidar.watch(target, {persistent: true})
var run = runner(command)
watcher
.on('error', logError)
.on('change', run)
console.log('Watching', target, 'and running command "' + command + '" on changes')
function runner(command) {
var running = false
return function() {
if (running) return
running = true
var p = exec(command, function(err, stdout, stderr) {
if (err !== null) logError(err)
running = false
})
p.stdout.on('data', process.stdout.write)
p.stderr.on('data', process.stderr.write)
}
}
function logError(err) {
console.error('chokidar-cmd error:', err.message)
}
function usage() {
console.log('Usage: chokidar-watch \'command\' file-or-dir')
}
|
Format de date chelou pour l'ANSM
|
package rss
import (
"strings"
"time"
)
func parseTime(s string) (time.Time, error) {
formats := []string{
"Mon, _2 Jan 2006 15:04:05 MST",
"Mon, _2 Jan 2006 15:04:05 -0700",
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC3339Nano,
"02 Jan 2006 15:04:05 -0700", // cc ANSM
}
s = strings.TrimSpace(s)
var e error
var t time.Time
for _, format := range formats {
t, e = time.Parse(format, s)
if e == nil {
return t, e
}
}
return time.Time{}, e
}
|
package rss
import (
"strings"
"time"
)
func parseTime(s string) (time.Time, error) {
formats := []string{
"Mon, _2 Jan 2006 15:04:05 MST",
"Mon, _2 Jan 2006 15:04:05 -0700",
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC3339Nano,
}
s = strings.TrimSpace(s)
var e error
var t time.Time
for _, format := range formats {
t, e = time.Parse(format, s)
if e == nil {
return t, e
}
}
return time.Time{}, e
}
|
Use interfaces instead of concrete implementations
|
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Orm;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Orm\EntityUpdaterInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
final class EntityUpdater implements EntityUpdaterInterface
{
private $propertyAccesor;
public function __construct(PropertyAccessorInterface $propertyAccesor)
{
$this->propertyAccesor = $propertyAccesor;
}
public function updateProperty(EntityDto $entityDto, string $propertyName, $value): void
{
if (!$this->propertyAccesor->isWritable($entityDto->getInstance(), $propertyName)) {
throw new \RuntimeException(sprintf('The "%s" property of the "%s" entity is not writable.', $propertyName, $entityDto->getName()));
}
$entityInstance = $entityDto->getInstance();
$this->propertyAccesor->setValue($entityInstance, $propertyName, $value);
$entityDto->setInstance($entityInstance);
}
}
|
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Orm;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Orm\EntityUpdaterInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use Symfony\Component\PropertyAccess\PropertyAccessor;
/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
final class EntityUpdater implements EntityUpdaterInterface
{
private $propertyAccesor;
public function __construct(PropertyAccessor $propertyAccesor)
{
$this->propertyAccesor = $propertyAccesor;
}
public function updateProperty(EntityDto $entityDto, string $propertyName, $value): void
{
if (!$this->propertyAccesor->isWritable($entityDto->getInstance(), $propertyName)) {
throw new \RuntimeException(sprintf('The "%s" property of the "%s" entity is not writable.', $propertyName, $entityDto->getName()));
}
$entityInstance = $entityDto->getInstance();
$this->propertyAccesor->setValue($entityInstance, $propertyName, $value);
$entityDto->setInstance($entityInstance);
}
}
|
Modify : ajout de get Timestamp
|
package entity;
import java.sql.Timestamp;
import java.util.Calendar;
import java.io.Serializable;
/**
* Created by corentin on 10/03/15.
*/
public abstract class AbstractEntity implements Serializable {
/**
* Unique id of entity
*/
protected long id;
/**
* Type of entity
*/
protected String type;
/**
* Timestamp
*/
protected Timestamp lastUpdate;
/**
* Basic contruct, assign an id
*/
public AbstractEntity()
{
id = -1;
}
/**
* Update the lastUpdate timestamp to current timestamp
*/
public void updateDate() {
this.lastUpdate = new Timestamp(Calendar.getInstance().getTime().getTime());
}
public long getId() {
return id;
}
public void setId(long id)
{
this.id=id;
}
public String getType() {
return type;
}
public Timestamp getLastUpdate() {
return lastUpdate;
}
}
|
package entity;
import java.sql.Timestamp;
import java.util.Calendar;
import java.io.Serializable;
/**
* Created by corentin on 10/03/15.
*/
public abstract class AbstractEntity implements Serializable {
/**
* Unique id of entity
*/
protected long id;
/**
* Type of entity
*/
protected String type;
/**
* Timestamp
*/
protected Timestamp lastUpdate;
/**
* Basic contruct, assign an id
*/
public AbstractEntity()
{
id = -1;
}
/**
* Update the lastUpdate timestamp to current timestamp
*/
public void updateDate() {
this.lastUpdate = new Timestamp(Calendar.getInstance().getTime().getTime());
}
public long getId() {
return id;
}
public void setId(long id)
{
this.id=id;
}
public String getType() {
return type;
}
}
|
Move key to correct element
|
import React from 'react'
import BlankSlate from './BlankSlate'
import EventCard from '../EventCard'
import StyledEvents, {
StyledLink,
StyledList,
StyledListItem,
} from './Events.css'
export default ({ events = [] }) => {
if (!events.length) {
return <BlankSlate>No events yet. Check back soon.</BlankSlate>
}
return (
<StyledEvents>
<StyledList>
{events.map((event, index) => (
<StyledListItem key={event.slug}>
<StyledLink to={`/events/${event.slug}`}>
<EventCard {...event }/>
</StyledLink>
</StyledListItem>
))}
</StyledList>
</StyledEvents>
)
}
|
import React from 'react'
import BlankSlate from './BlankSlate'
import EventCard from '../EventCard'
import StyledEvents, {
StyledLink,
StyledList,
StyledListItem,
} from './Events.css'
export default ({ events = [] }) => {
if (!events.length) {
return <BlankSlate>No events yet. Check back soon.</BlankSlate>
}
return (
<StyledEvents>
<StyledList>
{events.map((event, index) => (
<StyledListItem>
<StyledLink key={index} to={`/events/${event.slug}`}>
<EventCard {...event }/>
</StyledLink>
</StyledListItem>
))}
</StyledList>
</StyledEvents>
)
}
|
[5.1] Handle InnoDB Deadlocks By Re-Attempting Transactions
https://github.com/laravel/framework/issues/12813
|
<?php
namespace Illuminate\Database;
use Exception;
use Illuminate\Support\Str;
trait DetectsLostConnections
{
/**
* Determine if the given exception was caused by a lost connection.
*
* @param \Exception $e
* @return bool
*/
protected function causedByLostConnection(Exception $e)
{
$message = $e->getMessage();
return Str::contains($message, [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Deadlock found when trying to get lock',
'Error writing data to the connection',
'Resource deadlock avoided'
]);
}
}
|
<?php
namespace Illuminate\Database;
use Exception;
use Illuminate\Support\Str;
trait DetectsLostConnections
{
/**
* Determine if the given exception was caused by a lost connection.
*
* @param \Exception $e
* @return bool
*/
protected function causedByLostConnection(Exception $e)
{
$message = $e->getMessage();
return Str::contains($message, [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Deadlock found when trying to get lock',
'Error writing data to the connection',
]);
}
}
|
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
Fix corner case for javadoc redirector
|
/*
* Copyright 2014 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.web;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class LegacyJavadocRedirectServlet extends HttpServlet {
private static final String PREFIX = "/w/docs/javadoc";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String requestURI = request.getRequestURI();
Preconditions.checkArgument(requestURI.startsWith(PREFIX));
String requestWithoutPrefix = requestURI.substring(PREFIX.length());
if (requestWithoutPrefix.isEmpty()) {
requestWithoutPrefix = "/";
}
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader(HttpHeaders.LOCATION, "http://zxing.github.io/zxing/apidocs" + requestWithoutPrefix);
}
}
|
/*
* Copyright 2014 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.web;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class LegacyJavadocRedirectServlet extends HttpServlet {
private static final String PREFIX = "/w/docs/javadoc/";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String requestURI = request.getRequestURI();
Preconditions.checkArgument(requestURI.startsWith(PREFIX));
String redirectURI = "http://zxing.github.io/zxing/apidocs/" + requestURI.substring(PREFIX.length());
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader(HttpHeaders.LOCATION, redirectURI);
}
}
|
Add setInterval to keep clock up to date
|
angular.module('mini-data.controllers', [])
.controller('mainCtrl', function($scope){
var getTimeInfo = function(){
var now = new Date();
var hours = now.getHours();
var period = 'AM';
var minutes = now.getMinutes();
if(hours > 12){
hours -= 12;
period = 'PM';
}
minutes < 10 && (minutes = '0' + minutes);
return hours + ':' + minutes + period;
}
var getDateInfo = function(){
var monthObj = {
0: 'January', 1: 'February', 2: 'March', 3: 'April', 4: 'May', 5: 'June',
6: 'July', 7: 'August', 8: 'September', 9: 'October', 10: 'November', 11: 'December'
}
var now = new Date();
var day = now.getDate();
var month = monthObj[now.getMonth()];
var year = now.getFullYear();
return month + ' ' + day + 'th, ' + year;
}
$scope.time = getTimeInfo();
setInterval(function(){
$scope.$apply(function(){
$scope.time = getTimeInfo();
});
}, 10000);
$scope.date = getDateInfo();
});
|
angular.module('mini-data.controllers', [])
.controller('mainCtrl', function($scope){
var getTimeInfo = function(){
var now = new Date();
var hours = now.getHours();
var period = 'AM';
var minutes = now.getMinutes();
if(hours > 12){
hours -= 12;
period = 'PM';
}
minutes < 10 && (minutes = '0' + minutes);
return hours + ':' + minutes + period;
}
var getDateInfo = function(){
var monthObj = {
0: 'January', 1: 'February', 2: 'March', 3: 'April', 4: 'May', 5: 'June',
6: 'July', 7: 'August', 8: 'September', 9: 'October', 10: 'November', 11: 'December'
}
var now = new Date();
var day = now.getDate();
var month = monthObj[now.getMonth()];
var year = now.getFullYear();
return month + ' ' + day + 'th, ' + year;
}
$scope.time = getTimeInfo();
$scope.date = getDateInfo();
});
|
Fix componet build on iterator
|
<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-calendar-check-o"></i>
<span class="label {{ $appointments->count() > 0 ? 'label-warning' : 'label-default' }}">{{ $appointments->count() }}</span>
</a>
@foreach($appointments as $appointment)
<ul class="dropdown-menu">
<li>
<!-- Inner Menu: contains the notifications -->
<ul class="menu">
<li><!-- start notification -->
<a href="{{ route('user.agenda') . '#' . $appointment->code() }}">
<i class="fa fa-calendar-check-o text-aqua"></i> {{ $appointment->service->name }} : {{ $appointment->business->name }}
</a>
</li>
<!-- end notification -->
</ul>
</li>
<li class="footer"><a href="{{ route('user.agenda') }}"></a></li>
</ul>
@endforeach
</li>
|
<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-calendar-check-o"></i>
<span class="label {{ $appointments->count() > 0 ? 'label-warning' : 'label-default' }}">{{ $appointments->count() }}</span>
</a>
<ul class="dropdown-menu">
@foreach($appointments as $appointment)
<li>
<!-- Inner Menu: contains the notifications -->
<ul class="menu">
<li><!-- start notification -->
<a href="{{ route('user.agenda') . '#' . $appointment->code() }}">
<i class="fa fa-calendar-check-o text-aqua"></i> {{ $appointment->service->name }} : {{ $appointment->business->name }}
</a>
</li>
<!-- end notification -->
</ul>
</li>
@endforeach
<li class="footer"><a href="{{ route('user.agenda') . '#' . $appointment->code() }}"></a></li>
</ul>
</li>
|
Add back call to setStyle on options
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
const vectorlayer = require('./VectorLayer.js');
export class LeafletPathModel extends vectorlayer.LeafletVectorLayerModel {
defaults() {
return {
...super.defaults(),
_view_name: 'LeafletPathView',
_model_name: 'LeafletPathModel',
stroke: true,
color: '#0033FF',
weight: 5,
fill: true,
fill_color: null,
fill_opacity: 0.2,
dash_array: null,
line_cap: 'round',
line_join: 'round',
pointer_events: '',
class_name: ''
};
}
}
export class LeafletPathView extends vectorlayer.LeafletVectorLayerView {
model_events() {
super.model_events();
var key;
var o = this.model.get('options');
for (var i = 0; i < o.length; i++) {
key = o[i];
this.listenTo(
this.model,
'change:' + key,
function() {
this.obj.setStyle(this.get_options());
},
this
);
}
this.obj.setStyle(this.get_options());
}
}
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
const vectorlayer = require('./VectorLayer.js');
export class LeafletPathModel extends vectorlayer.LeafletVectorLayerModel {
defaults() {
return {
...super.defaults(),
_view_name: 'LeafletPathView',
_model_name: 'LeafletPathModel',
stroke: true,
color: '#0033FF',
weight: 5,
fill: true,
fill_color: null,
fill_opacity: 0.2,
dash_array: null,
line_cap: 'round',
line_join: 'round',
pointer_events: '',
class_name: ''
};
}
}
export class LeafletPathView extends vectorlayer.LeafletVectorLayerView {
model_events() {
super.model_events();
this.obj.setStyle(this.get_options());
}
}
|
Fix some more U tests ...
|
package redis.clients.jedis.tests;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPipeline;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;
public class PipeliningTest extends Assert {
private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0);
private Jedis jedis;
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.host, hnp.port, 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
}
@Test
public void pipeline() throws UnknownHostException, IOException {
List<Object> results = jedis.pipelined(new JedisPipeline() {
public void execute() {
client.set("foo", "bar");
client.get("foo");
}
});
assertEquals(2, results.size());
assertArrayEquals("OK".getBytes(Protocol.UTF8), (byte[])results.get(0));
assertArrayEquals("bar".getBytes(Protocol.UTF8), (byte[])results.get(1));
}
}
|
package redis.clients.jedis.tests;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPipeline;
import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;
public class PipeliningTest extends Assert {
private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0);
private Jedis jedis;
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.host, hnp.port, 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
}
@Test
public void pipeline() throws UnknownHostException, IOException {
List<Object> results = jedis.pipelined(new JedisPipeline() {
public void execute() {
client.set("foo", "bar");
client.get("foo");
}
});
assertEquals(2, results.size());
assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1));
}
}
|
Return right path on gulp watch
|
var pathModule = require('path');
module.exports = function(data) {
data = data || {};
var functions = [
{
name: 'revisionedPath',
func: function (fullPath) {
var path = pathModule.basename(fullPath);
if (data.manifest) {
if(!data.manifest[path]) {
throw new Error('File '+path+' seems to not be revisioned');
}
return pathModule.join(pathModule.dirname(fullPath),
data.manifest[path]);
} else {
return fullPath;
}
}
},
{
name: 'assetPath',
func: function (path) {
return pathModule.join(data.config.dest.assets, path);
}
}
];
return functions;
}
|
var pathModule = require('path');
module.exports = function(data) {
data = data || {};
var functions = [
{
name: 'revisionedPath',
func: function (fullPath) {
var path = pathModule.basename(fullPath);
if (data.manifest) {
if(!data.manifest[path]) {
throw new Error('File '+path+' seems to not be revisioned');
}
return pathModule.join(pathModule.dirname(fullPath),
data.manifest[path]);
} else {
return path;
}
}
},
{
name: 'assetPath',
func: function (path) {
return pathModule.join(data.config.dest.assets, path);
}
}
];
return functions;
}
|
Fix the auto-generated docstrings of style sheets
|
# This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import inspect
import os
import sys
from .. import DATA_PATH
from ..style import StyleSheetFile
from .matcher import matcher
__all__ = ['matcher', 'sphinx', 'sphinx_base14']
STYLESHEETS_PATH = os.path.join(DATA_PATH, 'stylesheets')
def path(filename):
return os.path.join(STYLESHEETS_PATH, filename)
sphinx = StyleSheetFile(path('sphinx.rts'))
sphinx_article = StyleSheetFile(path('sphinx_article.rts'))
sphinx_base14 = StyleSheetFile(path('base14.rts'))
# generate docstrings for the StyleSheet instances
for name, stylesheet in inspect.getmembers(sys.modules[__name__]):
if not isinstance(stylesheet, StyleSheetFile):
continue
stylesheet.__doc__ = ('{}\n\nEntry point name: ``{}``'
.format(stylesheet.description, stylesheet))
|
# This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import inspect
import os
import sys
from .. import DATA_PATH
from ..style import StyleSheetFile
from .matcher import matcher
__all__ = ['matcher', 'sphinx', 'sphinx_base14']
STYLESHEETS_PATH = os.path.join(DATA_PATH, 'stylesheets')
def path(filename):
return os.path.join(STYLESHEETS_PATH, filename)
sphinx = StyleSheetFile(path('sphinx.rts'))
sphinx_article = StyleSheetFile(path('sphinx_article.rts'))
sphinx_base14 = StyleSheetFile(path('base14.rts'))
# generate docstrings for the StyleSheet instances
for name, stylesheet in inspect.getmembers(sys.modules[__name__]):
if not isinstance(stylesheet, StyleSheetFile):
continue
stylesheet.__doc__ = (':entry point name: ``{}``\n\n{}'
.format(stylesheet, stylesheet.description))
|
Make OS pie chart aware of dates
|
<?php
require_once('./conf.php');
$sql =
"SELECT type, sum(cnt) as sumcnt FROM (
select
useragent,
(SELECT count(*) FROM log
WHERE useragent_id=useragent.id AND
`responsecode` <> " . E_DOSPROTECT . " AND
`date` BETWEEN timestamp('$startTime') AND timestamp('$endTime')) as cnt,
(CASE
WHEN useragent LIKE '%Linux%' THEN 'Linux'
WHEN useragent LIKE '%Macintosh%' THEN 'Macintosh'
WHEN useragent LIKE '%Windows%' THEN 'Windows'
WHEN useragent LIKE 'CloogleBot' THEN 'CloogleBot'
WHEN useragent LIKE 'vim-clean' THEN 'vim-clean'
WHEN useragent LIKE 'cloogle-cli' THEN 'cloogle-cli'
WHEN useragent LIKE 'CloogleMail' THEN 'CloogleMail'
WHEN useragent LIKE 'cloogle-irc' THEN 'cloogle-irc'
ELSE 'Other'
END) as type
FROM useragent
ORDER BY cnt DESC
) counts
GROUP BY type
ORDER BY sumcnt DESC";
$stmt = $db->stmt_init();
if (!$stmt->prepare($sql))
var_dump($stmt->error);
$stmt->execute();
$stmt->bind_result($type, $count);
$results = [];
while ($stmt->fetch())
$results[] = ['name' => $type, 'y' => (int) $count];
$stmt->close();
header('Content-Type: text/javascript');
echo "$callback(" . json_encode($results) . ");";
|
<?php
require_once('./conf.php');
$sql =
"SELECT type, sum(cnt) as sumcnt FROM (
select
useragent,
(SELECT count(*) FROM log WHERE useragent_id=useragent.id) as cnt,
(CASE
WHEN useragent LIKE '%Linux%' THEN 'Linux'
WHEN useragent LIKE '%Macintosh%' THEN 'Macintosh'
WHEN useragent LIKE '%Windows%' THEN 'Windows'
WHEN useragent LIKE 'CloogleBot' THEN 'CloogleBot'
WHEN useragent LIKE 'vim-clean' THEN 'vim-clean'
WHEN useragent LIKE 'cloogle-cli' THEN 'cloogle-cli'
WHEN useragent LIKE 'CloogleMail' THEN 'CloogleMail'
WHEN useragent LIKE 'cloogle-irc' THEN 'cloogle-irc'
ELSE 'Other'
END) as type
FROM useragent
ORDER BY cnt DESC
) counts
GROUP BY type
ORDER BY sumcnt DESC";
$stmt = $db->stmt_init();
if (!$stmt->prepare($sql))
var_dump($stmt->error);
$stmt->execute();
$stmt->bind_result($type, $count);
$results = [];
while ($stmt->fetch())
$results[] = ['name' => $type, 'y' => (int) $count];
$stmt->close();
header('Content-Type: text/javascript');
echo "$callback(" . json_encode($results) . ");";
|
Remove scrollIntoView() to fix scroll jank preventing users from scrolling
|
const observer = new IntersectionObserver(entries => {
const intersectingEntries = entries.filter(e => e.isIntersecting);
for (const entry of intersectingEntries) {
const previouslyActive = document.querySelector('.pageNav a.is-active');
if (previouslyActive) {
previouslyActive.classList.remove('is-active');
}
const id = entry.target.getAttribute('id')
const newActive = document.querySelector(`.pageNav a[href="#${id}"]`);
newActive.classList.add('is-active');
}
}, { rootMargin: `0% 0% -90% 0%` }
);
//track headings with an id
if (document.querySelector('.pageNav')) {
for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) {
observer.observe(heading)
}
}
|
const observer = new IntersectionObserver(entries => {
const intersectingEntries = entries.filter(e => e.isIntersecting);
for (const entry of intersectingEntries) {
const previouslyActive = document.querySelector('.pageNav a.is-active');
if (previouslyActive) {
previouslyActive.classList.remove('is-active');
}
const id = entry.target.getAttribute('id')
const newActive = document.querySelector(`.pageNav a[href="#${id}"]`);
newActive.classList.add('is-active');
newActive.scrollIntoView({ block: 'nearest' });
}
}, { rootMargin: `0% 0% -90% 0%` }
);
//track headings with an id
if (document.querySelector('.pageNav')) {
for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) {
observer.observe(heading)
}
}
|
Add integration test for starting the API
|
from piper.cli import cmd_piperd
from piper.api import api
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piperd.entry(self.mock)
clibase.assert_called_once_with(
'piperd',
(api.ApiCLI,),
args=self.mock
)
clibase.return_value.entry.assert_called_once_with()
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_return_value(self, clibase):
ret = cmd_piperd.entry()
assert ret is clibase.return_value.entry.return_value
class TestEntryIntegration(object):
@mock.patch('piper.api.api.Flask')
def test_api_start(self, flask):
cmd_piperd.entry(['api', 'start'])
flask.return_value.run.assert_called_once_with(debug=True)
|
from piper.cli import cmd_piperd
from piper.api import api
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piperd.entry(self.mock)
clibase.assert_called_once_with(
'piperd',
(api.ApiCLI,),
args=self.mock
)
clibase.return_value.entry.assert_called_once_with()
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_return_value(self, clibase):
ret = cmd_piperd.entry()
assert ret is clibase.return_value.entry.return_value
|
Remove the extra require for https
|
var request = require('request');
var yaml = require('js-yaml');
// The URL of the data file with GitHub's language colors.
exports.languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
// Given an Object of languages (from language name Strings to Objects),
// filterColors will return an Object of language name Strings to String hex
// color values, with all color-less languages removed.
exports.filterColors = function (languages) {
return Object.keys(languages).reduce(function (memo, languageName) {
var color = languages[languageName].color;
if (color) {
memo[languageName] = color;
}
return memo;
}, {});
};
// get accepts a callback, downloads GitHub's language colors,
// creates a new languages Object, and passes it to the callback when it is
// ready. The languages Object has String language name keys and String hex
// color values (with leading "#"s).
exports.get = function (callback) {
request(exports.languagesURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var languages = exports.filterColors(yaml.safeLoad(body));
callback(languages);
} else {
callback(undefined);
}
})
};
|
var https = require('https');
var yaml = require('js-yaml');
var request = require('request');
// The URL of the data file with GitHub's language colors.
exports.languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
// Given an Object of languages (from language name Strings to Objects),
// filterColors will return an Object of language name Strings to String hex
// color values, with all color-less languages removed.
exports.filterColors = function (languages) {
return Object.keys(languages).reduce(function (memo, languageName) {
var color = languages[languageName].color;
if (color) {
memo[languageName] = color;
}
return memo;
}, {});
};
// get accepts a callback, downloads GitHub's language colors,
// creates a new languages Object, and passes it to the callback when it is
// ready. The languages Object has String language name keys and String hex
// color values (with leading "#"s).
exports.get = function (callback) {
request(exports.languagesURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var languages = exports.filterColors(yaml.safeLoad(body));
callback(languages);
} else {
callback(undefined);
}
})
};
|
Add a docstring to image_bytes
|
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in the terminal.
If filename=None the filename defaults to "Unnamed file".
"""
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(image_bytes(f.read(), filename=fn))
|
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(image_bytes(f.read(), filename=fn))
|
Add fixme for future revision
|
"""
URLCONF for the user accounts app (part 2/2).
"""
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from . import views
# User accounts URL patterns configuration
urlpatterns = (
# My account page
url(r'^$', views.my_account_show, name='index'),
# Password change
url(r'^modification-mot-de-passe/$', auth_views.password_change, {
'post_change_redirect': 'myaccount:password_change_done',
'template_name': 'accounts/password_change_form.html'
}, name='password_change'),
url(r'^modification-mot-de-passe/ok/$', auth_views.password_change_done, {
'template_name': 'accounts/password_change_done.html'
}, name='password_change_done'),
# Email change
# FIXME Move to root urlconf if possible (to avoid useless dependency)
url(r'^modification-adresse-email/', include('apps.changemail.urls')),
)
|
"""
URLCONF for the user accounts app (part 2/2).
"""
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from . import views
# User accounts URL patterns configuration
urlpatterns = (
# My account page
url(r'^$', views.my_account_show, name='index'),
# Password change
url(r'^modification-mot-de-passe/$', auth_views.password_change, {
'post_change_redirect': 'myaccount:password_change_done',
'template_name': 'accounts/password_change_form.html'
}, name='password_change'),
url(r'^modification-mot-de-passe/ok/$', auth_views.password_change_done, {
'template_name': 'accounts/password_change_done.html'
}, name='password_change_done'),
# Email change
url(r'^modification-adresse-email/', include('apps.changemail.urls')),
)
|
Handle instances where level_tag is undefined
Better mimics the implementation of message.tags in Django 1.7
|
from django import template
from django.contrib.messages.utils import get_level_tags
from django.utils.encoding import force_text
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix
along with any tags included in message.extra_tags
Messages in Django >= 1.7 have a message.level_tag attr
"""
level_tag = force_text(LEVEL_TAGS.get(message.level, ''), strings_only=True)
if level_tag == u"error":
level_tag = u"danger"
if level_tag:
alert_level_tag = u"alert-{tag}".format(tag=level_tag)
else:
alert_level_tag = None
extra_tags = force_text(message.extra_tags, strings_only=True)
if extra_tags and alert_level_tag:
return u' '.join([extra_tags, alert_level_tag])
elif extra_tags:
return extra_tags
elif alert_level_tag:
return alert_level_tag
return u''
|
from django import template
from django.contrib.messages.utils import get_level_tags
from django.utils.encoding import force_text
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix
along with any tags included in message.extra_tags
Messages in Django >= 1.7 have a message.level_tag attr
"""
level_tag = force_text(LEVEL_TAGS.get(message.level, ''), strings_only=True)
if level_tag == u"error":
level_tag = u"danger"
alert_level_tag = u"alert-{tag}".format(tag=level_tag)
tags = [alert_level_tag]
extra_tags = force_text(message.extra_tags, strings_only=True)
if extra_tags:
tags.append(extra_tags)
return u" ".join(tags)
|
emoji: Fix misleading variable name `list` for non-lists.
The `Array#reduce` method basically operates on a list... but
these variables are referring to essentially the opposite thing!
The array (or "list") acts as input, but this variable / this
parameter to the inner function is the *output* we're in the
middle of building.
That makes this misnaming super confusing if you don't have the
specifics of the `Array#reduce` signature solid in your head;
and in any event, it's just wrong. Fix it.
|
/* @flow */
import { createSelector } from 'reselect';
import { getRawRealmEmoji } from '../directSelectors';
import { getAuth } from '../account/accountSelectors';
import { getFullUrl } from '../utils/url';
export const getAllRealmEmojiById = createSelector(getAuth, getRawRealmEmoji, (auth, emojis) =>
Object.keys(emojis).reduce((result, key) => {
result[key] = { ...emojis[key], source_url: getFullUrl(emojis[key].source_url, auth.realm) };
return result;
}, {}),
);
export const getActiveRealmEmojiById = createSelector(getAllRealmEmojiById, emojis =>
Object.keys(emojis)
.filter(emoji => !emojis[emoji].deactivated)
.reduce((result, key) => {
result[key] = emojis[key];
return result;
}, {}),
);
|
/* @flow */
import { createSelector } from 'reselect';
import { getRawRealmEmoji } from '../directSelectors';
import { getAuth } from '../account/accountSelectors';
import { getFullUrl } from '../utils/url';
export const getAllRealmEmojiById = createSelector(getAuth, getRawRealmEmoji, (auth, emojis) =>
Object.keys(emojis).reduce((list, key) => {
list[key] = { ...emojis[key], source_url: getFullUrl(emojis[key].source_url, auth.realm) };
return list;
}, {}),
);
export const getActiveRealmEmojiById = createSelector(getAllRealmEmojiById, emojis =>
Object.keys(emojis)
.filter(emoji => !emojis[emoji].deactivated)
.reduce((list, key) => {
list[key] = emojis[key];
return list;
}, {}),
);
|
Declare dependency on zeit.cms (for testing)
|
from setuptools import setup, find_packages
setup(
name='zeit.objectlog',
version='0.11dev',
author='Christian Zagrodnick',
author_email='cz@gocept.com',
description="""\
""",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit'],
install_requires=[
'ZODB3',
'pytz',
'setuptools',
'zc.sourcefactory',
'zeit.cms',
'zope.app.component',
'zope.app.form',
'zope.app.generations',
'zope.app.keyreference',
'zope.app.security',
'zope.app.securitypolicy',
'zope.app.testing',
'zope.app.zcmlfiles',
'zope.app.zopeappgenerations',
'zope.component',
'zope.i18n>3.4.0',
'zope.interface',
'zope.security',
'zope.securitypolicy',
'zope.testing',
],
)
|
from setuptools import setup, find_packages
setup(
name='zeit.objectlog',
version='0.11dev',
author='Christian Zagrodnick',
author_email='cz@gocept.com',
description="""\
""",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit'],
install_requires=[
'ZODB3',
'pytz',
'setuptools',
'zc.sourcefactory',
'zope.app.component',
'zope.app.form',
'zope.app.generations',
'zope.app.keyreference',
'zope.app.security',
'zope.app.securitypolicy',
'zope.app.testing',
'zope.app.zcmlfiles',
'zope.app.zopeappgenerations',
'zope.component',
'zope.i18n>3.4.0',
'zope.interface',
'zope.security',
'zope.securitypolicy',
'zope.testing',
],
)
|
Remove unused main entry point.
|
import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
|
import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
Add placeholder htmlbars flag in dummy app for packaging to toggle
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
//'ember-htmlbars': true
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
[clean] Use the specifiers in the JCC order
|
package net.safedata.springboot.training.d02.s04.exceptions;
import net.safedata.springboot.training.d02.s04.dto.MessageDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* The most common exception handlers
*
* @author bogdan.solga
*/
@ControllerAdvice
public class ExceptionHandlers {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlers.class);
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public MessageDTO notFoundException(final NotFoundException e) {
return new MessageDTO(e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public MessageDTO illegalArgumentException(final IllegalArgumentException e) {
return new MessageDTO(e.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MessageDTO internalServerError(final Exception e) {
LOGGER.error(e.getMessage(), e);
return new MessageDTO("Oops!");
}
}
|
package net.safedata.springboot.training.d02.s04.exceptions;
import net.safedata.springboot.training.d02.s04.dto.MessageDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* The most common exception handlers
*
* @author bogdan.solga
*/
@ControllerAdvice
public class ExceptionHandlers {
private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlers.class);
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public MessageDTO notFoundException(final NotFoundException e) {
return new MessageDTO(e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public MessageDTO illegalArgumentException(final IllegalArgumentException e) {
return new MessageDTO(e.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MessageDTO internalServerError(final Exception e) {
LOGGER.error(e.getMessage(), e);
return new MessageDTO("Oops!");
}
}
|
BB-4395: Create entity MenuUpdate that extends MenuUpdate model
- improve tests
|
<?php
namespace Oro\Bundle\NavigationBundle\Tests\Unit\Entity;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
use Oro\Bundle\NavigationBundle\Entity\MenuUpdate;
class MenuUpdateTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
public function testProperties()
{
$properties = [
['id', 42],
['key', 'page_wrapper'],
['parentId', 'page_container'],
['title', 'title'],
['uri', 'uri'],
['menu', 'main_menu'],
['ownershipType', MenuUpdate::OWNERSHIP_GLOBAL],
['ownerId', 3],
['isActive', true],
['priority', 1],
];
$this->assertPropertyAccessors(new MenuUpdate(), $properties);
}
}
|
<?php
namespace Oro\Bundle\NavigationBundle\Tests\Unit\Entity;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
use Oro\Bundle\NavigationBundle\Entity\MenuUpdate;
class MenuUpdateTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
public function testProperties()
{
$properties = [
['id', 42],
['key', 'page_wrapper'],
['parentId', 'page_container'],
['title', ''],
['menu', 'main_menu'],
['ownershipType', MenuUpdate::OWNERSHIP_GLOBAL],
['ownerId', 3],
['isActive', true],
['priority', 1],
];
$this->assertPropertyAccessors(new MenuUpdate(), $properties);
}
}
|
Send 404 errors as JSON to keep NPM happy
|
const express = require('express')
const fs = require('fs')
const http = require('http')
const https = require('https')
const path = require('path')
function startHttpServer(app, port) {
const httpServer = http.Server(app)
httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`))
}
function startHttpsServer(app, port, sslKey, sslCert) {
const privateKey = fs.readFileSync(sslKey, 'utf8')
const certificate = fs.readFileSync(sslCert, 'utf8')
const httpsServer = https.Server({key: privateKey, cert: certificate}, app)
httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`))
}
function jsonError(res) {
return function (err) {
if (err) {
res.status(err.status).json({})
}
}
}
function bindRoutes(app, rootFolder) {
const sendFileOptions = {root: path.resolve(rootFolder)}
app.use((req, res, next) => {
if (req.url.endsWith('gz')) {
res.sendFile(req.url, sendFileOptions, jsonError(res))
} else {
res.sendFile(`${req.url}/index.json`, sendFileOptions, jsonError(res))
}
})
}
function init(options) {
const app = express()
bindRoutes(app, options.root)
startHttpServer(app, options.port)
if (options.https) {
startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert)
}
}
module.exports = init
|
const express = require('express')
const fs = require('fs')
const http = require('http')
const https = require('https')
const path = require('path')
function startHttpServer(app, port) {
const httpServer = http.Server(app)
httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`))
}
function startHttpsServer(app, port, sslKey, sslCert) {
const privateKey = fs.readFileSync(sslKey, 'utf8')
const certificate = fs.readFileSync(sslCert, 'utf8')
const httpsServer = https.Server({key: privateKey, cert: certificate}, app)
httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`))
}
function bindRoutes(app, rootFolder) {
const sendFileOptions = {root: path.resolve(rootFolder)}
app.use((req, res, next) => {
if (req.url.endsWith('gz')) {
res.sendFile(req.url, sendFileOptions)
} else {
res.sendFile(`${req.url}/index.json`, sendFileOptions)
}
})
}
function init(options) {
const app = express()
bindRoutes(app, options.root)
startHttpServer(app, options.port)
if (options.https) {
startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert)
}
}
module.exports = init
|
Implement 'inverse' prop and remove obsolete styling
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { TextBody, TextDisplay } from '../typography';
import theme from './theme.css';
import cx from "classnames";
export default class Label extends PureComponent {
static propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.array]),
for: PropTypes.string,
inverse: PropTypes.bool,
size: PropTypes.oneOf(['small', 'medium']),
};
static defaultProps = {
inverse: false,
size: 'medium',
};
render() {
const { children, inverse, size } = this.props;
const classNames = cx(
theme['label'],
{
[theme['is-inverse']]: inverse,
},
);
const Element = size === 'medium' ? TextDisplay : TextBody;
return (
<Element color={inverse ? 'white' : 'teal'} element="label" htmlFor={this.props.for} marginBottom={3} className={classNames}>
{children}
</Element>
);
}
}
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { TextBody, TextDisplay } from '../typography';
import theme from './theme.css';
export default class Label extends PureComponent {
static propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.array]),
for: PropTypes.string,
size: PropTypes.oneOf(['small', 'medium']),
};
static defaultProps = {
size: 'medium',
};
render() {
const { children, size } = this.props;
const Element = size === 'medium' ? TextDisplay : TextBody;
return (
<Element element="label" htmlFor={this.props.for} marginBottom={3} className={theme['label']}>
{children}
</Element>
);
}
}
|
Fix getting snapshotsoftware on old snapshots
|
from pydash import find
from ereuse_devicehub.resources.device.domain import DeviceDomain
from ereuse_devicehub.resources.event.device import DeviceEventDomain
from ereuse_devicehub.scripts.updates.update import Update
class SnapshotSoftware(Update):
"""
Changes the values of SnapshotSoftware and adds it to the materialized one in devices
"""
def execute(self, database):
SNAPSHOT_SOFTWARE = {
'DDI': 'Workbench',
'Scan': 'AndroidApp',
'DeviceHubClient': 'Web'
}
for snapshot in DeviceEventDomain.get({'@type': "devices:Snapshot"}):
snapshot['snapshotSoftware'] = SNAPSHOT_SOFTWARE[snapshot.get('snapshotSoftware', 'DDI')]
DeviceEventDomain.update_one_raw(snapshot['_id'], {'$set': {'snapshotSoftware': snapshot['snapshotSoftware']}})
for device in DeviceDomain.get({'events._id': snapshot['_id']}):
materialized_snapshot = find(device['events'], lambda event: event['_id'] == snapshot['_id'])
materialized_snapshot['snapshotSoftware'] = snapshot['snapshotSoftware']
DeviceDomain.update_one_raw(device['_id'], {'$set': {'events': device['events']}})
|
from pydash import find
from ereuse_devicehub.resources.device.domain import DeviceDomain
from ereuse_devicehub.resources.event.device import DeviceEventDomain
from ereuse_devicehub.scripts.updates.update import Update
class SnapshotSoftware(Update):
"""
Changes the values of SnapshotSoftware and adds it to the materialized one in devices
"""
def execute(self, database):
SNAPSHOT_SOFTWARE = {
'DDI': 'Workbench',
'Scan': 'AndroidApp',
'DeviceHubClient': 'Web'
}
for snapshot in DeviceEventDomain.get({'@type': "devices:Snapshot"}):
snapshot['snapshotSoftware'] = SNAPSHOT_SOFTWARE[snapshot['snapshotSoftware']]
DeviceEventDomain.update_one_raw(snapshot['_id'], {'$set': {'snapshotSoftware': snapshot['snapshotSoftware']}})
for device in DeviceDomain.get({'events._id': snapshot['_id']}):
materialized_snapshot = find(device['events'], lambda event: event['_id'] == snapshot['_id'])
materialized_snapshot['snapshotSoftware'] = snapshot['snapshotSoftware']
DeviceDomain.update_one_raw(device['_id'], {'$set': {'events': device['events']}})
|
Bump aiohttp version constraint to <3.4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.10.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.10.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.1'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
|
Allow keys to contain hyphens
See the [full length example](http://www.yaml.org/spec/1.2/spec.html#id2761803) from the yaml docs.
|
// Contributed by ribrdb @ code.google.com
/**
* @fileoverview
* Registers a language handler for YAML.
*
* @author ribrdb
*/
PR['registerLangHandler'](
PR['createSimpleLexer'](
[
[PR['PR_PUNCTUATION'], /^[:|>?]+/, null, ':|>?'],
[PR['PR_DECLARATION'], /^%(?:YAML|TAG)[^#\r\n]+/, null, '%'],
[PR['PR_TYPE'], /^[&]\S+/, null, '&'],
[PR['PR_TYPE'], /^!\S*/, null, '!'],
[PR['PR_STRING'], /^"(?:[^\\"]|\\.)*(?:"|$)/, null, '"'],
[PR['PR_STRING'], /^'(?:[^']|'')*(?:'|$)/, null, "'"],
[PR['PR_COMMENT'], /^#[^\r\n]*/, null, '#'],
[PR['PR_PLAIN'], /^\s+/, null, ' \t\r\n']
],
[
[PR['PR_DECLARATION'], /^(?:---|\.\.\.)(?:[\r\n]|$)/],
[PR['PR_PUNCTUATION'], /^-/],
[PR['PR_KEYWORD'], /^[\w-]+:[ \r\n]/],
[PR['PR_PLAIN'], /^\w+/]
]), ['yaml', 'yml']);
|
// Contributed by ribrdb @ code.google.com
/**
* @fileoverview
* Registers a language handler for YAML.
*
* @author ribrdb
*/
PR['registerLangHandler'](
PR['createSimpleLexer'](
[
[PR['PR_PUNCTUATION'], /^[:|>?]+/, null, ':|>?'],
[PR['PR_DECLARATION'], /^%(?:YAML|TAG)[^#\r\n]+/, null, '%'],
[PR['PR_TYPE'], /^[&]\S+/, null, '&'],
[PR['PR_TYPE'], /^!\S*/, null, '!'],
[PR['PR_STRING'], /^"(?:[^\\"]|\\.)*(?:"|$)/, null, '"'],
[PR['PR_STRING'], /^'(?:[^']|'')*(?:'|$)/, null, "'"],
[PR['PR_COMMENT'], /^#[^\r\n]*/, null, '#'],
[PR['PR_PLAIN'], /^\s+/, null, ' \t\r\n']
],
[
[PR['PR_DECLARATION'], /^(?:---|\.\.\.)(?:[\r\n]|$)/],
[PR['PR_PUNCTUATION'], /^-/],
[PR['PR_KEYWORD'], /^\w+:[ \r\n]/],
[PR['PR_PLAIN'], /^\w+/]
]), ['yaml', 'yml']);
|
Fix failure on Django < 1.4.5
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
# Django >= 1.4.5
from django.utils.encoding import force_bytes, force_text, smart_text # NOQA
from django.utils.six import string_types, text_type, binary_type # NOQA
except ImportError: # pragma: no cover
# Django < 1.4.5
from django.utils.encoding import ( # NOQA
smart_unicode as smart_text, smart_str as force_bytes) # NOQA
force_text = smart_text
string_types = (basestring,)
text_type = unicode
binary_type = str
try:
# Django >= 1.4
from django.utils.crypto import get_random_string # NOQA
except ImportError: # pragma: no cover
# Django < 1.4
from random import choice
get_random_string = lambda n: ''.join(
[choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(n)])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
# Django >= 1.4.5
from django.utils.encoding import force_bytes, force_text, smart_text # NOQA
from django.utils.six import string_types, text_type, binary_type # NOQA
except ImportError: # pragma: no cover
# Django < 1.4.5
from django.utils.encoding import ( # NOQA
smart_unicode as smart_text, smart_str as force_bytes) # NOQA
force_text = smart_text
string_types = basestring
text_type = unicode
binary_type = str
try:
# Django >= 1.4
from django.utils.crypto import get_random_string # NOQA
except ImportError: # pragma: no cover
# Django < 1.4
from random import choice
get_random_string = lambda n: ''.join(
[choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(n)])
|
Add data to JobStep serializer
|
from changes.api.serializer import Serializer, register
from changes.models import JobStep
@register(JobStep)
class JobStepSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'phase': {
'id': instance.phase_id.hex,
},
'data': dict(instance.data),
'result': instance.result,
'status': instance.status,
'node': instance.node,
'duration': instance.duration,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
}
|
from changes.api.serializer import Serializer, register
from changes.models import JobStep
@register(JobStep)
class JobStepSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'phase': {
'id': instance.phase_id.hex,
},
'result': instance.result,
'status': instance.status,
'node': instance.node,
'duration': instance.duration,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
}
|
Fix param name in docblock
|
<?php
namespace QueryTranslator\Values;
/**
* Token sequence holds an array of tokens extracted from the query string.
*
* @see \QueryTranslator\Tokenizing::tokenize()
*/
class TokenSequence
{
/**
* An array of tokens extracted from the input string.
*
* @var \QueryTranslator\Values\Token[]
*/
public $tokens;
/**
* Source query string, unmodified.
*
* @var string
*/
public $source;
/**
* @param \QueryTranslator\Values\Token[] $tokens
* @param string $source
*/
public function __construct(array $tokens, $source)
{
$this->tokens = $tokens;
$this->source = $source;
}
}
|
<?php
namespace QueryTranslator\Values;
/**
* Token sequence holds an array of tokens extracted from the query string.
*
* @see \QueryTranslator\Tokenizing::tokenize()
*/
class TokenSequence
{
/**
* An array of tokens extracted from the input string.
*
* @var \QueryTranslator\Values\Token[]
*/
public $tokens;
/**
* Source query string, unmodified.
*
* @var string
*/
public $source;
/**
* @param \QueryTranslator\Values\Token[] $tokens[]
* @param string $source
*/
public function __construct(array $tokens, $source)
{
$this->tokens = $tokens;
$this->source = $source;
}
}
|
Update list of ignored files in servers bootstrap
|
const fs = require('fs'),
path = require('path'),
async = require('async'),
IGNORE_FILES = ['index.js', '_servers.js', 'servers.json', '.gitignore'],
SERVERS = [],
URLS = {};
fs.readdirSync(__dirname).forEach(function (file) {
if (IGNORE_FILES.includes(file)) { return; }
SERVERS.push({
name: path.basename(file, '.js'),
server: require(path.join(__dirname, file))
});
});
module.exports = {
start: function (callback) {
async.each(SERVERS, function (s, next) {
s.server.listen(function (err) {
if (err) { return next(err); }
URLS[s.name] = s.server.url;
next();
});
}, function (err) {
if (err) { return callback(err); }
fs.writeFileSync(path.join(__dirname, 'servers.json'), JSON.stringify(URLS));
callback();
});
},
close: function (callback) {
async.each(SERVERS, function (server, next) {
server.server.destroy(next);
}, callback);
}
};
|
const fs = require('fs'),
path = require('path'),
async = require('async'),
IGNORE_FILES = ['index.js', '_servers.js', 'servers.json'],
SERVERS = [],
URLS = {};
fs.readdirSync(__dirname).forEach(function (file) {
if (IGNORE_FILES.includes(file)) { return; }
SERVERS.push({
name: path.basename(file, '.js'),
server: require(path.join(__dirname, file))
});
});
module.exports = {
start: function (callback) {
async.each(SERVERS, function (s, next) {
s.server.listen(function (err) {
if (err) { return next(err); }
URLS[s.name] = s.server.url;
next();
});
}, function (err) {
if (err) { return callback(err); }
fs.writeFileSync(path.join(__dirname, 'servers.json'), JSON.stringify(URLS));
callback();
});
},
close: function (callback) {
async.each(SERVERS, function (server, next) {
server.server.destroy(next);
}, callback);
}
};
|
Add ability to list file uploads.
|
<?php
class Stripe_FileUpload extends Stripe_ApiResource
{
public static function baseUrl()
{
return Stripe::$apiUploadBase;
}
public static function className($class)
{
return 'file';
}
/**
* @param string $id The ID of the file upload to retrieve.
* @param string|null $apiKey
*
* @return Stripe_FileUpload
*/
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
/**
* @param array|null $params
* @param string|null $apiKey
*
* @return Stripe_FileUpload The created file upload.
*/
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
/**
* @param array|null $params
* @param string|null $apiKey
*
* @return array An array of Stripe_FileUploads
*/
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
}
|
<?php
class Stripe_FileUpload extends Stripe_ApiResource
{
public static function baseUrl()
{
return Stripe::$apiUploadBase;
}
public static function className($class)
{
return 'file';
}
/**
* @param string $id The ID of the file upload to retrieve.
* @param string|null $apiKey
*
* @return Stripe_FileUpload
*/
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
/**
* @param array|null $params
* @param string|null $apiKey
*
* @return Stripe_FileUpload The created file upload.
*/
public static function create($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedCreate($class, $params, $apiKey);
}
}
|
Fix : Use SCryptPasswordHaser instead of SShaPasswordHasher
Change-Id: I03faaf863d0034a45dde318b877c02e7e4acb00a
|
package oasis.services.authn;
import javax.inject.Inject;
import oasis.model.authn.ClientType;
import oasis.model.authn.Credentials;
import oasis.model.authn.CredentialsRepository;
import oasis.services.authn.login.PasswordHasher;
import oasis.services.authn.login.SCryptPasswordHasher;
public class CredentialsService {
private final CredentialsRepository credentialsRepository;
private final PasswordHasher passwordHasher;
@Inject
CredentialsService(CredentialsRepository credentialsRepository, SCryptPasswordHasher passwordHasher) {
this.credentialsRepository = credentialsRepository;
this.passwordHasher = passwordHasher;
}
public void setPassword(ClientType type, String id, String password) {
byte[] salt = passwordHasher.createSalt();
byte[] hash = passwordHasher.hashPassword(password, salt);
credentialsRepository.saveCredentials(type, id, hash, salt);
}
public boolean checkPassword(ClientType type, String id, String password) {
Credentials credentials = credentialsRepository.getCredentials(type, id);
if (credentials == null) {
return false;
}
return passwordHasher.checkPassword(password, credentials.getHash(), credentials.getSalt());
}
}
|
package oasis.services.authn;
import javax.inject.Inject;
import oasis.model.authn.ClientType;
import oasis.model.authn.Credentials;
import oasis.model.authn.CredentialsRepository;
import oasis.services.authn.login.PasswordHasher;
import oasis.services.authn.login.SShaPasswordHasher;
public class CredentialsService {
private final CredentialsRepository credentialsRepository;
private final PasswordHasher passwordHasher;
@Inject
CredentialsService(CredentialsRepository credentialsRepository, SShaPasswordHasher passwordHasher) {
this.credentialsRepository = credentialsRepository;
this.passwordHasher = passwordHasher;
}
public void setPassword(ClientType type, String id, String password) {
byte[] salt = passwordHasher.createSalt();
byte[] hash = passwordHasher.hashPassword(password, salt);
credentialsRepository.saveCredentials(type, id, hash, salt);
}
public boolean checkPassword(ClientType type, String id, String password) {
Credentials credentials = credentialsRepository.getCredentials(type, id);
if (credentials == null) {
return false;
}
return passwordHasher.checkPassword(password, credentials.getHash(), credentials.getSalt());
}
}
|
Change click event to change event
|
var settings = {
api_url: "http://127.0.0.1:8000/api/",
agency_id: "SPTRANS"
};
start();
function start(){
var api_url = settings.api_url;
var agency_id = settings.agency_id;
var url = "";
url = api_url + "agency?agency_id=" + agency_id;
getApi(url, Generator.drawAgencyStop);
url = api_url + "routes?agency_id=" + agency_id;
getApi(url, Generator.drawRoutes);
}
$("#rotas").change(function() {
drawSelectedRoute();
});
function drawSelectedRoute() {
var api_url = settings.api_url;
var agency_id = settings.agency_id;
var route_id = $("#rotas option:selected").val();
var direction_id = "0";
var url = "";
map.removeLayer(markers);
markers = new L.FeatureGroup();
url = api_url + "shapes?agency_key=" + agency_id + "&route_id=" + route_id + "&direction_id=" + direction_id;
getApi(url, Generator.drawShapes);
url = api_url + "stops?agency_key=" + agency_id + "&route_id=" + route_id + "&direction_id=" + direction_id;
getApi(url, Generator.drawStops);
}
|
var settings = {
api_url: "http://127.0.0.1:8000/api/",
agency_id: "SPTRANS"
};
start();
function start(){
var api_url = settings.api_url;
var agency_id = settings.agency_id;
var url = "";
url = api_url + "agency?agency_id=" + agency_id;
getApi(url, Generator.drawAgencyStop);
url = api_url + "routes?agency_id=" + agency_id;
getApi(url, Generator.drawRoutes);
}
$("#rotas").click(function() {
drawSelectedRoute();
});
function drawSelectedRoute() {
var api_url = settings.api_url;
var agency_id = settings.agency_id;
var route_id = $("#rotas option:selected").val();
var direction_id = "0";
var url = "";
map.removeLayer(markers);
markers = new L.FeatureGroup();
url = api_url + "shapes?agency_key=" + agency_id + "&route_id=" + route_id + "&direction_id=" + direction_id;
getApi(url, Generator.drawShapes);
url = api_url + "stops?agency_key=" + agency_id + "&route_id=" + route_id + "&direction_id=" + direction_id;
getApi(url, Generator.drawStops);
}
|
[SMALLFIX] Use static imports for standard test utilities
Change
`import org.junit.Assert;`
to
`import static org.junit.Assert.assertEquals;`
AND
Update all
`Assert.{{ method }}*`
to
`{{ method }}*`
pr-link: Alluxio/alluxio#8697
change-id: cid-80367e58e882e7d64d77c0040a4faf3cf3f1d84d
|
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.util;
import static org.junit.Assert.assertEquals;
import alluxio.test.util.CommonUtils;
import org.junit.Test;
import java.util.Random;
public final class WaitForOptionsTest {
@Test
public void defaults() {
WaitForOptions options = WaitForOptions.defaults();
assertEquals(WaitForOptions.DEFAULT_INTERVAL, options.getInterval());
assertEquals(WaitForOptions.NEVER, options.getTimeoutMs());
}
/**
* Tests getting and setting fields.
*/
@Test
public void fields() {
Random random = new Random();
int interval = random.nextInt();
int timeout = random.nextInt();
WaitForOptions options = WaitForOptions.defaults();
options.setInterval(interval);
options.setTimeoutMs(timeout);
assertEquals(interval, options.getInterval());
assertEquals(timeout, options.getTimeoutMs());
}
@Test
public void equalsTest() throws Exception {
CommonUtils.testEquals(WaitForOptions.class);
}
}
|
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.util;
import alluxio.test.util.CommonUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.Random;
public final class WaitForOptionsTest {
@Test
public void defaults() {
WaitForOptions options = WaitForOptions.defaults();
Assert.assertEquals(WaitForOptions.DEFAULT_INTERVAL, options.getInterval());
Assert.assertEquals(WaitForOptions.NEVER, options.getTimeoutMs());
}
/**
* Tests getting and setting fields.
*/
@Test
public void fields() {
Random random = new Random();
int interval = random.nextInt();
int timeout = random.nextInt();
WaitForOptions options = WaitForOptions.defaults();
options.setInterval(interval);
options.setTimeoutMs(timeout);
Assert.assertEquals(interval, options.getInterval());
Assert.assertEquals(timeout, options.getTimeoutMs());
}
@Test
public void equalsTest() throws Exception {
CommonUtils.testEquals(WaitForOptions.class);
}
}
|
Rename env var to PUSHOVER_TOKEN
|
exports.name = 'task.pushover';
exports.version = '1.0.0';
exports.register = function(plugin, options, next) {
var app = plugin.app;
var request = app.service.request;
var url = 'https://api.pushover.net/1/messages.json';
function run(job, done) {
var params = {
method: 'POST',
url: url,
json: true,
body: {
token: app.config.get('/env/PUSHOVER_TOKEN'),
user: 'Doorbell',
title: 'Doorbell - Side Gate',
message: 'Ring! Ring! Ring!',
priority: 1
}
};
request(params, function(err, res, body) {
if(err) return done(err);
return done();
});
}
app.task.define('Notify Pushover', options || {}, run);
next();
};
|
exports.name = 'task.pushover';
exports.version = '1.0.0';
exports.register = function(plugin, options, next) {
var app = plugin.app;
var request = app.service.request;
var url = 'https://api.pushover.net/1/messages.json';
function run(job, done) {
var params = {
method: 'POST',
url: url,
json: true,
body: {
token: app.config.get('/env/pushoverToken'),
user: 'Doorbell',
title: 'Doorbell - Side Gate',
message: 'Ring! Ring! Ring!',
priority: 1
}
};
request(params, function(err, res, body) {
if(err) return done(err);
return done();
});
}
app.task.define('Notify Pushover', options || {}, run);
next();
};
|
Add child(); TODO: test this
|
class DataModelAdapter(object) :
def __init__(self, data) :
self._data = data
self._children = set()
self._parent = None
pass
def numChildren(self) :
return len(self._children)
def hasData(self) :
return self._data is not None
def getData(self, key) :
if key in self._data :
return self._data[key]
return None
def addChild(self, child) :
child.setParent(self)
self._children.add(child)
def child(self, row) :
children_list = [c for c in self._children]
return children_list[row]
def setParent(self, parent) :
self._parent = parent
def parent(self) :
return self._parent
|
class DataModelAdapter(object) :
def __init__(self, data) :
self._data = data
self._children = set()
self._parent = None
pass
def numChildren(self) :
return len(self._children)
def hasData(self) :
return self._data is not None
def getData(self, key) :
if key in self._data :
return self._data[key]
return None
def addChild(self, child) :
child.setParent(self)
self._children.add(child)
def setParent(self, parent) :
self._parent = parent
def parent(self) :
return self._parent
|
Use the Charset constants in the JDK's StandardCharsets class instead of c.g.c.base.Charsets. The c.g.common.base.Charsets is scheduled for deletion.
More information: []
Tested:
TAP train for global presubmit queue
[] Some tests failed; test failures are believed to be unrelated to this CL
Change on 2015/01/30 by kak <kak@google.com>
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=85186588
|
// Copyright 2011 The MOE Authors All Rights Reserved.
package com.google.devtools.moe.client.project;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
/**
*
* @author dbentley@google.com (Daniel Bentley)
*/
public class FileReadingProjectContextFactory implements ProjectContextFactory {
@Inject Ui ui;
public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
String configText;
Ui.Task task = ui.pushTask(
"read_config",
String.format("Reading config file from %s", configFilename));
try {
try {
configText = Files.toString(new File(configFilename), UTF_8);
} catch (IOException e) {
throw new InvalidProject(
"Config File \"" + configFilename + "\" not accessible.");
}
return ProjectContext.makeProjectContextFromConfigText(configText);
} finally {
ui.popTask(task, "");
}
}
}
|
// Copyright 2011 The MOE Authors All Rights Reserved.
package com.google.devtools.moe.client.project;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
/**
*
* @author dbentley@google.com (Daniel Bentley)
*/
public class FileReadingProjectContextFactory implements ProjectContextFactory {
@Inject Ui ui;
public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
String configText;
Ui.Task task = ui.pushTask(
"read_config",
String.format("Reading config file from %s", configFilename));
try {
try {
configText = Files.toString(new File(configFilename), Charsets.UTF_8);
} catch (IOException e) {
throw new InvalidProject(
"Config File \"" + configFilename + "\" not accessible.");
}
return ProjectContext.makeProjectContextFromConfigText(configText);
} finally {
ui.popTask(task, "");
}
}
}
|
Add a line that was removed by mistake
|
#!/usr/bin/env python3
"""
Main entry point to run all tests
"""
import sys
from pathlib import Path
from unittest import TestLoader, TestSuite, TextTestRunner
PATH = Path(__file__).absolute()
sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix())
sys.path.append(PATH.parents[1].as_posix())
try:
from test_enums import TestEnumsProducer
from test_functions import TestFunctionsProducer
from test_structs import TestStructsProducer
from test_code_format_and_quality import CodeFormatAndQuality
except ImportError as message:
print('{}. probably you did not initialize submodule'.format(message))
sys.exit(1)
def main():
"""
Main entry point to run all tests
"""
suite = TestSuite()
suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality))
runner = TextTestRunner(verbosity=2)
ret = not runner.run(suite).wasSuccessful()
sys.exit(ret)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
"""
Main entry point to run all tests
"""
import sys
from pathlib import Path
from unittest import TestLoader, TestSuite, TextTestRunner
PATH = Path(__file__).absolute()
sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix())
sys.path.append(PATH.parents[1].as_posix())
try:
from test_enums import TestEnumsProducer
from test_functions import TestFunctionsProducer
from test_structs import TestStructsProducer
from test_code_format_and_quality import CodeFormatAndQuality
except ImportError as message:
print('{}. probably you did not initialize submodule'.format(message))
sys.exit(1)
def main():
"""
Main entry point to run all tests
"""
suite = TestSuite()
suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer))
suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality))
ret = not runner.run(suite).wasSuccessful()
sys.exit(ret)
if __name__ == '__main__':
main()
|
Add flash messages to the response
|
<?php
/**
* jsonAPI - Slim extension to implement fast JSON API's
*
* @package Slim
* @subpackage View
* @author Jonathan Tavares <the.entomb@gmail.com>
* @license GNU General Public License, version 3
* @filesource
*
*
*/
/**
* JsonApiView - view wrapper for json responses (with error code).
*
* @package Slim
* @subpackage View
* @author Jonathan Tavares <the.entomb@gmail.com>
* @license GNU General Public License, version 3
* @filesource
*/
class JsonApiView extends \Slim\View {
public function render($status=200) {
$app = \Slim\Slim::getInstance();
$status = intval($status);
$response = $this->all();
//append error bool
if (!$this->has('error')) {
$response['error'] = false;
}
//append status code
$response['status'] = $status;
//add flash messages
$response['flash'] = $this->data->flash->getMessages();
$app->response()->status($status);
$app->response()->header('Content-Type', 'application/json');
$app->response()->body(json_encode($response));
$app->stop();
}
}
|
<?php
/**
* jsonAPI - Slim extension to implement fast JSON API's
*
* @package Slim
* @subpackage View
* @author Jonathan Tavares <the.entomb@gmail.com>
* @license GNU General Public License, version 3
* @filesource
*
*
*/
/**
* JsonApiView - view wrapper for json responses (with error code).
*
* @package Slim
* @subpackage View
* @author Jonathan Tavares <the.entomb@gmail.com>
* @license GNU General Public License, version 3
* @filesource
*/
class JsonApiView extends \Slim\View {
public function render($status=200) {
$app = \Slim\Slim::getInstance();
$status = intval($status);
//append error bool
if (!$this->has('error')) {
$this->set('error', false);
}
//append status code
$this->set('status', $status);
$app->response()->status($status);
$app->response()->header('Content-Type', 'application/json');
$app->response()->body(json_encode($this->all()));
$app->stop();
}
}
|
Fix for child process running
|
import { resolve } from 'path'
import { node } from 'execa'
const childProcessHelperPath = resolve(__dirname, 'childProcessHelper.js')
export default class ChildProcessRunner {
#env = null
#functionKey = null
#handlerName = null
#handlerPath = null
#timeout = null
constructor(funOptions, env) {
const { functionKey, handlerName, handlerPath, timeout } = funOptions
this.#env = env
this.#functionKey = functionKey
this.#handlerName = handlerName
this.#handlerPath = handlerPath
this.#timeout = timeout
}
// no-op
// () => void
cleanup() {}
async run(event, context) {
const childProcess = node(
childProcessHelperPath,
[this.#functionKey, this.#handlerName, this.#handlerPath],
{
env: this.#env,
stdio: 'inherit',
},
)
childProcess.send({
context,
event,
timeout: this.#timeout,
})
const message = new Promise((_resolve) => {
childProcess.on('message', _resolve)
// TODO
// on error? on exit? ..
})
let result
try {
result = await message
} catch (err) {
// TODO
console.log(err)
throw err
}
return result
}
}
|
import { resolve } from 'path'
import { node } from 'execa'
const childProcessHelperPath = resolve(__dirname, 'childProcessHelper.js')
export default class ChildProcessRunner {
#env = null
#functionKey = null
#handlerName = null
#handlerPath = null
#timeout = null
constructor(funOptions, env) {
const { functionKey, handlerName, handlerPath, timeout } = funOptions
this.#env = env
this.#functionKey = functionKey
this.#handlerName = handlerName
this.#handlerPath = handlerPath
this.#timeout = timeout
}
// no-op
// () => void
cleanup() {}
async run(event, context) {
const childProcess = node(
childProcessHelperPath,
[this.#functionKey, this.#handlerName, this.#handlerPath],
{
env: this.#env,
},
)
childProcess.send({
context,
event,
timeout: this.#timeout,
})
const message = new Promise((_resolve) => {
childProcess.on('message', _resolve)
// TODO
// on error? on exit? ..
})
let result
try {
result = await message
} catch (err) {
// TODO
console.log(err)
throw err
}
return result
}
}
|
Use 'wraps' from 'functools', to keep wrapped function's docstring, name and attributes.
|
# -*- coding:utf-8 -*-
'''
Decorators for using specific routing state for particular requests.
Used in cases when automatic switching based on request method doesn't
work.
Usage:
from django_replicated.decorators import use_master, use_slave
@use_master
def my_view(request, ...):
# master database used for all db operations during
# execution of the view (if not explicitly overriden).
@use_slave
def my_view(request, ...):
# same with slave connection
'''
import utils
from functools import wraps
def _use_state(state):
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
current_state = utils.check_state_override(request, state)
utils._use_state(current_state)
try:
response = func(request, *args, **kwargs)
finally:
utils._revert()
utils.handle_updated_redirect(request, response)
return response
return wrapper
return decorator
use_master = _use_state('master')
use_slave = _use_state('slave')
|
# -*- coding:utf-8 -*-
'''
Decorators for using specific routing state for particular requests.
Used in cases when automatic switching based on request method doesn't
work.
Usage:
from django_replicated.decorators import use_master, use_slave
@use_master
def my_view(request, ...):
# master database used for all db operations during
# execution of the view (if not explicitly overriden).
@use_slave
def my_view(request, ...):
# same with slave connection
'''
import utils
def _use_state(state):
def decorator(func):
def wrapper(request, *args, **kwargs):
current_state = utils.check_state_override(request, state)
utils._use_state(current_state)
try:
response = func(request, *args, **kwargs)
finally:
utils._revert()
utils.handle_updated_redirect(request, response)
return response
return wrapper
return decorator
use_master = _use_state('master')
use_slave = _use_state('slave')
|
Add new configuration setting for log_directory
|
# General Settings
timerestriction = False
debug_mode = True
log_directory = './logs'
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Services Auth
basic_auth = 'basic auth header here'
spsms_host = 'host here'
spsms_url = 'url here'
# Postgres Connection Details
pg_host = 'localhost'
pg_dbname = 'blockbuster'
pg_user = 'blockbuster'
pg_passwd = 'blockbuster'
# Proxy Details
proxy_user = ''
proxy_pass = ''
proxy_host = ''
proxy_port = 8080
# Testing
test_to_number = ''
test_from_number = ''
# Pushover Keys
pushover_app_token = "pushover_token"
# Email Configuration
smtp_server = 'smtp.gmail.com:587'
mail_username = ''
mail_fromaddr = mail_username
mail_password = ''
mail_monitoring_addr = ''
# API Variables
api_username = "username here"
api_passphrase = "passphrase here"
# New Number
return_number = "+440000111222"
|
# General Settings
timerestriction = False
debug_mode = True
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Services Auth
basic_auth = 'basic auth header here'
spsms_host = 'host here'
spsms_url = 'url here'
# Postgres Connection Details
pg_host = 'localhost'
pg_dbname = 'blockbuster'
pg_user = 'blockbuster'
pg_passwd = 'blockbuster'
# Proxy Details
proxy_user = ''
proxy_pass = ''
proxy_host = ''
proxy_port = 8080
# Testing
test_to_number = ''
test_from_number = ''
# Pushover Keys
pushover_app_token = "pushover_token"
# Email Configuration
smtp_server = 'smtp.gmail.com:587'
mail_username = ''
mail_fromaddr = mail_username
mail_password = ''
# API Variables
api_username = "username here"
api_passphrase = "passphrase here"
# New Number
return_number = "+440000111222"
|
MNT: Add explicit test for deprecation decorator
|
# Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test MetPy's testing utilities."""
import warnings
import numpy as np
import pytest
from metpy.deprecation import MetpyDeprecationWarning
from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
@check_and_silence_deprecation
def test_deprecation_decorator():
"""Make sure the deprecation checker works."""
warnings.warn('Testing warning.', MetpyDeprecationWarning)
|
# Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test MetPy's testing utilities."""
import numpy as np
import pytest
from metpy.testing import assert_array_almost_equal
# Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around
def test_masked_arrays():
"""Test that we catch masked arrays with different masks."""
with pytest.raises(AssertionError):
assert_array_almost_equal(np.array([10, 20]),
np.ma.array([10, np.nan], mask=[False, True]), 2)
def test_masked_and_no_mask():
"""Test that we can compare a masked array with no masked values and a regular array."""
a = np.array([10, 20])
b = np.ma.array([10, 20], mask=[False, False])
assert_array_almost_equal(a, b)
|
Use low root margin to prevent premature loading of images
|
import mediumZoom from 'src/config/medium-zoom';
import lqip from 'src/modules/lqip';
import galleryLoader from 'src/modules/gallery-lazy-load';
window.addEventListener('DOMContentLoaded', () => {
galleryLoader({
afterInsert(lastPost) {
lqip({
selectorRoot: lastPost,
rootMargin: '0px',
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
})
},
});
lqip({
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
});
});
|
import mediumZoom from 'src/config/medium-zoom';
import lqip from 'src/modules/lqip';
import galleryLoader from 'src/modules/gallery-lazy-load';
window.addEventListener('DOMContentLoaded', () => {
galleryLoader({
afterInsert(lastPost) {
lqip({
selectorRoot: lastPost,
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
})
},
});
lqip({
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
});
});
|
Include skip-link-focus-fix.js in bundled js.
|
// 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
//= require jquery_ujs
//= require 'jquery-readyselector'
//= require select2
//= require 'polyfills'
//= require 'lib/requests'
//= require 'lib/ui/skip-link-focus-fix'
//= require 'lib/ui/content'
//= require 'lib/ui/filter-selectize'
//= require 'lib/ckeditor'
//= require old_tree/fonts
//= require old_tree/ui
//= require export
//= require_tree ./old_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
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require 'jquery-readyselector'
//= require select2
//= require 'polyfills'
//= require 'lib/requests'
//= require 'lib/ui/content'
//= require 'lib/ui/filter-selectize'
//= require 'lib/ckeditor'
//= require old_tree/fonts
//= require old_tree/ui
//= require export
//= require_tree ./old_tree
|
Add API for handler that know the SDocumentGraph of the editor
|
/**
*
*/
package org.corpus_tools.atomic.api.commands;
import org.corpus_tools.atomic.api.editors.DocumentGraphEditor;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
/**
* TODO Description
*
* @author Stephan Druskat <mail@sdruskat.net>
*
*/
public abstract class DocumentGraphAwareHandler extends AbstractHandler {
private final SDocumentGraph graph;
/**
*
*/
public DocumentGraphAwareHandler() {
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (editor instanceof DocumentGraphEditor) {
graph = ((DocumentGraphEditor) editor).getGraph();
}
else {
graph = null;
}
}
/**
* @return the graph
*/
public final SDocumentGraph getGraph() {
return graph;
}
}
|
/**
*
*/
package org.corpus_tools.atomic.api.commands;
import org.corpus_tools.atomic.api.editors.DocumentGraphEditor;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
/**
* TODO Description
*
* @author Stephan Druskat <mail@sdruskat.net>
*
*/
public class DocumentGraphAwareHandler extends AbstractHandler {
private final SDocumentGraph graph;
/**
*
*/
public DocumentGraphAwareHandler() {
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (editor instanceof DocumentGraphEditor) {
graph = ((DocumentGraphEditor) editor).getGraph();
}
else {
graph = null;
}
}
/* (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// TODO Auto-generated method stub
return null;
}
/**
* @return the graph
*/
public final SDocumentGraph getGraph() {
return graph;
}
}
|
Allow irregular whitespaces in string or comment
|
module.exports = {
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
},
},
"rules": {
"arrow-parens": "warn",
"comma-dangle": ["error", "always-multiline"],
"max-len": ["error", {
"code": 100,
"ignoreUrls": true,
"ignoreRegExpLiterals": true,
"tabWidth": 2,
}],
"no-irregular-whitespace": ["error", {
"skipStrings": true,
"skipComments": true,
"skipRegExps": true,
"skipTemplates": true,
}],
"no-plusplus": ["error", {
"allowForLoopAfterthoughts": true,
}],
"no-prototype-builtins": "off",
"no-underscore-dangle": "off",
"quotes": ["error", "double", {
"avoidEscape": true,
}],
"semi": ["error", "never"],
"import/no-unresolved": "off",
},
}
|
module.exports = {
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
},
},
"rules": {
"arrow-parens": "warn",
"comma-dangle": ["error", "always-multiline"],
"max-len": ["error", {
"code": 100,
"ignoreUrls": true,
"ignoreRegExpLiterals": true,
"tabWidth": 2,
}],
"no-plusplus": ["error", {
"allowForLoopAfterthoughts": true,
}],
"no-prototype-builtins": "off",
"no-underscore-dangle": "off",
"quotes": ["error", "double", {
"avoidEscape": true,
}],
"semi": ["error", "never"],
"import/no-unresolved": "off",
},
}
|
Improve the speed of csv export file generation
|
import sys
import csv
from optparse import make_option
from django.core.management.base import BaseCommand
from modoboa.core import load_core_settings
from modoboa.core.models import User
from modoboa.core.extensions import exts_pool
from modoboa.core.management.commands import CloseConnectionMixin
from ...models import Alias
class Command(BaseCommand, CloseConnectionMixin):
help = 'Export identities (mailbox and aliases) to a csv'
option_list = BaseCommand.option_list + (
make_option(
'--sepchar', action='store_true', dest='sepchar', default=';'
),
)
def handle(self, *args, **kwargs):
exts_pool.load_all()
load_core_settings()
csvwriter = csv.writer(sys.stdout, delimiter=kwargs['sepchar'])
for u in User.objects.all():
u.to_csv(csvwriter)
for a in Alias.objects.prefetch_related('mboxes', 'aliases'):
a.to_csv(csvwriter)
|
import sys
import csv
from optparse import make_option
from django.core.management.base import BaseCommand
from modoboa.core import load_core_settings
from modoboa.core.models import User
from modoboa.core.extensions import exts_pool
from modoboa.core.management.commands import CloseConnectionMixin
from ...models import Alias
class Command(BaseCommand, CloseConnectionMixin):
help = 'Export identities (mailbox and aliases) to a csv'
option_list = BaseCommand.option_list + (
make_option(
'--sepchar', action='store_true', dest='sepchar', default=';'
),
)
def handle(self, *args, **kwargs):
exts_pool.load_all()
load_core_settings()
csvwriter = csv.writer(sys.stdout, delimiter=kwargs['sepchar'])
for u in User.objects.all():
u.to_csv(csvwriter)
for a in Alias.objects.all():
a.to_csv(csvwriter)
|
Modify example server request params
|
'use strict';
const express = require('express');
const MsgQueueClient = require('msgqueue-client');
const mqServerConfig = require('../common/config/mqserver.js');
const config = require('./config.js');
const app = express();
const mq = new MsgQueueClient(`${mqServerConfig.url}:${mqServerConfig.port}`, { log: true });
mq.on('connected', () => { console.log('connected to mq'); });
app.set('port', config.port);
// curl 'http://localhost:65000/images?task=img_verification&num=200&concept=porsche&query=porsche'
// curl 'http://localhost:65000/images?task=img_verification&num=200&concept=porsche&query=porsche+macan'
app.get('/images', (req, res) => {
console.log('GET on /images');
if (req.query.num > 1000) res.status(400).send('Can only query for up to 1000 images currently.');
let nQ = 'ctrl_sns_img_scrape_req';
mq.enqueue(nQ, req.query); // query, num, task (optional)
res.status(200).send('images');
});
app.listen(app.get('port'), () => {
console.log('api-server is listening on port', app.get('port'));
});
module.exports = app;
|
'use strict';
const express = require('express');
const MsgQueueClient = require('msgqueue-client');
const mqServerConfig = require('../common/config/mqserver.js');
const config = require('./config.js');
const app = express();
const mq = new MsgQueueClient(`${mqServerConfig.url}:${mqServerConfig.port}`, { log: true });
mq.on('connected', () => { console.log('connected to mq'); });
app.set('port', config.port);
// curl 'http://localhost:65000/images?query=porsche&concept=porsche&num=200&task=img_verification'
// curl 'http://localhost:65000/images?query=porsche+macan&concept=porsche&num=12&task=img_verification'
app.get('/images', (req, res) => {
console.log('GET on /images');
if (req.query.num > 1000) res.status(400).send('Can only query for up to 1000 images currently.');
let nQ = 'ctrl_sns_img_scrape_req';
mq.enqueue(nQ, req.query); // query, num, task (optional)
res.status(200).send('images');
});
app.listen(app.get('port'), () => {
console.log('api-server is listening on port', app.get('port'));
});
module.exports = app;
|
Set preferBuiltins to silence a rollup warning.
|
const fs = require('fs');
const pathModule = require('path');
const plugins = [
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
require('rollup-plugin-commonjs')({
// leave the os require in the tree as that codepath is not
// taken when executed in Deno after magicpen porting work
ignore: process.env.ESM_BUILD ? ['os'] : undefined
}),
require('rollup-plugin-node-resolve')({ preferBuiltins: true }),
require('rollup-plugin-node-globals')(),
require('rollup-plugin-terser').terser({
output: {
comments: function(node, comment) {
return /^!|@preserve|@license|@cc_on/i.test(comment.value);
}
}
})
];
module.exports = {
output: {
banner:
'/*!\n' +
fs
.readFileSync(pathModule.resolve(__dirname, 'LICENSE'), 'utf-8')
.replace(/^/gm, ' * ')
.replace(/\s+$/g, '') +
'/\n'
},
plugins
};
|
const fs = require('fs');
const pathModule = require('path');
const plugins = [
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
require('rollup-plugin-commonjs')({
// leave the os require in the tree as that codepath is not
// taken when executed in Deno after magicpen porting work
ignore: process.env.ESM_BUILD ? ['os'] : undefined
}),
require('rollup-plugin-node-resolve')(),
require('rollup-plugin-node-globals')(),
require('rollup-plugin-terser').terser({
output: {
comments: function(node, comment) {
return /^!|@preserve|@license|@cc_on/i.test(comment.value);
}
}
})
];
module.exports = {
output: {
banner:
'/*!\n' +
fs
.readFileSync(pathModule.resolve(__dirname, 'LICENSE'), 'utf-8')
.replace(/^/gm, ' * ')
.replace(/\s+$/g, '') +
'/\n'
},
plugins
};
|
Fix sql error in migration
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20121107231047 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE team ADD ownerId INT DEFAULT NULL, DROP owner");
$this->addSql("ALTER TABLE `team`
ADD CONSTRAINT `FK_C4E0A61FE05EFD25`
FOREIGN KEY (`ownerId` )
REFERENCES `user` (`userId` );
");
$this->addSql("CREATE INDEX IDX_C4E0A61FE05EFD25 ON team (ownerId)");
}
public function down(Schema $schema)
{
// this down() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE team DROP FOREIGN KEY FK_C4E0A61FE05EFD25");
$this->addSql("DROP INDEX IDX_C4E0A61FE05EFD25 ON team");
$this->addSql("ALTER TABLE team ADD owner INT NOT NULL, DROP ownerId");
}
}
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration,
Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your need!
*/
class Version20121107231047 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE team ADD ownerId INT DEFAULT NULL, DROP owner");
$this->addSql("ALTER TABLE `team`
ADD CONSTRAINT `FK_C4E0A61FE05EFD25`
FOREIGN KEY (`ownerId` )
REFERENCES ``user` (`userId` );
");
$this->addSql("CREATE INDEX IDX_C4E0A61FE05EFD25 ON team (ownerId)");
}
public function down(Schema $schema)
{
// this down() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
$this->addSql("ALTER TABLE team DROP FOREIGN KEY FK_C4E0A61FE05EFD25");
$this->addSql("DROP INDEX IDX_C4E0A61FE05EFD25 ON team");
$this->addSql("ALTER TABLE team ADD owner INT NOT NULL, DROP ownerId");
}
}
|
Set Factory.noisy to False by default
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@3933 e27351fd-9f3e-4f54-a53b-843176b1656c
|
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
from twisted.internet.protocol import Factory
Factory.noisy = False
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
Remove explicit unboxing to primitive
|
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.operation.projectors;
import io.crate.core.collections.Row;
import io.crate.core.collections.Row1;
public class MergeCountProjector extends AbstractProjector {
private long sum;
@Override
public boolean setNextRow(Row row) {
Long count = (Long)row.get(0);
sum += count;
return true;
}
@Override
public void finish() {
downstream.setNextRow(new Row1(sum));
downstream.finish();
}
@Override
public void fail(Throwable throwable) {
downstream.fail(throwable);
}
}
|
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.operation.projectors;
import io.crate.core.collections.Row;
import io.crate.core.collections.Row1;
public class MergeCountProjector extends AbstractProjector {
private long sum;
@Override
public boolean setNextRow(Row row) {
Long count = (Long)row.get(0);
sum += count.longValue();
return true;
}
@Override
public void finish() {
downstream.setNextRow(new Row1(sum));
downstream.finish();
}
@Override
public void fail(Throwable throwable) {
downstream.fail(throwable);
}
}
|
Put the category tabs on the left and scroll them if they are too many.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@907 6335cc39-0255-0410-8fd6-9bcaacd3b74c
|
//
// $Id: BrowsePanel.java,v 1.3 2002/11/11 17:04:12 mdb Exp $
package robodj.chooser;
import javax.swing.*;
import robodj.repository.*;
public class BrowsePanel extends JTabbedPane
{
public BrowsePanel ()
{
EntryList elist;
Category[] cats = Chooser.model.getCategories();
// stick our tabs along the side and scroll if they don't fit
setTabPlacement(LEFT);
setTabLayoutPolicy(SCROLL_TAB_LAYOUT);
// create a tab for each category
for (int i = 0; i < cats.length; i++) {
elist = new CategoryEntryList(cats[i].categoryid);
String tip = "Browse entries in '" + cats[i].name + "' category.";
addTab(cats[i].name, null, elist, tip);
}
// and add one for uncategorized entries
elist = new CategoryEntryList(-1);
addTab("Uncategorized", null, elist,
"Browse uncategorized entries.");
setSelectedIndex(0);
}
}
|
//
// $Id: BrowsePanel.java,v 1.2 2002/02/22 07:06:33 mdb Exp $
package robodj.chooser;
import javax.swing.*;
import robodj.repository.*;
public class BrowsePanel extends JTabbedPane
{
public BrowsePanel ()
{
EntryList elist;
Category[] cats = Chooser.model.getCategories();
// create a tab for each category
for (int i = 0; i < cats.length; i++) {
elist = new CategoryEntryList(cats[i].categoryid);
String tip = "Browse entries in '" + cats[i].name + "' category.";
addTab(cats[i].name, null, elist, tip);
}
// and add one for uncategorized entries
elist = new CategoryEntryList(-1);
addTab("Uncategorized", null, elist,
"Browse uncategorized entries.");
setSelectedIndex(0);
}
}
|
Add matches method to AndRule class.
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
|
Add logging to see if model is being correctly loaded
|
package sk.sodik.sample.wro4jBoot;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.manager.factory.ConfigurableWroManagerFactory;
import ro.isdc.wro.model.factory.WroModelFactory;
import ro.isdc.wro.model.factory.XmlModelFactory;
public class Wro4jCustomXmlModelManagerFactory extends
ConfigurableWroManagerFactory {
private static final Logger log = LoggerFactory
.getLogger(Wro4jCustomXmlModelManagerFactory.class);
final private Properties props;
public Wro4jCustomXmlModelManagerFactory(Properties props) {
this.props = props;
}
@Override
protected Properties newConfigProperties() {
return props;
}
@Override
protected WroModelFactory newModelFactory() {
log.debug("loading from /wro.xml");
return new XmlModelFactory() {
@Override
protected InputStream getModelResourceAsStream() throws IOException {
String resourceLocation = "/wro.xml";
log.info("Loading resource {}", resourceLocation);
final InputStream stream = getClass().getResourceAsStream(
resourceLocation);
if (stream == null) {
throw new IOException("Invalid resource requested: "
+ resourceLocation);
}
return stream;
}
};
}
}
|
package sk.sodik.sample.wro4jBoot;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.manager.factory.ConfigurableWroManagerFactory;
import ro.isdc.wro.model.factory.WroModelFactory;
import ro.isdc.wro.model.factory.XmlModelFactory;
public class Wro4jCustomXmlModelManagerFactory extends
ConfigurableWroManagerFactory {
private static final Logger log = LoggerFactory
.getLogger(Wro4jCustomXmlModelManagerFactory.class);
final private Properties props;
public Wro4jCustomXmlModelManagerFactory(Properties props) {
this.props = props;
}
@Override
protected Properties newConfigProperties() {
return props;
}
@Override
protected WroModelFactory newModelFactory() {
log.debug("loading from /wro.xml");
return new XmlModelFactory() {
@Override
protected InputStream getModelResourceAsStream() throws IOException {
String resourceLocation = "/wro.xml";
final InputStream stream = getClass().getResourceAsStream(
resourceLocation);
if (stream == null) {
throw new IOException("Invalid resource requested: "
+ resourceLocation);
}
return stream;
}
};
}
}
|
Change license info to show name of license, not license text.
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = ['magento']
requires = []
setup(
name='python-magento',
version='0.2.1',
author='Vikram Oberoi',
author_email='voberoi@gmail.com',
packages=['magento'],
install_requires=requires,
entry_points={
'console_scripts': [
'magento-ipython-shell = magento.magento_ipython_shell:main'
]
},
url='https://github.com/voberoi/python-magento',
license="MIT License",
description='A Python wrapper to Magento\'s XML-RPC API.',
long_description=open('README.rst').read(),
classifiers=(
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
)
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = ['magento']
requires = []
setup(
name='python-magento',
version='0.2.1',
author='Vikram Oberoi',
author_email='voberoi@gmail.com',
packages=['magento'],
install_requires=requires,
entry_points={
'console_scripts': [
'magento-ipython-shell = magento.magento_ipython_shell:main'
]
},
url='https://github.com/voberoi/python-magento',
license=open('LICENSE.md').read(),
description='A Python wrapper to Magento\'s XML-RPC API.',
long_description=open('README.rst').read(),
classifiers=(
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
)
)
|
Send HTTP code when cron is too much executed
|
<?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / Include / Class
*/
namespace PH7;
class Cron extends Framework\Cron\Run\Cron
{
public function __construct()
{
parent::__construct();
// Check delay
$this->isAlreadyExec();
}
/**
* Check if the cron has already been executed.
*
* @return void If cron has already been executed, the script stops with exit() function and an explanatory message.
*/
public function isAlreadyExec()
{
if (!$this->checkDelay()) {
Framework\Http\Http::setHeadersByCode(403);
exit(t('This cron has already been executed.'));
}
}
}
|
<?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / Include / Class
*/
namespace PH7;
class Cron extends Framework\Cron\Run\Cron
{
public function __construct()
{
parent::__construct();
// Check delay
$this->isAlreadyExec();
}
/**
* Check if the cron has already been executed.
*
* @return void If cron has already been executed, the script stops with exit() function and an explanatory message.
*/
public function isAlreadyExec()
{
if (!$this->checkDelay())
exit(t('This cron has already been executed.'));
}
}
|
Fix Use % formatting in logging functions
|
import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import settings as app_settings
for setting in dir(app_settings):
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
LOGGER.info("Settings '%s' as the default ('%s')", setting, getattr(settings, setting))
except ImportError:
pass
set_default_settings()
|
import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import settings as app_settings
for setting in dir(app_settings):
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
LOGGER.info("Settings '{}' as the default ('{}')".format(setting, getattr(settings, setting)))
except ImportError:
pass
set_default_settings()
|
Fix docstring for module (minor)
|
# No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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.
"""
GPU
---
Model describing a given make and model of graphics card.
Every agent can have zero or more GPUs associated with it.
"""
from sqlalchemy.schema import UniqueConstraint
from pyfarm.master.application import db
from pyfarm.models.core.mixins import ReprMixin, UtilityMixins
from pyfarm.models.core.types import id_column
from pyfarm.models.core.cfg import TABLE_GPU, MAX_GPUNAME_LENGTH
class GPU(db.Model, UtilityMixins, ReprMixin):
__tablename__ = TABLE_GPU
__table_args__ = (UniqueConstraint("fullname"),)
id = id_column(db.Integer)
fullname = db.Column(db.String(MAX_GPUNAME_LENGTH), nullable=False,
doc="The full name of this graphics card model")
|
# No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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.
"""
GPU
-------
Model describing a given make and model of graphics card.
Every agent can have zero or more GPUs associated with it.
"""
from sqlalchemy.schema import UniqueConstraint
from pyfarm.master.application import db
from pyfarm.models.core.mixins import ReprMixin, UtilityMixins
from pyfarm.models.core.types import id_column
from pyfarm.models.core.cfg import TABLE_GPU, MAX_GPUNAME_LENGTH
class GPU(db.Model, UtilityMixins, ReprMixin):
__tablename__ = TABLE_GPU
__table_args__ = (UniqueConstraint("fullname"),)
id = id_column(db.Integer)
fullname = db.Column(db.String(MAX_GPUNAME_LENGTH), nullable=False,
doc="The full name of this graphics card model")
|
Clear require cache for config reloads.
Wrapping in a `Function` worked for simple `config/environment.js`
contents but breaks down in other scenarios that relied on the file
being evaluated in "nodeland". The prior implementation prevented
custom `require`'s (to get the package name from the `package.json`
for instance).
Now we just clear the `require` cache to allow re-requiring the file
again.
|
'use strict';
var fs = require('fs');
var path = require('path');
var Filter = require('broccoli-filter');
function ConfigLoader (inputTree, options) {
if (!(this instanceof ConfigLoader)) {
return new ConfigLoader(inputTree, options);
}
this.inputTree = inputTree;
this.options = options || {};
}
ConfigLoader.prototype = Object.create(Filter.prototype);
ConfigLoader.prototype.constructor = ConfigLoader;
ConfigLoader.prototype.extensions = ['js'];
ConfigLoader.prototype.targetExtension = 'js';
ConfigLoader.prototype.processFile = function (srcDir, destDir, relativePath) {
var outputPath = path.join(destDir, relativePath);
var configPath = path.join(this.options.project.root, srcDir, relativePath);
// clear the previously cached version of this module
delete require.cache[configPath];
var configGenerator = require(configPath);
var currentConfig = configGenerator(this.options.env);
var moduleString = 'export default ' + JSON.stringify(currentConfig) + ';';
fs.writeFileSync(outputPath, moduleString, { encoding: 'utf8' });
};
module.exports = ConfigLoader;
|
'use strict';
var fs = require('fs');
var path = require('path');
var Filter = require('broccoli-filter');
function ConfigLoader (inputTree, options) {
if (!(this instanceof ConfigLoader)) {
return new ConfigLoader(inputTree, options);
}
this.inputTree = inputTree;
this.options = options || {};
}
ConfigLoader.prototype = Object.create(Filter.prototype);
ConfigLoader.prototype.constructor = ConfigLoader;
ConfigLoader.prototype.extensions = ['js'];
ConfigLoader.prototype.targetExtension = 'js';
ConfigLoader.prototype.processFile = function (srcDir, destDir, relativePath) {
var outputPath = path.join(destDir, relativePath);
var configPath = path.join(this.options.project.root, srcDir, relativePath);
var contents = fs.readFileSync(configPath, {encoding: 'utf8'});
var wrapperContents = '"use strict";\nvar module = { };\n' + contents + '; return module.exports(env);';
var configGenerator = new Function('env', wrapperContents);
var currentConfig = configGenerator(this.options.env);
var moduleString = 'export default ' + JSON.stringify(currentConfig) + ';';
fs.writeFileSync(outputPath, moduleString, { encoding: 'utf8' });
};
module.exports = ConfigLoader;
|
Add guid to checkbox select
|
import FormControlsAbstractSelectComponent from './abstract-select';
import { action } from '@ember/object';
import { arg } from 'ember-arg-types';
import { string, bool } from 'prop-types';
import { get } from '@ember/object';
import { A } from '@ember/array';
import { guidFor } from '@ember/object/internals';
export default class FormControlsFfCheckboxSelectComponent extends FormControlsAbstractSelectComponent {
@arg(string)
for = 'id';
@arg
value = [];
@arg(bool)
showClearAll = false;
get _showClearAll() {
return this.showClearAll && this.value.length > 0;
}
@action
idFor(item) {
return `${this.for}-${this.isPrimitive ? item : get(item, this.idKey)}-${guidFor(this)}`;
}
@action
labelFor(item) {
return this.isPrimitive ? item : get(item, this.labelKey);
}
@action
handleChange(value) {
if (this.isSelected(value)) {
this.args.onChange(this.value.filter((_) => !this._compare(_, value)));
} else {
this.args.onChange(A(this.value).toArray().concat(value));
}
}
@action
isSelected(value) {
return !!this.value.find((_) => this._compare(_, value));
}
@action
clearAll() {
return this.args.onChange([]);
}
_compare(a, b) {
return this.isPrimitive ? a === b : get(a, this.idKey) === get(b, this.idKey);
}
}
|
import FormControlsAbstractSelectComponent from './abstract-select';
import { action } from '@ember/object';
import { arg } from 'ember-arg-types';
import { string, bool } from 'prop-types';
import { get } from '@ember/object';
import { A } from '@ember/array';
export default class FormControlsFfCheckboxSelectComponent extends FormControlsAbstractSelectComponent {
@arg(string)
for = 'id';
@arg
value = [];
@arg(bool)
showClearAll = false;
get _showClearAll() {
return this.showClearAll && this.value.length > 0;
}
@action
idFor(item) {
return `${this.for}-${this.isPrimitive ? item : get(item, this.idKey)}`;
}
@action
labelFor(item) {
return this.isPrimitive ? item : get(item, this.labelKey);
}
@action
handleChange(value) {
if (this.isSelected(value)) {
this.args.onChange(this.value.filter((_) => !this._compare(_, value)));
} else {
this.args.onChange(A(this.value).toArray().concat(value));
}
}
@action
isSelected(value) {
return !!this.value.find((_) => this._compare(_, value));
}
@action
clearAll() {
return this.args.onChange([]);
}
_compare(a, b) {
return this.isPrimitive ? a === b : get(a, this.idKey) === get(b, this.idKey);
}
}
|
Change 'language' to 'syntax', that is more precise terminology.
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
syntax = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
language = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
|
Remove superfluous check in core.oauth
|
/*globals chrome,console */
/*jslint indent:2,browser:true, node:true */
var PromiseCompat = require('es6-promise').Promise;
var oAuthRedirectId = "freedom.oauth.redirect.handler";
var ChromeIdentityAuth = function() {
"use strict";
};
ChromeIdentityAuth.prototype.initiateOAuth = function(redirectURIs, continuation) {
"use strict";
var i;
if (typeof chrome !== 'undefined' &&
typeof chrome.identity !== 'undefined') {
for (i = 0; i < redirectURIs.length; i += 1) {
if (redirectURIs[i].indexOf('https://') === 0 &&
redirectURIs[i].indexOf('.chromiumapp.org') > 0) {
continuation({
redirect: redirectURIs[i],
state: oAuthRedirectId + Math.random()
});
return true;
}
}
}
return false;
};
ChromeIdentityAuth.prototype.launchAuthFlow = function(authUrl, stateObj, continuation) {
chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true
}, function(stateObj, continuation, responseUrl) {
continuation(responseUrl);
}.bind({}, stateObj, continuation));
};
/**
* If we have access to chrome.identity, use the built-in support for oAuth flows
* chrome.identity exposes a very similar interface to core.oauth.
*/
module.exports = ChromeIdentityAuth;
|
/*globals chrome,console */
/*jslint indent:2,browser:true, node:true */
var PromiseCompat = require('es6-promise').Promise;
var oAuthRedirectId = "freedom.oauth.redirect.handler";
var ChromeIdentityAuth = function() {
"use strict";
};
ChromeIdentityAuth.prototype.initiateOAuth = function(redirectURIs, continuation) {
"use strict";
var i;
if (typeof chrome !== 'undefined' &&
typeof chrome.permissions !== 'undefined' && //cca doesn't support chrome.permissions yet
typeof chrome.identity !== 'undefined') {
for (i = 0; i < redirectURIs.length; i += 1) {
if (redirectURIs[i].indexOf('https://') === 0 &&
redirectURIs[i].indexOf('.chromiumapp.org') > 0) {
continuation({
redirect: redirectURIs[i],
state: oAuthRedirectId + Math.random()
});
return true;
}
}
}
return false;
};
ChromeIdentityAuth.prototype.launchAuthFlow = function(authUrl, stateObj, continuation) {
chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true
}, function(stateObj, continuation, responseUrl) {
continuation(responseUrl);
}.bind({}, stateObj, continuation));
};
/**
* If we have access to chrome.identity, use the built-in support for oAuth flows
* chrome.identity exposes a very similar interface to core.oauth.
*/
module.exports = ChromeIdentityAuth;
|
Add ExcludeIds parameter to AnswerServer GetResources action
[rev. matthew.gordon]
|
/*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.types.requests.idol.actions.answer.params;
@SuppressWarnings({"WeakerAccess", "unused"})
public enum GetResourcesParams {
ExcludedIds,
Filter,
FirstResult,
Ids,
MaxResults,
Sort,
SystemName,
Type;
public static GetResourcesParams fromValue(final String value) {
for (final GetResourcesParams param : values()) {
if (param.name().equalsIgnoreCase(value)) {
return param;
}
}
throw new IllegalArgumentException("Unknown parameter " + value);
}
}
|
/*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.types.requests.idol.actions.answer.params;
@SuppressWarnings({"WeakerAccess", "unused"})
public enum GetResourcesParams {
Filter,
FirstResult,
Ids,
MaxResults,
Sort,
SystemName,
Type;
public static GetResourcesParams fromValue(final String value) {
for (final GetResourcesParams param : values()) {
if (param.name().equalsIgnoreCase(value)) {
return param;
}
}
throw new IllegalArgumentException("Unknown parameter " + value);
}
}
|
Put in some version requirements.
|
import os
from setuptools import setup, find_packages
setup(name='morepath',
version = '0.1dev',
description="A micro web-framework with superpowers",
author="Martijn Faassen",
author_email="faassen@startifact.com",
license="BSD",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'venusian >= 1.0a8',
'reg',
'werkzeug >= 0.9.4',
],
extras_require = dict(
test=['pytest >= 2.0',
'pytest-cov'],
),
)
|
import os
from setuptools import setup, find_packages
setup(name='morepath',
version = '0.1dev',
description="A micro web-framework with superpowers",
author="Martijn Faassen",
author_email="faassen@startifact.com",
license="BSD",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'venusian',
'reg',
'werkzeug',
],
extras_require = dict(
test=['pytest >= 2.0',
'pytest-cov'],
),
)
|
Use POST instead of GET Request for ES Search API (Issue with query string size)
|
from __future__ import absolute_import
from future.builtins import ( # noqa
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
from functools import wraps
import logging
from elasticsearch import Elasticsearch
from conf.appconfig import SEARCH_SETTINGS
MAPPING_LOCATION = './conf/index-mapping.json'
logger = logging.getLogger(__name__)
def using_search(fun):
"""
Function wrapper that automatically passes elastic search instance to
wrapped function.
:param fun: Function to be wrapped
:return: Wrapped function.
"""
@wraps(fun)
def outer(*args, **kwargs):
kwargs.setdefault('es', get_search_client())
kwargs.setdefault('idx', SEARCH_SETTINGS['default-index'])
return fun(*args, **kwargs)
return outer
def get_search_client():
"""
Creates the elasticsearch client instance using SEARCH_SETTINGS
:return: Instance of Elasticsearch
:rtype: elasticsearch.Elasticsearch
"""
return Elasticsearch(hosts=SEARCH_SETTINGS['host'],
port=SEARCH_SETTINGS['port'],
send_get_body_as='POST')
|
from __future__ import absolute_import
from future.builtins import ( # noqa
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
from functools import wraps
import logging
from elasticsearch import Elasticsearch
from conf.appconfig import SEARCH_SETTINGS
MAPPING_LOCATION = './conf/index-mapping.json'
logger = logging.getLogger(__name__)
def using_search(fun):
"""
Function wrapper that automatically passes elastic search instance to
wrapped function.
:param fun: Function to be wrapped
:return: Wrapped function.
"""
@wraps(fun)
def outer(*args, **kwargs):
kwargs.setdefault('es', get_search_client())
kwargs.setdefault('idx', SEARCH_SETTINGS['default-index'])
return fun(*args, **kwargs)
return outer
def get_search_client():
"""
Creates the elasticsearch client instance using SEARCH_SETTINGS
:return: Instance of Elasticsearch
:rtype: elasticsearch.Elasticsearch
"""
return Elasticsearch(hosts=SEARCH_SETTINGS['host'],
port=SEARCH_SETTINGS['port'])
|
Update Cloud9 per 2021-04-01 changes
|
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import integer
class Repository(AWSProperty):
props = {
"PathComponent": (str, True),
"RepositoryUrl": (str, True),
}
class EnvironmentEC2(AWSObject):
resource_type = "AWS::Cloud9::EnvironmentEC2"
props = {
"AutomaticStopTimeMinutes": (integer, False),
"ConnectionType": (str, False),
"Description": (str, False),
"ImageId": (str, False),
"InstanceType": (str, True),
"Name": (str, False),
"OwnerArn": (str, False),
"Repositories": ([Repository], False),
"SubnetId": (str, False),
"Tags": (Tags, False),
}
|
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer
class Repository(AWSProperty):
props = {
"PathComponent": (str, True),
"RepositoryUrl": (str, True),
}
class EnvironmentEC2(AWSObject):
resource_type = "AWS::Cloud9::EnvironmentEC2"
props = {
"AutomaticStopTimeMinutes": (integer, False),
"Description": (str, False),
"InstanceType": (str, True),
"Name": (str, False),
"OwnerArn": (str, False),
"Repositories": ([Repository], False),
"SubnetId": (str, False),
}
|
Remove default route because it is not the desired behavior.
Autoconverted from SVN (revision:1409)
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template, redirect_to
UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}'
urlpatterns = patterns('dashboard.main.views',
# Index
(r'^$', redirect_to, {'url': '/ingest/'}),
# Ingest
url(r'ingest/$', direct_to_template, {'template': 'main/ingest.html', 'extra_context': {'polling_interval': settings.POLLING_INTERVAL, 'microservices_help': settings.MICROSERVICES_HELP}}, 'ingest'),
(r'ingest/go/$', 'ingest'),
(r'ingest/go/(?P<uuid>' + UUID_REGEX + ')$', 'ingest'),
(r'jobs/(?P<uuid>' + UUID_REGEX + ')/explore/$', 'explore'),
(r'jobs/(?P<uuid>' + UUID_REGEX + ')/list-objects/$', 'list_objects'),
(r'tasks/(?P<uuid>' + UUID_REGEX + ')/$', 'tasks'),
# Preservatin planning
(r'preservation-planning/$', 'preservation_planning'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template, redirect_to
UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}'
urlpatterns = patterns('dashboard.main.views',
# Ingest
url(r'ingest/$', direct_to_template, {'template': 'main/ingest.html', 'extra_context': {'polling_interval': settings.POLLING_INTERVAL, 'microservices_help': settings.MICROSERVICES_HELP}}, 'ingest'),
(r'ingest/go/$', 'ingest'),
(r'ingest/go/(?P<uuid>' + UUID_REGEX + ')$', 'ingest'),
(r'jobs/(?P<uuid>' + UUID_REGEX + ')/explore/$', 'explore'),
(r'tasks/(?P<uuid>' + UUID_REGEX + ')/$', 'tasks'),
# Preservatin planning
(r'preservation-planning/$', 'preservation_planning'),
# Index
(r'', redirect_to, {'url': '/ingest/'}),
)
|
Fix broken require after refactoring
|
import program from 'commander'
import sagui from './index'
import { InvalidPath } from './configure/path'
import { logError, log } from './util/log'
program.command('build')
.description('Build the project')
.action(function (options) {
sagui.build(options)
})
program.command('dist')
.description('Builds an optimized distribution of the project')
.action(function (options) {
sagui.dist(options)
})
program.command('develop')
.description('Run development environment')
.action(function (options) {
sagui.develop(options)
})
program.command('test')
.description('Run tests')
.option('-w, --watch', 'Run tests on any file change')
.action(function (options) {
sagui.test(options)
})
program.command('install')
.description('Install or update sagui in the current project')
.action(function (options) {
sagui.install(options)
log('installed in the project')
})
export default function cli (argv) {
try {
program.parse(argv)
} catch (e) {
if (e instanceof InvalidPath) {
logError('Must be executed in target project\'s package.json path')
} else {
logError('Error starting up')
logError(e.stack || e)
}
}
if (!argv.slice(2).length) program.outputHelp()
}
|
import program from 'commander'
import sagui from './index'
import { InvalidPath } from './plugins/path'
import { logError, log } from './util/log'
program.command('build')
.description('Build the project')
.action(function (options) {
sagui.build(options)
})
program.command('dist')
.description('Builds an optimized distribution of the project')
.action(function (options) {
sagui.dist(options)
})
program.command('develop')
.description('Run development environment')
.action(function (options) {
sagui.develop(options)
})
program.command('test')
.description('Run tests')
.option('-w, --watch', 'Run tests on any file change')
.action(function (options) {
sagui.test(options)
})
program.command('install')
.description('Install or update sagui in the current project')
.action(function (options) {
sagui.install(options)
log('installed in the project')
})
export default function cli (argv) {
try {
program.parse(argv)
} catch (e) {
if (e instanceof InvalidPath) {
logError('Must be executed in target project\'s package.json path')
} else {
logError('Error starting up')
logError(e.stack || e)
}
}
if (!argv.slice(2).length) program.outputHelp()
}
|
Fix the scenario plugin sample
We forgot to fix scenario plugin sample when we were doing
rally.task.scenario refactoring
Change-Id: Iadbb960cf168bd3b9cd6c1881a5f7a8dffd7036f
|
# Copyright 2013: Mirantis Inc.
# 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.
from rally.plugins.openstack import scenario
from rally.task import atomic
class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
@atomic.action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@atomic.action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@scenario.configure()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
|
# Copyright 2013: Mirantis Inc.
# 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.
from rally.task.scenarios import base
class ScenarioPlugin(base.Scenario):
"""Sample plugin which lists flavors."""
@base.atomic_action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@base.atomic_action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@base.scenario()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
|
Use PEP8 style for conditionals
|
import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.html. The ``re`` module provides the
# ``compile`` function, which prepares regex patterns for use in searching input
# strings.
#
# We put an ``r`` before the string so that Python doesn't interpret the
# backslashes before the ``re`` module gets to see them. (E.g., ``\n`` means a
# newline character, so ``\n`` is a single character, not two as they appear in
# the source code.)
#
# The Unicode flag lets us handle words with accented characters.
FIRST_LAST = re.compile(r"(\w*)\s+((?:\w|\s|['-]){2,})", flags=re.UNICODE)
def split_name(name):
'''Return ("First", "Last") tuple from a string like "First Last".
``name`` is a string. This function returns a tuple of strings. When a
non-matching string is encoutered, we return ``None``.
'''
match = FIRST_LAST.search(name)
if match is None:
return None
return match.group(1), match.group(2)
|
import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.html. The ``re`` module provides the
# ``compile`` function, which prepares regex patterns for use in searching input
# strings.
#
# We put an ``r`` before the string so that Python doesn't interpret the
# backslashes before the ``re`` module gets to see them. (E.g., ``\n`` means a
# newline character, so ``\n`` is a single character, not two as they appear in
# the source code.)
#
# The Unicode flag lets us handle words with accented characters.
FIRST_LAST = re.compile(r"(\w*)\s+((?:\w|\s|['-]){2,})", flags=re.UNICODE)
def split_name(name):
'''Return ("First", "Last") tuple from a string like "First Last".
``name`` is a string. This function returns a tuple of strings. When a
non-matching string is encoutered, we return ``None``.
'''
match = FIRST_LAST.search(name)
return None if match is None else (match.group(1), match.group(2))
|
Add blank to allow no stars/tags in admin
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.text
|
Revert remote origin to 'origin' for deploy github pages
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin2' // default is 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
Use generator to get random character buffers
|
var mt = require('mersenne-twister')
var prng
var codes
var generator
main()
function main() {
seed = process.argv[2]
setup(seed)
console.log(getBuffer(10000))
}
function setup(seed) {
if (!seed) {
console.log('no seed provided - using default seed')
seed = 123
}
prng = new mt(seed)
codes = getCommonCodes()
charGen = randomCharacterGen()
}
function getBuffer(size) {
var buffer = ''
var i = 0
while (i++ < size) {
buffer += charGen.next().value
}
return buffer
}
function getRange(from, to) {
var range = []
for (;from <= to; from++) {
range.push(from)
}
return range
}
function getCommonCodes() {
var codes = getRange(97, 122)
codes.push(32)
codes.push(33)
codes.push(44)
codes.push(46)
return codes
}
function* randomCharacterGen() {
while(true) {
var index = Math.floor(prng.random() * codes.length)
var code = codes[index]
yield String.fromCharCode(code)
}
}
|
var mt = require('mersenne-twister')
var generator
main()
function main() {
seed = process.argv[2]
if (!seed) {
console.log('no seed provided - using default seed')
seed = 123
}
generator = new mt(seed)
console.log(getCharacterStream(10))
}
function getRange(from, to) {
var range = []
for (;from <= to; from++) {
range.push(from)
}
return range
}
function getCommonCodes() {
var codes = getRange(97, 122)
codes.push(32)
codes.push(33)
codes.push(44)
codes.push(46)
return codes
}
function getCharacterStream(limit) {
var codes = getCommonCodes()
var characters = []
var i = 0
for (; i < limit; i++) {
characters.push(getRandomCharacter(codes))
}
return characters
}
function getRandomCharacter(codes) {
var index = Math.floor(generator.random() * codes.length)
var code = codes[index]
return String.fromCharCode(code)
}
|
[BACKLOG-18075] Fix for input box focus
|
/*!
* Copyright 2017 Pentaho Corporation. 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.
*/
define([
'angular'
], function(angular) {
focus.inject = ['$timeout'];
/**
* @param {Function} $timeout - Angular wrapper for window.setTimeout.
* @return {{restrict: string, scope: {model: string}, link: link}} - Focus directive
*/
function focus($timeout) {
return {
restrict: 'AE',
scope: {model: '=ngModel'},
link: function(scope, element, attrs) {
scope.$watch("model", function(value) {
$timeout(function() {
element[0].focus();
element[0].select();
element[0].setSelectionRange(0, value.length);
});
});
}
};
}
return {
name: "focus",
options: ['$timeout', focus]
};
});
|
/*!
* Copyright 2017 Pentaho Corporation. 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.
*/
define([
'angular'
], function (angular) {
focus.inject = ['$timeout', '$document'];
function focus($timeout, $document) {
return {
retrict: 'AE',
scope: {},
link: function (scope, element, attr) {
$document.ready(function() {
$timeout(function() {
element[0].focus();
element[0].select();
element[0].setSelectionRange(0, element.val().length);
}, 100);
});
}
}
}
return {
name: "focus",
options: ['$timeout', '$document', focus]
}
});
|
Remove deprecated ContainerAware class and make use of the trait in another class
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
/**
* References Doctrine connections and entity/document managers.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
abstract class ManagerRegistry extends AbstractManagerRegistry implements ContainerAwareInterface
{
use ContainerAwareTrait;
/**
* {@inheritdoc}
*/
protected function getService($name)
{
return $this->container->get($name);
}
/**
* {@inheritdoc}
*/
protected function resetService($name)
{
$this->container->set($name, null);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
/**
* References Doctrine connections and entity/document managers.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
abstract class ManagerRegistry extends AbstractManagerRegistry implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* {@inheritdoc}
*/
protected function getService($name)
{
return $this->container->get($name);
}
/**
* {@inheritdoc}
*/
protected function resetService($name)
{
$this->container->set($name, null);
}
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
|
Throw exception before using null
|
package org.irmacard.credentials.info;
import java.net.URI;
import java.util.HashMap;
/**
* TODO: Change print statements to proper Logging statements
*/
public class DescriptionStore {
static URI CORE_LOCATION;
static DescriptionStore ds;
HashMap<Integer,CredentialDescription> credentialDescriptions = new HashMap<Integer, CredentialDescription>();
/**
* Define the CoreLocation. This has to be set before using the
* DescriptionStore.
* @param coreLocation Location of configuration files.
*/
public static void setCoreLocation(URI coreLocation) {
CORE_LOCATION = coreLocation;
}
/**
* Get DescriptionStore instance
*
* @return The DescriptionStore instance
* @throws Exception if CoreLocation has not been set
*/
public static DescriptionStore getInstance() throws InfoException {
if(CORE_LOCATION == null) {
// TODO: Improve exception type
throw new InfoException(
"Please set CoreLocation before using the DescriptionStore");
}
if(ds == null) {
ds = new DescriptionStore();
}
return ds;
}
private DescriptionStore() throws InfoException {
TreeWalker tw = new TreeWalker(CORE_LOCATION, this);
tw.parseConfiguration();
}
public CredentialDescription getCredentialDescription(short id) {
return credentialDescriptions.get(new Integer(id));
}
protected void addCredentialDescription(CredentialDescription cd) {
credentialDescriptions.put(new Integer(cd.getId()), cd);
}
}
|
package org.irmacard.credentials.info;
import java.net.URI;
import java.util.HashMap;
/**
* TODO: Change print statements to proper Logging statements
*/
public class DescriptionStore {
static URI CORE_LOCATION;
static DescriptionStore ds;
HashMap<Integer,CredentialDescription> credentialDescriptions = new HashMap<Integer, CredentialDescription>();
/**
* Define the CoreLocation. This has to be set before using the
* DescriptionStore.
* @param coreLocation Location of configuration files.
*/
public static void setCoreLocation(URI coreLocation) {
CORE_LOCATION = coreLocation;
}
/**
* Get DescriptionStore instance
*
* @return The DescriptionStore instance
* @throws Exception if CoreLocation has not been set
*/
public static DescriptionStore getInstance() throws InfoException {
if(ds == null) {
ds = new DescriptionStore();
}
if(CORE_LOCATION == null) {
// TODO: Improve exception type
throw new InfoException(
"Please set CoreLocation before using the DescriptionStore");
}
return ds;
}
private DescriptionStore() throws InfoException {
TreeWalker tw = new TreeWalker(CORE_LOCATION, this);
tw.parseConfiguration();
}
public CredentialDescription getCredentialDescription(short id) {
return credentialDescriptions.get(new Integer(id));
}
protected void addCredentialDescription(CredentialDescription cd) {
credentialDescriptions.put(new Integer(cd.getId()), cd);
}
}
|
fix: Return empty tuple in get_readonly_fields
|
from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
if obj:
return 'key', 'value', 'is_secret'
return tuple()
class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline):
model = EnvironmentVariable
extra = 0
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time',
'last_build_number', 'can_deploy')
list_filter = ['owner', 'queue_name', 'approved', 'can_deploy']
actions = ['sync_members']
inlines = [EnvironmentVariableInline]
def sync_members(self, request, queryset):
for project in queryset:
project.update_members()
self.message_user(
request,
'{} project{} was synced'.format(len(queryset), pluralize(len(queryset)))
)
sync_members.short_description = 'Sync members of selected projects'
@admin.register(EnvironmentVariable)
class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin):
list_display = (
'__str__',
'is_secret',
)
|
from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
if obj:
return 'key', 'value', 'is_secret'
class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline):
model = EnvironmentVariable
extra = 0
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time',
'last_build_number', 'can_deploy')
list_filter = ['owner', 'queue_name', 'approved', 'can_deploy']
actions = ['sync_members']
inlines = [EnvironmentVariableInline]
def sync_members(self, request, queryset):
for project in queryset:
project.update_members()
self.message_user(
request,
'{} project{} was synced'.format(len(queryset), pluralize(len(queryset)))
)
sync_members.short_description = 'Sync members of selected projects'
@admin.register(EnvironmentVariable)
class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin):
list_display = (
'__str__',
'is_secret',
)
|
Use basic auth when posting data.
|
package com.watcher.car;
import android.util.Base64;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.util.Base64.DEFAULT;
public class HttpClient {
public void post(String data) {
try {
HttpURLConnection conn = openConnection("http://leetor.no-ip.org:8010/");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("car:watcher".getBytes(), DEFAULT));
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed to post data, http status: " + conn.getResponseCode());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private HttpURLConnection openConnection(String url) throws IOException {
return (HttpURLConnection) (new URL(url).openConnection());
}
}
|
package com.watcher.car;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClient {
public void post(String data) {
try {
HttpURLConnection conn = openConnection("http://leetor.no-ip.org:8010/");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed to post data, http status: " + conn.getResponseCode());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private HttpURLConnection openConnection(String url) throws IOException {
return (HttpURLConnection) (new URL(url).openConnection());
}
}
|
Add go_api as a dependency.
|
from setuptools import setup, find_packages
setup(
name="go_contacts",
version="0.1.0a",
url='http://github.com/praekelt/go-contacts-api',
license='BSD',
description="A contacts and groups API for Vumi Go",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
include_package_data=True,
install_requires=[
'cyclone',
'go_api',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
|
from setuptools import setup, find_packages
setup(
name="go_contacts",
version="0.1.0a",
url='http://github.com/praekelt/go-contacts-api',
license='BSD',
description="A contacts and groups API for Vumi Go",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
include_package_data=True,
install_requires=[
'cyclone',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Update the explostion effect code comments.
|
/* global Demo, Random */
//------------------------------------------------------------------
//
// Creates an explostion effect that emits all particles at creation time.
// The spec is defined as:
// {
// center: { x: , y: },
// howMany: // How many particles to emit
// }
//
//------------------------------------------------------------------
Demo.components.ParticleSystem.createEffectExplosion = function(spec) {
'use strict';
var effect = {
get center() { return spec.center; },
get emitRate() { return 0; }
},
particle = 0;
effect.update = function() {
for (particle = 0; particle < spec.howMany; particle += 1) {
//
// Create a new fire particle
Demo.components.ParticleSystem.createParticle({
image: Demo.assets['fire'],
center: { x: spec.center.x, y: spec.center.y },
size: Random.nextGaussian(0.015, 0.005),
direction: Random.nextCircleVector(),
speed: Random.nextGaussian(0.0003, 0.0001),
rateRotation: (2 * Math.PI) / 1000, // Radians per millisecond
lifetime: Random.nextGaussian(1500, 250)
});
}
return false; // One time emit!
};
Demo.components.ParticleSystem.emitters.push(effect);
};
|
/* global Demo, Random */
Demo.components.ParticleSystem.createEffectExplosion = function(spec) {
'use strict';
var effect = {
get center() { return spec.center; },
get emitRate() { return 0; }
},
particle = 0;
effect.update = function() {
for (particle = 0; particle < spec.howMany; particle += 1) {
//
// Create a new fire particle
Demo.components.ParticleSystem.createParticle({
image: Demo.assets['fire'],
center: { x: spec.center.x, y: spec.center.y },
size: Random.nextGaussian(0.015, 0.005),
direction: Random.nextCircleVector(),
speed: Random.nextGaussian(0.0003, 0.0001),
rateRotation: (2 * Math.PI) / 1000, // Radians per millisecond
lifetime: Random.nextGaussian(1500, 250)
});
}
return false; // One time emit!
};
Demo.components.ParticleSystem.emitters.push(effect);
};
|
Logs: Check for each stream if the filepath exists, create it otherwise
|
'use strict';
const bunyan = require('bunyan');
const path = require('path');
const fs = require('fs');
const argv = require('yargs').argv;
function initLogger({Configuration}) {
const environment = Configuration.get('env');
const loggerConfig = Configuration.get('logs');
const streams = []
// If Mockiji is not in silent mode, add a stdout stream
if (!argv.silent) {
streams.push({
stream: process.stdout,
level: (environment === 'dev') ? 'debug' : 'info',
});
}
// Create log streams based on the configuration
if (loggerConfig) {
if (Array.isArray(loggerConfig)) {
for (let stream of loggerConfig) {
streams.push(stream);
}
} else {
streams.push(loggerConfig);
}
}
// Create logs directory for each stream if needed
for (let stream of streams) {
if (stream.path) {
const logsDirectory = path.dirname(stream.path);
if (!fs.existsSync(logsDirectory)) {
fs.mkdirSync(logsDirectory);
}
}
}
// Return bunyan object so it can directly be used
// to log things.
//
// Logger.log('foo');
//
return bunyan.createLogger({
name: 'mockiji',
streams
});
}
module.exports = initLogger;
|
'use strict';
const bunyan = require('bunyan');
const argv = require('yargs').argv;
function initLogger({Configuration}) {
const environment = Configuration.get('env');
const loggerConfig = Configuration.get('logs');
const streams = []
// If Mockiji is not in silent mode, add a stdout stream
if (!argv.silent) {
streams.push({
stream: process.stdout,
level: (environment === 'dev') ? 'debug' : 'info',
});
}
// Create log streams based on the configuration
if (loggerConfig) {
if (Array.isArray(loggerConfig)) {
for (let stream of loggerConfig) {
streams.push(stream);
}
} else {
streams.push(loggerConfig);
}
}
// Return bunyan object so it can directly be used
// to log things.
//
// Logger.log('foo');
//
return bunyan.createLogger({
name: 'mockiji',
streams
});
}
module.exports = initLogger;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.