text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix Sha1Stream return raw buffer | 'use strict';
var Stream = require('stream');
var Transform = Stream.Transform;
var crypto = require('crypto');
var ALGORITHM = 'sha1';
var ENCODING = 'hex';
function Sha1Stream() {
Transform.call(this, {
objectMode: true
});
this._hash = crypto.createHash(ALGORITHM);
}
require('util').inherits(Sha1Stream, Transform);
Sha1Stream.prototype._transform = function(chunk, enc, callback) {
var buffer = chunk instanceof Buffer ? chunk : new Buffer(chunk, enc);
this._hash.update(buffer);
callback();
};
Sha1Stream.prototype._flush = function(callback) {
this.push(this._hash.digest(ENCODING));
callback();
};
exports.hash = function(content) {
var hash = crypto.createHash(ALGORITHM);
hash.update(content);
return hash.digest(ENCODING);
};
exports.stream = function() {
return new Sha1Stream();
};
| 'use strict';
var Stream = require('stream');
var Transform = Stream.Transform;
var crypto = require('crypto');
var ALGORITHM = 'sha1';
var ENCODING = 'hex';
function Sha1Stream() {
Transform.call(this);
this._hash = crypto.createHash(ALGORITHM);
}
require('util').inherits(Sha1Stream, Transform);
Sha1Stream.prototype._transform = function(chunk, enc, callback) {
var buffer = chunk instanceof Buffer ? chunk : new Buffer(chunk, enc);
this._hash.update(buffer);
callback();
};
Sha1Stream.prototype._flush = function(callback) {
this.push(this._hash.digest(ENCODING));
callback();
};
exports.hash = function(content) {
var hash = crypto.createHash(ALGORITHM);
hash.update(content);
return hash.digest(ENCODING);
};
exports.stream = function() {
return new Sha1Stream();
};
|
Fix name of the logger | package tw.davy.minecraft.treelogging.bukkit;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import tw.davy.minecraft.treelogging.bukkit.listener.BlockListener;
/**
* The main class for TreeLogging as a Bukkit plugin.
*
* @author Davy
*/
public final class TreeLoggingPlugin extends JavaPlugin
{
public static final Logger logger = Logger.getLogger("Minecraft.TreeLogging");
/**
* Called on plugin enable.
*/
public void onEnable()
{
(new BlockListener(this)).registerEvents();
logger.info("[TreeLogging] Enabled.");
}
/**
* Called on plugin disable.
*/
public void onDisable()
{
logger.info("[TreeLogging] Disabled.");
}
/**
* Called on command trigged.
*/
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if (cmd.getName().equalsIgnoreCase("treelogging"))
{
//if (!(sender instanceof Player)) {
//} else {
// Player player = (Player) sender;
//}
sender.sendMessage("TreeLogging, Makes logging trees truely.");
sender.sendMessage(" Version: 0.1.0");
return true;
}
return false;
}
}
| package tw.davy.minecraft.treelogging.bukkit;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import tw.davy.minecraft.treelogging.bukkit.listener.BlockListener;
/**
* The main class for TreeLogging as a Bukkit plugin.
*
* @author Davy
*/
public final class TreeLoggingPlugin extends JavaPlugin
{
public static final Logger logger = Logger.getLogger("Minecraft.LyTreeHelper");
/**
* Called on plugin enable.
*/
public void onEnable()
{
(new BlockListener(this)).registerEvents();
logger.info("[TreeLogging] Enabled.");
}
/**
* Called on plugin disable.
*/
public void onDisable()
{
logger.info("[TreeLogging] Disabled.");
}
/**
* Called on command trigged.
*/
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if (cmd.getName().equalsIgnoreCase("treelogging"))
{
//if (!(sender instanceof Player)) {
//} else {
// Player player = (Player) sender;
//}
sender.sendMessage("TreeLogging, Makes logging trees truely.");
sender.sendMessage(" Version: 0.1.0");
return true;
}
return false;
}
}
|
Modify that using default value when input value is None. | # coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
| # coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
Remove a Javadoc link from the 'tags' package to the 'stats' package. | /*
* Copyright 2017, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 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.
*/
/**
* API for associating tags with scoped operations.
*
* <p>This package manages a set of tags in the {@code io.grpc.Context}. The tags can be used to
* label anything that is associated with a specific operation. For example, the {@code
* io.opencensus.stats} package labels all measurements with the current tags.
*
* <p>{@link io.opencensus.tags.Tag Tags} are key-value pairs. The {@link io.opencensus.tags.TagKey
* keys} are wrapped {@code String}s, but the values can have multiple types, such as {@code
* String}, {@code long}, and {@code boolean}. They are stored as a map in a {@link
* io.opencensus.tags.TagContext}.
*/
// TODO(sebright): Add code examples after the API is updated to use a TagContext factory.
package io.opencensus.tags;
| /*
* Copyright 2017, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 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.
*/
/**
* API for associating tags with scoped operations.
*
* <p>This package manages a set of tags in the {@code io.grpc.Context}. The tags can be used to
* label anything that is associated with a specific operation. For example, the {@link
* io.opencensus.stats} package labels all measurements with the current tags.
*
* <p>{@link io.opencensus.tags.Tag Tags} are key-value pairs. The {@link io.opencensus.tags.TagKey
* keys} are wrapped {@code String}s, but the values can have multiple types, such as {@code
* String}, {@code long}, and {@code boolean}. They are stored as a map in a {@link
* io.opencensus.tags.TagContext}.
*/
// TODO(sebright): Add code examples after the API is updated to use a TagContext factory.
package io.opencensus.tags;
|
Add test for clicking a link and confirming the page | <?php
namespace SymfonyDay\Bundle\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
// Set a crawler to make a fake request
$crawler = $client->request('GET', '/blog');
// Count instances with CSS3 syntax
$this->assertEquals(2, $crawler->filter('.post')->count());
$this->assertEquals(1, $crawler->filter('html:contains("Symfony Day")')->count());
// Use a regexp to look for a certain word
$response = $client->getResponse();
$this->assertRegExp('/Second/', $response->getContent());
// Check if there are more than five SQL queries
$profile = $client->getProfile();
$this->assertLessThanOrEqual(5, $profile->getCollector('db')->getQueryCount());
// Click a link a move to another page
$title = 'Welcome To The Symfony Day Conference';
$link = $crawler
->selectLink($title)
->link()
;
$crawler = $client->click($link);
$this->assertEquals(1, $crawler->filter('title:contains("'.$title.'")')->count());
}
}
| <?php
namespace SymfonyDay\Bundle\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
// Set a crawler to make a fake request
$crawler = $client->request('GET', '/blog');
// Count instances with CSS3 syntax
$this->assertEquals(2, $crawler->filter('.post')->count());
$this->assertEquals(1, $crawler->filter('html:contains("Symfony Day")')->count());
// Use a regexp to look for a certain word
$response = $client->getResponse();
$this->assertRegExp('/Second/', $response->getContent());
// Check if there are more than five SQL queries
$profile = $client->getProfile();
$this->assertLessThanOrEqual(5, $profile->getCollector('db')->getQueryCount());
}
}
|
Fix error if trying to do slr in current dir | #!/usr/bin/env node
global.__base = __dirname + '/src/';
// Commands
var cli = require('commander');
cli
.version('0.0.1')
.option('-p, --port <port>' , 'Change static server port [8000]', 8000)
.option('-P, --livereload-port <port>' , 'Change livereload port [35729]', 35729)
.option('-d, --directory <path>' , 'Change the default directory for serving files [.]', process.cwd())
.parse(process.argv);
// Start Asset server
var AssetServer = require(__base + 'assets_server');
var assetServer = new AssetServer({
port: cli.port,
directory: cli.directory,
livereloadPort: cli.livereloadPort
});
assetServer.start();
// Start Livereload server
var LivereloadServer = require(__base + 'livereload_server');
var livereloadServer = new LivereloadServer({
port: cli.livereloadPort
});
livereloadServer.start();
// Start Monitor
var Monitor = require(__base + 'monitor');
var monitor = new Monitor({
directory: cli.directory,
livereloadPort: cli.livereloadPort
})
monitor.start();
| #!/usr/bin/env node
global.__base = __dirname + '/src/';
// Commands
var cli = require('commander');
cli
.version('0.0.1')
.option('-p, --port <port>' , 'Change static server port [8000]', 8000)
.option('-P, --livereload-port <port>' , 'Change livereload port [35729]', 35729)
.option('-d, --directory <path>' , 'Change the default directory for serving files [.]', __dirname)
.parse(process.argv);
// Start Asset server
var AssetServer = require(__base + 'assets_server');
var assetServer = new AssetServer({
port: cli.port,
directory: cli.directory,
livereloadPort: cli.livereloadPort
});
assetServer.start();
// Start Livereload server
var LivereloadServer = require(__base + 'livereload_server');
var livereloadServer = new LivereloadServer({
port: cli.livereloadPort
});
livereloadServer.start();
// Start Monitor
var Monitor = require(__base + 'monitor');
var monitor = new Monitor({
directory: cli.directory,
livereloadPort: cli.livereloadPort
})
monitor.start();
|
Quit ImageOptim app when finished | /*
* grunt-imageoptim
* https://github.com/JamieMason/grunt-imageoptim
*
* Copyright (c) 2013 Jamie Mason @GotNoSugarBaby
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('imageoptim', 'Losslessly compress images from the command line', function() {
var directories = this.filesSrc;
var done = this.async();
var exec = require('child_process').exec;
var complete = 0;
if (!directories.length) {
grunt.fail.fatal('No valid directories were supplied for processing', 1);
}
directories.forEach(function(dir) {
var imageOptim;
grunt.log.writeln('Processing "' + dir + '"');
imageOptim = exec('imageOptim -daq ' + dir, function(error, stdout, stderr) {
if (error !== null) {
done(error);
}
if (stdout) {
console.log(stdout);
}
if (stderr) {
console.log(stderr);
}
});
imageOptim.on('exit', function(code) {
if (++complete === directories.length) {
done(code);
}
});
});
});
};
| /*
* grunt-imageoptim
* https://github.com/JamieMason/grunt-imageoptim
*
* Copyright (c) 2013 Jamie Mason @GotNoSugarBaby
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('imageoptim', 'Losslessly compress images from the command line', function() {
var directories = this.filesSrc;
var done = this.async();
var exec = require('child_process').exec;
var complete = 0;
if (!directories.length) {
grunt.fail.fatal('No valid directories were supplied for processing', 1);
}
directories.forEach(function(dir) {
var imageOptim;
grunt.log.writeln('Processing "' + dir + '"');
imageOptim = exec('imageOptim -da ' + dir, function(error, stdout, stderr) {
if (error !== null) {
done(error);
}
if (stdout) {
console.log(stdout);
}
if (stderr) {
console.log(stderr);
}
});
imageOptim.on('exit', function(code) {
if (++complete === directories.length) {
done(code);
}
});
});
});
};
|
Fix prompt validator that broke netrc saving | import { promisify } from 'bluebird';
import { prompt as promptCallback } from 'promptly';
import { getNetrc, saveNetrc } from '../netrc';
const prompt = promisify(promptCallback);
export default async function login(reindex, args) {
let [url, token] = args._.slice(1);
if (!url) {
url = await prompt('Reindex URL', {
validator: (value) => value && value.length > 0 && value,
retry: true,
});
}
if (!token) {
token = await prompt('Reindex Token', {
validator: (value) => value && value.length > 0 && value,
retry: true,
});
}
const userNetrc = getNetrc();
userNetrc['accounts.reindex.io'] = {
login: url,
password: token,
};
saveNetrc(userNetrc);
console.log('You are now logged-in.');
}
| import { promisify } from 'bluebird';
import { prompt as promptCallback } from 'promptly';
import { getNetrc, saveNetrc } from '../netrc';
const prompt = promisify(promptCallback);
export default async function login(reindex, args) {
let [url, token] = args._.slice(1);
if (!url) {
url = await prompt('Reindex URL', {
validator: (value) => value && value.length > 0,
retry: true,
});
}
if (!token) {
token = await prompt('Reindex Token', {
validator: (value) => value && value.length > 0,
retry: true,
});
}
const userNetrc = getNetrc();
userNetrc['accounts.reindex.io'] = {
login: url,
password: token,
};
saveNetrc(userNetrc);
console.log('You are now logged-in.');
}
|
Set the version to 0.9 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")
with open(README_FILE) as f:
long_description = f.read()
setup(
name="xutils",
version="0.9",
description="A Fragmentary Python Library.",
long_description=long_description,
author="xgfone",
author_email="xgfone@126.com",
maintainer="xgfone",
maintainer_email="xgfone@126.com",
url="https://github.com/xgfone/xutils",
packages=["xutils"],
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")
with open(README_FILE) as f:
long_description = f.read()
setup(
name="xutils",
version="0.8.2",
description="A Fragmentary Python Library.",
long_description=long_description,
author="xgfone",
author_email="xgfone@126.com",
maintainer="xgfone",
maintainer_email="xgfone@126.com",
url="https://github.com/xgfone/xutils",
packages=["xutils"],
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
)
|
Add language strings for mention's scheduled task | <?php
/**
* Language file for mentions
*
* @author Shitiz Garg <mail@dragooon.net>
* @copyright 2014 Shitiz Garg
* @license Simplified BSD (2-Clause) License
*/
global $txt, $context;
$txt['mentions_subject'] = 'MENTIONNAME, you have been mentioned at a post in ' . $context['forum_name'];
$txt['mentions_body'] = 'Hello MENTIONNAME!
MEMBERNAME mentioned you in the post "POSTNAME", you can view the post at POSTLINK
Regards,
' . $context['forum_name'];
$txt['mentions'] = 'Mentions';
$txt['mentions_profile_title'] = 'Posts mentioning %s';
$txt['mentions_post_subject'] = 'Subject';
$txt['mentions_member'] = 'Mentioned By';
$txt['mentions_post_time'] = 'Mentioned Time';
$txt['permissionname_mention_member'] = 'Mention members';
$txt['permissionhelp_mention_member'] = 'Allow members to tag other members and alert them via mentioning them via @username syntax';
$txt['email_mentions'] = 'E-mail mention notifications';
$txt['scheduled_task_removeMentions'] = 'Remove seen mentions';
$txt['scheduled_task_desc_removeMentions'] = 'Automatically removes seen mentions older than the specified days'; | <?php
/**
* Language file for mentions
*
* @author Shitiz Garg <mail@dragooon.net>
* @copyright 2014 Shitiz Garg
* @license Simplified BSD (2-Clause) License
*/
global $txt, $context;
$txt['mentions_subject'] = 'MENTIONNAME, you have been mentioned at a post in ' . $context['forum_name'];
$txt['mentions_body'] = 'Hello MENTIONNAME!
MEMBERNAME mentioned you in the post "POSTNAME", you can view the post at POSTLINK
Regards,
' . $context['forum_name'];
$txt['mentions'] = 'Mentions';
$txt['mentions_profile_title'] = 'Posts mentioning %s';
$txt['mentions_post_subject'] = 'Subject';
$txt['mentions_member'] = 'Mentioned By';
$txt['mentions_post_time'] = 'Mentioned Time';
$txt['permissionname_mention_member'] = 'Mention members';
$txt['permissionhelp_mention_member'] = 'Allow members to tag other members and alert them via mentioning them via @username syntax';
$txt['email_mentions'] = 'E-mail mention notifications'; |
Add redux-async-connect wrapper on client | import React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect';
export function createForServer(store, renderProps) {
return new Promise((resolve, reject) => {
loadOnServer(renderProps, store)
.then(() => {
const root = (
<Provider store={store} key="provider">
<div>
<ReduxAsyncConnect {...renderProps} />
</div>
</Provider>
);
resolve({ root });
})
.catch((err) => {
reject(err);
});
});
}
export function createForClient(store, { routes, history, devComponent }) {
const component = (
<Router render={(props) => <ReduxAsyncConnect {...props} />} history={history}>
{routes}
</Router>
);
const root = (
<Provider store={store} key="provider">
<div>
{component}
{devComponent}
</div>
</Provider>
);
return Promise.resolve({ root });
}
| import React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect';
export function createForServer(store, renderProps) {
return new Promise((resolve, reject) => {
loadOnServer(renderProps, store)
.then(() => {
const root = (
<Provider store={store} key="provider">
<div>
<ReduxAsyncConnect {...renderProps} />
</div>
</Provider>
);
resolve({ root });
})
.catch((err) => {
reject(err);
});
});
}
export function createForClient(store, { routes, history, devComponent }) {
const component = (
<Router history={history}>
{routes}
</Router>
);
const root = (
<Provider store={store} key="provider">
<div>
{component}
{devComponent}
</div>
</Provider>
);
return Promise.resolve({ root });
}
|
Disable test printing to stdOut | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.memory.test;
import org.apache.datasketches.memory.internal.VirtualMachineMemory;
import org.testng.annotations.Test;
@SuppressWarnings("javadoc")
public class VirtualMachineMemoryTest {
@Test
public void maxDirectBufferMemory() {
assert(VirtualMachineMemory.getMaxDBBMemory() >= 0);
}
@Test
public void inertPageAlignment() {
boolean result = VirtualMachineMemory.getIsPageAligned();
//System.out.println("VM page alignment:" + result);
assert(true); //no exception was thrown
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.memory.test;
import org.apache.datasketches.memory.internal.VirtualMachineMemory;
import org.testng.annotations.Test;
@SuppressWarnings("javadoc")
public class VirtualMachineMemoryTest {
@Test
public void maxDirectBufferMemory() {
assert(VirtualMachineMemory.getMaxDBBMemory() >= 0);
}
@Test
public void inertPageAlignment() {
System.out.println("VM page alignment:" + VirtualMachineMemory.getIsPageAligned());
assert(true);
}
}
|
Use the actual new EventEmitter API. | 'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function ImageComponent() {
Component.apply(this, arguments);
}
ImageComponent.Prototype = function() {
this.initialize = function() {
var doc = this.props.doc;
doc.on('document:changed', this.handleDocumentChange, this);
};
this.dispose = function() {
var doc = this.props.doc;
doc.off(this);
};
this.render = function() {
return $$('img')
.addClass('sc-image')
.attr({
"data-id": this.props.node.id,
contentEditable: false,
src: this.props.node.src,
});
};
this.handleDocumentChange = function(change) {
if (change.isAffected([this.props.node.id, "src"])) {
this.rerender();
}
};
};
Component.extend(ImageComponent);
module.exports = ImageComponent;
| 'use strict';
var Component = require('../../ui/Component');
var $$ = Component.$$;
function ImageComponent() {
Component.apply(this, arguments);
}
ImageComponent.Prototype = function() {
this.initialize = function() {
var doc = this.props.doc;
doc.on(this, { 'document:changed': this.handleDocumentChange });
};
this.dispose = function() {
var doc = this.props.doc;
doc.off(this);
};
this.render = function() {
return $$('img')
.addClass('sc-image')
.attr({
"data-id": this.props.node.id,
contentEditable: false,
src: this.props.node.src,
});
};
this.handleDocumentChange = function(change) {
if (change.isAffected([this.props.node.id, "src"])) {
this.rerender();
}
};
};
Component.extend(ImageComponent);
module.exports = ImageComponent;
|
Update import for mysql package | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Coporation
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 main
import (
"os"
"github.com/intelsdi-x/pulse-plugin-publisher-mysql/mysql"
"github.com/intelsdi-x/pulse/control/plugin"
)
func main() {
meta := mysql.Meta()
plugin.Start(meta, mysql.NewMySQLPublisher(), os.Args[1])
}
| /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Coporation
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 main
import (
"os"
"github.com/intelsdi-x/pulse/control/plugin"
"github.com/intelsdi-x/pulse/plugin/publisher/pulse-publisher-mysql/mysql"
)
func main() {
meta := mysql.Meta()
plugin.Start(meta, mysql.NewMySQLPublisher(), os.Args[1])
}
|
Fix T41937: NPE when render report with large line height and letter spacing styles in item | /***********************************************************************
* Copyright (c) 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.nLayout.area.impl;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.nLayout.area.IContainerArea;
public class HtmlRegionArea extends RegionArea implements IContainerArea
{
public HtmlRegionArea( )
{
super( );
}
HtmlRegionArea( HtmlRegionArea area )
{
super( area );
}
public void close( ) throws BirtException
{
if ( specifiedHeight >= currentBP )
{
finished = true;
}
else
{
finished = false;
}
setContentHeight( specifiedHeight );
}
public void update( AbstractArea area ) throws BirtException
{
int aHeight = area.getAllocatedHeight( );
currentBP += aHeight;
if ( currentIP + area.getAllocatedWidth( ) > maxAvaWidth )
{
setNeedClip( true );
}
}
public boolean isFinished( )
{
return finished;
}
}
| /***********************************************************************
* Copyright (c) 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.nLayout.area.impl;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.nLayout.area.IContainerArea;
public class HtmlRegionArea extends RegionArea implements IContainerArea
{
public HtmlRegionArea( )
{
super( );
}
HtmlRegionArea( HtmlRegionArea area )
{
super( area );
}
public void close( ) throws BirtException
{
if ( specifiedHeight >= currentBP )
{
finished = true;
}
else
{
finished = false;
}
setContentHeight( specifiedHeight );
checkDisplayNone( );
}
public void update( AbstractArea area ) throws BirtException
{
int aHeight = area.getAllocatedHeight( );
currentBP += aHeight;
if ( currentIP + area.getAllocatedWidth( ) > maxAvaWidth )
{
setNeedClip( true );
}
}
public boolean isFinished( )
{
return finished;
}
}
|
Fix the populate query on update | 'use strict';
var P = require('bluebird');
var _ = require('lodash');
var Schemas = require('../generators/schemas');
function ResourceUpdater(model, params) {
var schema = Schemas.schemas[model.collection.name];
this.perform = function () {
return new P(function (resolve, reject) {
var query = model
.findByIdAndUpdate(params.id, {
$set: params
}, {
new: true
});
_.each(schema.fields, function (field) {
if (field.reference) { query.populate(field.field); }
});
query
.lean()
.exec(function (err, record) {
if (err) { return reject(err); }
resolve(record);
});
});
};
}
module.exports = ResourceUpdater;
| 'use strict';
var P = require('bluebird');
var _ = require('lodash');
var Schemas = require('../generators/schemas');
function ResourceUpdater(model, params) {
var schema = Schemas.schemas[model.collection.name];
this.perform = function () {
return new P(function (resolve, reject) {
var query = model
.findByIdAndUpdate(params.id, {
$set: params
}, {
new: true
});
_.each(schema.fields, function (field) {
if (field.reference) { query.populate(field); }
});
query
.lean()
.exec(function (err, record) {
if (err) { return reject(err); }
resolve(record);
});
});
};
}
module.exports = ResourceUpdater;
|
Introduce unigram data to warehouse module. | import collections
from data import anagram_index, crossword, warehouse
from spec.data.fixtures import tries
def _get_unigram():
return collections.OrderedDict(tries.kitchen_sink_data())
def _get_unigram_anagram_index():
return anagram_index.AnagramIndex(warehouse.get('/words/unigram'))
def _get_unigram_trie():
return tries.kitchen_sink()
def _get_crossword():
connection = crossword.init(':memory:')
cursor = connection.cursor()
crossword.add(cursor, 'query', 1, {'ask': 1, 'question': 1})
return connection, cursor
def _get_crossword_connection():
connection, cursor = warehouse.get('/phrases/crossword')
del cursor
return connection
def _get_crossword_cursor():
connection, cursor = warehouse.get('/phrases/crossword')
del connection
return cursor
warehouse.init()
warehouse.register('/phrases/crossword', _get_crossword)
warehouse.register('/phrases/crossword/connection', _get_crossword_connection)
warehouse.register('/phrases/crossword/cursor', _get_crossword_cursor)
warehouse.register('/words/unigram', _get_unigram)
warehouse.register('/words/unigram/anagram_index', _get_unigram_anagram_index)
warehouse.register('/words/unigram/trie', _get_unigram_trie)
| from data import anagram_index, crossword, warehouse
from spec.data.fixtures import tries
def _get_unigram_anagram_index():
return anagram_index.AnagramIndex(warehouse.get('/words/unigram/trie'))
def _get_unigram_trie():
return tries.kitchen_sink()
def _get_crossword():
connection = crossword.init(':memory:')
cursor = connection.cursor()
crossword.add(cursor, 'query', 1, {'ask': 1, 'question': 1})
return connection, cursor
def _get_crossword_connection():
connection, cursor = warehouse.get('/phrases/crossword')
del cursor
return connection
def _get_crossword_cursor():
connection, cursor = warehouse.get('/phrases/crossword')
del connection
return cursor
warehouse.init()
warehouse.register('/phrases/crossword', _get_crossword)
warehouse.register('/phrases/crossword/connection', _get_crossword_connection)
warehouse.register('/phrases/crossword/cursor', _get_crossword_cursor)
warehouse.register('/words/unigram/anagram_index', _get_unigram_anagram_index)
warehouse.register('/words/unigram/trie', _get_unigram_trie)
|
Call Wait() instead of Start() so we wait for the command to finish before output. | package coreutils
import (
"os"
"os/exec"
)
// ExecCommand executes a command with args and returning the stringified output
func ExecCommand(command string, args []string, redirect bool) string {
if ExecutableExists(command) { // If the executable exists
var output []byte
runner := exec.Command(command, args...)
if redirect { // If we should redirect output to var
output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
} else {
runner.Stdout = os.Stdout
runner.Stderr = os.Stderr
runner.Wait()
}
return string(output[:])
} else { // If the executable doesn't exist
return command + " is not an executable."
}
}
// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
_, existsErr := exec.LookPath(executableName)
return (existsErr == nil)
}
| package coreutils
import (
"os"
"os/exec"
)
// ExecCommand executes a command with args and returning the stringified output
func ExecCommand(command string, args []string, redirect bool) string {
if ExecutableExists(command) { // If the executable exists
var output []byte
runner := exec.Command(command, args...)
if redirect { // If we should redirect output to var
output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
} else {
runner.Stdout = os.Stdout
runner.Stderr = os.Stderr
runner.Start()
}
return string(output[:])
} else { // If the executable doesn't exist
return command + " is not an executable."
}
}
// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
_, existsErr := exec.LookPath(executableName)
return (existsErr == nil)
}
|
Complete social ids for wordpress and faa | #
# define overloading of ids for each social site
# to be customized for your accounts
#
#
# flickr
#
def flickr_api_secret():
return ""
def flickr_api_key():
return ""
def flickr_user_id():
return ""
#
# twitter
#
def twitter_consumer_key():
return ""
def twitter_consumer_secret():
return ""
def twitter_access_token():
return ""
def twitter_access_token_secret():
return ""
def twitter_screenname():
return ""
#
# tumblr
#
def tumblr_consumer_key():
return ""
def tumblr_secret_key():
return ""
def tumblr_access_token():
return ""
def tumblr_access_token_secret():
return ""
def tumblr_userid():
return ""
#
# faa
#
def faa_username():
return ""
def faa_password():
return ""
def faa_profile():
return ""
#
# wordpress
#
def wordpress_blogid():
return ""
| #
# define overloading of ids for each social site
# to be customized for your accounts
#
#
# flickr
#
def flickr_api_secret():
return ""
def flickr_api_key():
return ""
def flickr_user_id():
return ""
#
# twitter
#
def twitter_consumer_key():
return ""
def twitter_consumer_secret():
return ""
def twitter_access_token():
return ""
def twitter_access_token_secret():
return ""
def twitter_screenname():
return ""
#
# tumblr
#
def tumblr_consumer_key():
return ""
def tumblr_secret_key():
return ""
def tumblr_access_token():
return ""
def tumblr_access_token_secret():
return ""
def tumblr_userid():
return ""
|
Update patch version ahead of a minor release.
PiperOrigin-RevId: 393332838
Change-Id: I70845f5a679a29f6bd9f497896c5820fd2880df2 | # python3
# Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package metadata for acme.
This is kept in a separate module so that it can be imported from setup.py, at
a time when acme's dependencies may not have been installed yet.
"""
# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '2'
_PATCH_VERSION = '2'
# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
| # python3
# Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package metadata for acme.
This is kept in a separate module so that it can be imported from setup.py, at
a time when acme's dependencies may not have been installed yet.
"""
# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '2'
_PATCH_VERSION = '1'
# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
|
Hide command options that are related to Windows
Signed-off-by: Boaz Shuster <dcfbdecb7964372c22343bdfc0ea59b1d969bfd5@gmail.com> | package client
import (
"fmt"
"github.com/docker/docker/api/types"
"golang.org/x/net/context"
)
// Ping pings the server and returns the value of the "Docker-Experimental", "OS-Type" & "API-Version" headers
func (cli *Client) Ping(ctx context.Context) (types.Ping, error) {
var ping types.Ping
req, err := cli.buildRequest("GET", fmt.Sprintf("%s/_ping", cli.basePath), nil, nil)
if err != nil {
return ping, err
}
serverResp, err := cli.doRequest(ctx, req)
if err != nil {
return ping, err
}
defer ensureReaderClosed(serverResp)
ping.APIVersion = serverResp.header.Get("API-Version")
if serverResp.header.Get("Docker-Experimental") == "true" {
ping.Experimental = true
}
ping.OSType = serverResp.header.Get("OSType")
return ping, nil
}
| package client
import (
"fmt"
"github.com/docker/docker/api/types"
"golang.org/x/net/context"
)
// Ping pings the server and returns the value of the "Docker-Experimental" & "API-Version" headers
func (cli *Client) Ping(ctx context.Context) (types.Ping, error) {
var ping types.Ping
req, err := cli.buildRequest("GET", fmt.Sprintf("%s/_ping", cli.basePath), nil, nil)
if err != nil {
return ping, err
}
serverResp, err := cli.doRequest(ctx, req)
if err != nil {
return ping, err
}
defer ensureReaderClosed(serverResp)
ping.APIVersion = serverResp.header.Get("API-Version")
if serverResp.header.Get("Docker-Experimental") == "true" {
ping.Experimental = true
}
return ping, nil
}
|
Fix typo create_conversion_rates in commands | from django.core.management.base import BaseCommand
from ...tasks import update_conversion_rates, create_conversion_rates
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--all',
action='store_true',
dest='all_currencies',
default=False,
help='Create entries for all currencies')
def handle(self, *args, **options):
if options['all_currencies']:
all_rates = create_conversion_rates()
else:
all_rates = update_conversion_rates()
for conversion_rate in all_rates:
self.stdout.write('%s' % (conversion_rate, ))
| from django.core.management.base import BaseCommand
from ...tasks import update_conversion_rates, create_conversion_dates
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--all',
action='store_true',
dest='all_currencies',
default=False,
help='Create entries for all currencies')
def handle(self, *args, **options):
if options['all_currencies']:
all_rates = create_conversion_dates()
else:
all_rates = update_conversion_rates()
for conversion_rate in all_rates:
self.stdout.write('%s' % (conversion_rate, ))
|
Update cookie definition to use root path | export default class CookieStorage {
constructor(storageName = '_token') {
this.cache = {};
this.storageName = storageName;
}
getItem(key) {
if (this.cache[key]) {
return Promise.resolve(this.cache[key]);
}
const data = this._getCookie();
if (!data[key]) {
return Promise.reject();
}
this.cache[key] = data[key];
return Promise.resolve(data[key]);
}
removeItem(key) {
const data = this._getCookie();
if (!data[key]) {
return Promise.resolve();
}
delete this.cache[key];
delete data[key];
this._setCookie(data);
return Promise.resolve();
}
setItem(key, value) {
const data = this._getCookie();
delete this.cache[key];
data[key] = value;
this._setCookie(data);
return Promise.resolve();
}
_getCookie() {
const data = new RegExp(`(?:^|; )${encodeURIComponent(this.storageName)}=([^;]*)`).exec(document.cookie);
return data ? JSON.parse(decodeURIComponent(data[1])) : {};
}
_setCookie(data) {
document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))};path=/`;
}
}
| export default class CookieStorage {
constructor(storageName = '_token') {
this.cache = {};
this.storageName = storageName;
}
getItem(key) {
if (this.cache[key]) {
return Promise.resolve(this.cache[key]);
}
const data = this._getCookie();
if (!data[key]) {
return Promise.reject();
}
this.cache[key] = data[key];
return Promise.resolve(data[key]);
}
removeItem(key) {
const data = this._getCookie();
if (!data[key]) {
return Promise.resolve();
}
delete this.cache[key];
delete data[key];
this._setCookie(data);
return Promise.resolve();
}
setItem(key, value) {
const data = this._getCookie();
delete this.cache[key];
data[key] = value;
this._setCookie(data);
return Promise.resolve();
}
_getCookie() {
const data = new RegExp(`(?:^|; )${encodeURIComponent(this.storageName)}=([^;]*)`).exec(document.cookie);
return data ? JSON.parse(decodeURIComponent(data[1])) : {};
}
_setCookie(data) {
document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))}`;
}
}
|
Move fs dependency in core dependencies | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
const fs = require('fs');
// Public node modules.
const _ = require('lodash');
module.exports = {
/**
* Upload files.
*
* @param part File extracted from the request body.
* @param ctx
* @returns {*}
*/
upload: function * (part, ctx) {
// Init the promise.
let deferred = Promise.defer();
// Init and format variables.
const promises = [];
const defaultUploadFolder = 'public/upload';
let stream;
ctx = ctx || {};
// Set the filename.
const filename = Date.now().toString() + '-' + (_.kebabCase(part.fileName) || Math.floor(Math.random() * 1000000).toString());
// Start uploading.
stream = fs.createWriteStream(path.join(process.cwd(), strapi.config.upload.folder || defaultUploadFolder, filename));
part.pipe(stream);
// Register the data of the file in the database.
promises.push(File.create(_.merge(part, {
user: ctx.user && ctx.user.id,
originalFilenameFormatted: _.kebabCase(part.fileName),
originalFilename: part.fileName || '',
filename: filename
})));
try {
let files = yield promises;
deferred.resolve(files);
} catch (err) {
strapi.log.error(err);
deferred.reject(err);
}
return deferred.promise;
}
};
| 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
const fs = require('fs');
module.exports = {
/**
* Upload files.
*
* @param part File extracted from the request body.
* @param ctx
* @returns {*}
*/
upload: function * (part, ctx) {
// Init the promise.
let deferred = Promise.defer();
// Init and format variables.
const promises = [];
const defaultUploadFolder = 'public/upload';
let stream;
ctx = ctx || {};
// Set the filename.
const filename = Date.now().toString() + '-' + (_.kebabCase(part.fileName) || Math.floor(Math.random() * 1000000).toString());
// Start uploading.
stream = fs.createWriteStream(path.join(process.cwd(), strapi.config.upload.folder || defaultUploadFolder, filename));
part.pipe(stream);
// Register the data of the file in the database.
promises.push(File.create(_.merge(part, {
user: ctx.user && ctx.user.id,
originalFilenameFormatted: _.kebabCase(part.fileName),
originalFilename: part.fileName || '',
filename: filename
})));
try {
let files = yield promises;
deferred.resolve(files);
} catch (err) {
strapi.log.error(err);
deferred.reject(err);
}
return deferred.promise;
}
};
|
Update zero data column width on desktop. | /**
* Admin Bar Clicks component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const AdminBarZeroData = () => {
return (
<div className="
mdc-layout-grid__cell--span-4-phone
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-12-desktop
">
<div className="googlesitekit-zero-data">
<h3 className="googlesitekit-zero-data__title">No data available yet</h3>
<p className="googlesitekit-zero-data__description">There is no data available for this content yet. This could be because it was recently created or because nobody has accessed it so far.</p>
</div>
</div>
);
};
export default AdminBarZeroData;
| /**
* Admin Bar Clicks component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const AdminBarZeroData = () => {
return (
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-4-phone
mdc-layout-grid__cell--span-8-tablet
mdc-layout-grid__cell--span-10-desktop
">
<div className="googlesitekit-zero-data">
<h3 className="googlesitekit-zero-data__title">No data available yet</h3>
<p className="googlesitekit-zero-data__description">There is no data available for this content yet. This could be because it was recently created or because nobody has accessed it so far.</p>
</div>
</div>
);
};
export default AdminBarZeroData;
|
Change WorkerDirectoryProvider to use GFileUtils.mkdirs() | /*
* Copyright 2017 the original author or 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 org.gradle.process.internal.worker.child;
import org.gradle.initialization.GradleUserHomeDirProvider;
import org.gradle.util.GFileUtils;
import java.io.File;
public class DefaultWorkerDirectoryProvider implements WorkerDirectoryProvider {
private final File gradleUserHomeDir;
public DefaultWorkerDirectoryProvider(GradleUserHomeDirProvider gradleUserHomeDirProvider) {
this.gradleUserHomeDir = gradleUserHomeDirProvider.getGradleUserHomeDirectory();
}
@Override
public File getIdleWorkingDirectory() {
File defaultWorkerDirectory = new File(gradleUserHomeDir, "workers");
if (!defaultWorkerDirectory.exists()) {
GFileUtils.mkdirs(defaultWorkerDirectory);
}
return defaultWorkerDirectory;
}
}
| /*
* Copyright 2017 the original author or 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 org.gradle.process.internal.worker.child;
import org.gradle.initialization.GradleUserHomeDirProvider;
import java.io.File;
public class DefaultWorkerDirectoryProvider implements WorkerDirectoryProvider {
private final File gradleUserHomeDir;
public DefaultWorkerDirectoryProvider(GradleUserHomeDirProvider gradleUserHomeDirProvider) {
this.gradleUserHomeDir = gradleUserHomeDirProvider.getGradleUserHomeDirectory();
}
@Override
public File getIdleWorkingDirectory() {
File defaultWorkerDirectory = new File(gradleUserHomeDir, "workers");
if (!defaultWorkerDirectory.exists() && !defaultWorkerDirectory.mkdirs()) {
throw new IllegalStateException("Unable to create default worker directory at " + defaultWorkerDirectory.getAbsolutePath());
}
return defaultWorkerDirectory;
}
}
|
Fix recovery iteration indexing (start at 0) | package org.spoofax.jsglr2.recovery;
public class RecoveryJob {
public int backtrackChoicePointIndex;
public int offset;
public int iteration;
final int iterationsQuota;
public int quota;
public RecoveryJob(int backtrackChoicePointIndex, int offset, int iterationsQuota) {
this.backtrackChoicePointIndex = backtrackChoicePointIndex;
this.offset = offset;
this.iteration = -1;
this.iterationsQuota = iterationsQuota;
}
boolean hasNextIteration() {
return iteration < iterationsQuota;
}
int nextIteration() {
if(this.backtrackChoicePointIndex > 0)
this.backtrackChoicePointIndex--;
quota = (++iteration + 1);
return iteration;
}
}
| package org.spoofax.jsglr2.recovery;
public class RecoveryJob {
public int backtrackChoicePointIndex;
public int offset;
public int iteration;
final int iterationsQuota;
public int quota;
public RecoveryJob(int backtrackChoicePointIndex, int offset, int iterationsQuota) {
this.backtrackChoicePointIndex = backtrackChoicePointIndex;
this.offset = offset;
this.iteration = 0;
this.iterationsQuota = iterationsQuota;
}
boolean hasNextIteration() {
return iteration < iterationsQuota;
}
int nextIteration() {
if(this.backtrackChoicePointIndex > 0)
this.backtrackChoicePointIndex--;
quota = ++iteration;
return iteration;
}
}
|
Fix proxy URIs with credentials in them | #!/usr/bin/python
"""
Set the firewall to allow access to configured HTTP(S) proxies.
This is only necessary until rBuilder handles the EC2 image posting
and registration process.
"""
import os, sys, urllib, urlparse
from conary.conarycfg import ConaryConfiguration
def main(args):
cfg = ConaryConfiguration(False)
cfg.read('/etc/conaryrc', exception=False)
import epdb;epdb.st()
for schema, uri in cfg.proxy.items():
userhostport = urlparse.urlsplit(uri)[1]
hostport = urllib.splituser(userhostport)[1]
host, port = urllib.splitport(hostport)
if not port:
if schema == 'https':
port = '443'
else:
port = '80'
os.system('/sbin/iptables -A FORWARD-SLAVE -m state --state NEW '
'-m tcp -p tcp --dport %s -d %s -j ACCEPT 2>/dev/null'
% (port, host))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| #!/usr/bin/python
"""
Set the firewall to allow access to configured HTTP(S) proxies.
This is only necessary until rBuilder handles the EC2 image posting
and registration process.
"""
import os, sys, urllib, urlparse
from conary.conarycfg import ConaryConfiguration
def main(args):
cfg = ConaryConfiguration(False)
cfg.read('/etc/conaryrc', exception=False)
for schema, uri in cfg.proxy.items():
hostpart = urlparse.urlsplit(uri)[1]
host, port = urllib.splitport(hostpart)
if not port:
if schema == 'https':
port = '443'
else:
port = '80'
os.system('/sbin/iptables -A FORWARD-SLAVE -m state --state NEW '
'-m tcp -p tcp --dport %s -d %s -j ACCEPT 2>/dev/null'
% (port, host))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Change default development server listen address back to 127.0.0.1 |
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Address for development server to listen on
#HOST = "127.0.0.1"
# Port for development server to listen on
#PORT = 5000
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# File to store the JSON server list data in.
FILENAME = "list.json"
# Amount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet.
# This should only be used to populate the server list after list.json was deleted.
# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
|
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Address for development server to listen on
#HOST = "0.0.0.0"
# Port for development server to listen on
#PORT = 5000
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# File to store the JSON server list data in.
FILENAME = "list.json"
# Amount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet.
# This should only be used to populate the server list after list.json was deleted.
# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
|
Remove comment about importing all plugins
No longer the case | 'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
let app = new EmberAddon(defaults, {
'ember-froala-editor': {
plugins : [
'align','char_counter','colors','emoticons','entities','font_family','font_size',
'line_breaker','link','lists','paragraph_format','special_characters','table','url'
],
languages: false,
themes : true
},
// Use Bootswatch in the "dummy" app
// to resemble the Froala Editor Website
'ember-cli-bootswatch': {
theme: 'materia',
importJS: ['util','collapse']
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
| 'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
let app = new EmberAddon(defaults, {
// Import _all_ Froala Editor files
// for the "dummy" app
'ember-froala-editor': {
plugins : [
'align','char_counter','colors','emoticons','entities','font_family','font_size',
'line_breaker','link','lists','paragraph_format','special_characters','table','url'
],
languages: false,
themes : true
},
// Use Bootswatch in the "dummy" app
// to resemble the Froala Editor Website
'ember-cli-bootswatch': {
theme: 'materia',
importJS: ['util','collapse']
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
Use DefaultRouter instead of SimpleRouter | from django.conf.urls import include, url
from kk.views import (
HearingCommentViewSet, HearingImageViewSet, HearingViewSet, SectionCommentViewSet,
SectionViewSet, UserDataViewSet
)
from rest_framework_nested import routers
router = routers.DefaultRouter()
router.register(r'hearing', HearingViewSet)
router.register(r'users', UserDataViewSet, base_name='users')
hearing_comments_router = routers.NestedSimpleRouter(router, r'hearing', lookup='comment_parent')
hearing_comments_router.register(r'comments', HearingCommentViewSet, base_name='comments')
hearing_child_router = routers.NestedSimpleRouter(router, r'hearing', lookup='hearing')
hearing_child_router.register(r'sections', SectionViewSet, base_name='sections')
hearing_child_router.register(r'images', HearingImageViewSet, base_name='images')
section_comments_router = routers.NestedSimpleRouter(hearing_child_router, r'sections', lookup='comment_parent')
section_comments_router.register(r'comments', SectionCommentViewSet, base_name='comments')
urlpatterns = [
url(r'^', include(router.urls, namespace='v1')),
url(r'^', include(hearing_comments_router.urls, namespace='v1')),
url(r'^', include(hearing_child_router.urls, namespace='v1')),
url(r'^', include(section_comments_router.urls, namespace='v1')),
]
| from django.conf.urls import include, url
from kk.views import (
HearingCommentViewSet, HearingImageViewSet, HearingViewSet, SectionCommentViewSet,
SectionViewSet, UserDataViewSet
)
from rest_framework_nested import routers
router = routers.SimpleRouter()
router.register(r'hearing', HearingViewSet)
router.register(r'users', UserDataViewSet, base_name='users')
hearing_comments_router = routers.NestedSimpleRouter(router, r'hearing', lookup='comment_parent')
hearing_comments_router.register(r'comments', HearingCommentViewSet, base_name='comments')
hearing_child_router = routers.NestedSimpleRouter(router, r'hearing', lookup='hearing')
hearing_child_router.register(r'sections', SectionViewSet, base_name='sections')
hearing_child_router.register(r'images', HearingImageViewSet, base_name='images')
section_comments_router = routers.NestedSimpleRouter(hearing_child_router, r'sections', lookup='comment_parent')
section_comments_router.register(r'comments', SectionCommentViewSet, base_name='comments')
urlpatterns = [
url(r'^', include(router.urls, namespace='v1')),
url(r'^', include(hearing_comments_router.urls, namespace='v1')),
url(r'^', include(hearing_child_router.urls, namespace='v1')),
url(r'^', include(section_comments_router.urls, namespace='v1')),
]
|
Fix HttpResponseException namespace reference in Laravel 5.4.x | <?php
namespace Huntie\JsonApi\Exceptions;
use Huntie\JsonApi\Support\JsonApiErrors;
use Illuminate\Foundation\Application;
use Illuminate\Http\Response;
class_alias(
version_compare(Application::VERSION, '5.4.0', '>=') ?
'Illuminate\Http\Exceptions\HttpResponseException' :
'Illuminate\Http\Exception\HttpResponseException',
__NAMESPACE__ . '\HttpResponseException'
);
class HttpException extends HttpResponseException
{
use JsonApiErrors;
/**
* Create a new HttpException instance.
*
* @param string $message The message for this exception
* @param Response|int|null $response The response object or HTTP status code send to the client
*/
public function __construct($message, $response = null)
{
if (is_null($response)) {
$response = $this->error(Response::HTTP_BAD_REQUEST, $message);
} else if (is_int($response)) {
$response = $this->error($response, $message);
}
parent::__construct($response);
}
}
| <?php
namespace Huntie\JsonApi\Exceptions;
use Huntie\JsonApi\Support\JsonApiErrors;
use Illuminate\Http\Response;
use Illuminate\Http\Exception\HttpResponseException;
class HttpException extends HttpResponseException
{
use JsonApiErrors;
/**
* Create a new HttpException instance.
*
* @param string $message The message for this exception
* @param Response|int|null $response The response object or HTTP status code send to the client
*/
public function __construct($message, $response = null)
{
if (is_null($response)) {
$response = $this->error(Response::HTTP_BAD_REQUEST, $message);
} else if (is_int($response)) {
$response = $this->error($response, $message);
}
parent::__construct($response);
}
}
|
Allow a null start date in search index. | import datetime
from haystack import indexes
from speeches.models import Speech
class SpeechIndex(indexes.SearchIndex, indexes.Indexable):
# Use a template here to include speaker name as well... TODO
text = indexes.CharField(document=True, model_attr='text') # , use_template=True)
title = indexes.CharField() # use_template=True)
start_date = indexes.DateTimeField(model_attr='start_date', null=True)
instance = indexes.CharField(model_attr='instance__label')
speaker = indexes.IntegerField(model_attr='speaker__id', null=True)
def get_model(self):
return Speech
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects # .filter(pub_date__lte=datetime.datetime.now())
| import datetime
from haystack import indexes
from speeches.models import Speech
class SpeechIndex(indexes.SearchIndex, indexes.Indexable):
# Use a template here to include speaker name as well... TODO
text = indexes.CharField(document=True, model_attr='text') # , use_template=True)
title = indexes.CharField() # use_template=True)
start_date = indexes.DateTimeField(model_attr='start_date')
instance = indexes.CharField(model_attr='instance__label')
speaker = indexes.IntegerField(model_attr='speaker__id', null=True)
def get_model(self):
return Speech
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects # .filter(pub_date__lte=datetime.datetime.now())
|
Enforce consistant morph table schema | <?php
declare(strict_types=1);
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTaggablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(config('rinvex.taggable.tables.taggables'), function (Blueprint $table) {
// Columns
$table->integer('tag_id')->unsigned();
$table->morphs('taggable');
$table->timestamps();
// Indexes
$table->unique(['tag_id', 'taggable_id', 'taggable_type'], 'taggables_ids_type_unique');
$table->foreign('tag_id')->references('id')->on(config('rinvex.taggable.tables.tags'))
->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(config('rinvex.taggable.tables.taggables'));
}
}
| <?php
declare(strict_types=1);
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTaggablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(config('rinvex.taggable.tables.taggables'), function (Blueprint $table) {
// Columns
$table->integer('tag_id')->unsigned();
$table->integer('taggable_id')->unsigned();
$table->string('taggable_type');
$table->timestamps();
// Indexes
$table->unique(['tag_id', 'taggable_id', 'taggable_type'], 'taggables_ids_type_unique');
$table->foreign('tag_id')->references('id')->on(config('rinvex.taggable.tables.tags'))
->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(config('rinvex.taggable.tables.taggables'));
}
}
|
Enable URL redirect, disable external data | window.onload = initialize;
var DATAFILE = "research.json";
var DONE_READYSTATE = 4;
var DONE_STATUS = 200;
var OFFICIAL_URL = "http://www.ecst.csuchico.edu/~kbuffardi/";
var OFFICIAL_HOST = "www.ecst.csuchico.edu"
var references = {};
function initialize()
{
validateHost();
//loadExternalData();
}
function validateHost()
{
if( window.location.hostname != OFFICIAL_HOST )
{
window.location.href = OFFICIAL_URL;
}
}
function loadExternalData()
{
var json = new XMLHttpRequest();
json.overrideMimeType("application/json");
//event listener: when json file load is "done"
json.onreadystatechange = function() {
if (this.readyState == DONE_READYSTATE
&& this.status == DONE_STATUS)
{
references=JSON.parse(this.responseText);
console.log(references);
}
}
json.open("GET", DATAFILE);
json.send();
} | window.onload = initialize;
var DATAFILE = "research.json";
var DONE_READYSTATE = 4;
var DONE_STATUS = 200;
var OFFICIAL_URL = "http://www.ecst.csuchico.edu/~kbuffardi/";
var OFFICIAL_HOST = "www.ecst.csuchico.edu"
var references = {};
function initialize()
{
validateHost();
loadExternalData();
}
function validateHost()
{
if( window.location.hostname != OFFICIAL_HOST )
{
window.location.href = OFFICIAL_URL;
}
}
function loadExternalData()
{
var json = new XMLHttpRequest();
json.overrideMimeType("application/json");
//event listener: when json file load is "done"
json.onreadystatechange = function() {
if (this.readyState == DONE_READYSTATE
&& this.status == DONE_STATUS)
{
references=JSON.parse(this.responseText);
console.log(references);
}
}
json.open("GET", DATAFILE);
json.send();
} |
Include the version delta field in AnalyzedCSVExporter
Fix #11 | from django.conf import settings
from osmdata.exporters import CSVExporter
from .models import ActionReport
class AnalyzedCSVExporter(CSVExporter):
""" Enhance CSVExporter adding some fields from diffanalysis module
"""
def get_header_row(self):
return super().get_header_row() + (
'main_tag', 'is_geometric_action', 'is_tag_action',
'added_tags', 'removed_tags', 'modified_tags', 'version_delta')
@staticmethod
def str_list(l):
""" Produce a list of str given a list of anything
"""
return [str(i) for i in l]
def get_row(self, action):
ar = ActionReport.objects.get_or_create_for_action(action)
return super().get_row(action) + (
ar.main_tag,
ar.is_geometric_action,
ar.is_tag_action,
self.str_list(ar.added_tags.all()),
self.str_list(ar.removed_tags.all()),
[self.str_list(i.all())
for i in [ar.modified_tags_old, ar.modified_tags_new]],
ar.version_delta,
)
| from django.conf import settings
from osmdata.exporters import CSVExporter
from .models import ActionReport
class AnalyzedCSVExporter(CSVExporter):
""" Enhance CSVExporter adding some fields from diffanalysis module
"""
def get_header_row(self):
return super().get_header_row() + (
'main_tag', 'is_geometric_action', 'is_tag_action',
'added_tags', 'removed_tags', 'modified_tags')
@staticmethod
def str_list(l):
""" Produce a list of str given a list of anything
"""
return [str(i) for i in l]
def get_row(self, action):
ar = ActionReport.objects.get_or_create_for_action(action)
return super().get_row(action) + (
ar.main_tag,
ar.is_geometric_action,
ar.is_tag_action,
self.str_list(ar.added_tags.all()),
self.str_list(ar.removed_tags.all()),
[self.str_list(i.all())
for i in [ar.modified_tags_old, ar.modified_tags_new]],
)
|
Increment version number to 0.4.1dev | __version__ = '0.4.1dev'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
| __version__ = '0.4.0'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
Remove os.setpgrp() from fake spawner | import os
from jupyterhub.auth import LocalAuthenticator
from jupyterhub.spawner import LocalProcessSpawner
from tornado import gen
class FakeUserAuth(LocalAuthenticator):
"""Authenticate fake users"""
@gen.coroutine
def authenticate(self, handler, data):
"""If the user is on the whitelist, authenticate regardless of password.
If not, then don't authenticate.
"""
username = data['username']
if not self.check_whitelist(username):
return
return username
@staticmethod
def system_user_exists(user):
return True
class FakeUserSpawner(LocalProcessSpawner):
def user_env(self, env):
env['USER'] = self.user.name
env['HOME'] = os.getcwd()
env['SHELL'] = '/bin/bash'
return env
def make_preexec_fn(self, name):
home = os.getcwd()
def preexec():
# start in the cwd
os.chdir(home)
return preexec
| import os
from jupyterhub.auth import LocalAuthenticator
from jupyterhub.spawner import LocalProcessSpawner
from tornado import gen
class FakeUserAuth(LocalAuthenticator):
"""Authenticate fake users"""
@gen.coroutine
def authenticate(self, handler, data):
"""If the user is on the whitelist, authenticate regardless of password.
If not, then don't authenticate.
"""
username = data['username']
if not self.check_whitelist(username):
return
return username
@staticmethod
def system_user_exists(user):
return True
class FakeUserSpawner(LocalProcessSpawner):
def user_env(self, env):
env['USER'] = self.user.name
env['HOME'] = os.getcwd()
env['SHELL'] = '/bin/bash'
return env
def make_preexec_fn(self, name):
home = os.getcwd()
def preexec():
# don't forward signals
os.setpgrp()
# start in the cwd
os.chdir(home)
return preexec
|
Add async attribute to JS | var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script async defer src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
| var components = require('./components');
var javascript = require('../tasks/javascript');
var extend = require('extend');
/**
* Helper function for rendering a page
* Abstracted out here to reduce some duplication in the main server
*/
var renderPage = function(hbs, data) {
return new Promise(function(resolve, reject) {
var pageData = {
pageTitle: data.title + ' - Land Registry pattern library',
assetPath: '/',
homepageUrl: '/',
content: data.content,
scripts: [],
propositionName: 'Land Registry pattern library'
};
// If any of the demos define pageData we need to pop this up onto the page context
extend(pageData, data.pageData);
// Grab all our components, sort them into bundles and then output the
// necessary script tags to load them
components
.getComponents()
.then(javascript.sort)
.then(function(bundles) {
Object.keys(bundles).forEach(function(bundle) {
pageData.scripts.push('<script defer src="/javascripts/' + bundle + '.js"></script>')
});
})
.then(function() {
pageData.scripts = pageData.scripts.join('\n');
})
.then(function() {
resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData));
})
.catch(function(err) {
reject(err);
});
})
}
module.exports = renderPage;
|
Add updated/created and renamed editionset | import { GraphQLID, GraphQLInt, GraphQLObjectType } from "graphql"
import { connectionDefinitions } from "graphql-relay"
import Artwork from "schema/artwork"
import EditionSet from "schema/edition_set"
import { amount } from "schema/fields/money"
import date from "schema/fields/date"
export const OrderLineItemType = new GraphQLObjectType({
name: "OrderLineItem",
fields: () => ({
id: {
type: GraphQLID,
description: "ID of the order line item",
},
artwork: {
type: Artwork.type,
description: "Artwork that is being ordered",
resolve: (
{ artworkId },
_args,
_context,
{ rootValue: { artworkLoader } }
) => artworkLoader(artworkId),
},
editionSet: {
type: EditionSet.type,
description: "Edition set on the artwork",
resolve: ({ editionSetId }) => editionSetId,
},
price: amount(({ priceCents }) => priceCents),
updatedAt: date,
createdAt: date,
quantity: {
type: GraphQLInt,
description: "Quantity of items in this line item",
},
}),
})
export const {
connectionType: OrderLineItemConnection,
edgeType: OrderLineItemEdge,
} = connectionDefinitions({
nodeType: OrderLineItemType,
})
| import { GraphQLID, GraphQLInt, GraphQLObjectType } from "graphql"
import { connectionDefinitions } from "graphql-relay"
import Artwork from "schema/artwork"
import EditionSet from "schema/edition_set"
import { amount } from "schema/fields/money"
export const OrderLineItemType = new GraphQLObjectType({
name: "OrderLineItem",
fields: () => ({
id: {
type: GraphQLID,
description: "ID of the order line item",
},
artwork: {
type: Artwork.type,
description: "Artwork that is being ordered",
resolve: (
{ artworkId },
_args,
_context,
{ rootValue: { artworkLoader } }
) => artworkLoader(artworkId),
},
edition_set: {
type: EditionSet.type,
description: "Edition set on the artwork",
resolve: ({ editionSetId }) => editionSetId,
},
price: amount(({ priceCents }) => priceCents),
quantity: {
type: GraphQLInt,
description: "Quantity of items in this line item",
},
}),
})
export const {
connectionType: OrderLineItemConnection,
edgeType: OrderLineItemEdge,
} = connectionDefinitions({
nodeType: OrderLineItemType,
})
|
Add an ONA_ORG env var
This env var allows it to take the name of the user's Ona organization
Signed-off-by: Njagi Mwaniki <b6a4ba60ad861b9c9afb6daea7294be4be68f44c@urbanslug.com> | const env = process.env;
module.exports = {
// core
environment: env.NODE_ENV || 'development', // dev, prod, test
PORT: env.PORT || env.APP_PORT || 3000, // env to run karma on
defaultLanguage: env.DEFAULT_LANGUAGE || 'en',
conversationTimeout: env.CONVERSATION_TIMEOUT || 120000,
// facebook
facebookPageAccessToken: env.FACEBOOK_PAGE_ACCESS_TOKEN,
facebookAppSecret: env.FACEBOOK_APP_SECRET,
facebookApiVersion: env.FACEBOOK_API_VERSION || 'v2.10',
facebookVerifyToken: env.FACEBOOK_VERIFY_TOKEN || 'karma',
// external data stores
onaOrg: env.ONA_ORG,
onadataApiToken: env.ONADATA_API_TOKEN,
rapidproApiToken: env.RAPIDPRO_API_TOKEN,
rapidproGroups: env.RAPIDPRO_GROUPS ? JSON.parse(env.RAPIDPRO_GROUPS) : [],
// logging and error reporting
sentryDSN: env.SENTRY_DSN,
karmaAccessLogFile: env.KARMA_ACCESS_LOG_FILE || 'bot.access.log',
debugTranslations: env.DEBUG_TRANSLATIONS === 'true' || false,
};
| const env = process.env;
module.exports = {
// core
environment: env.NODE_ENV || 'development', // dev, prod, test
PORT: env.PORT || env.APP_PORT || 3000, // env to run karma on
defaultLanguage: env.DEFAULT_LANGUAGE || 'en',
conversationTimeout: env.CONVERSATION_TIMEOUT || 120000,
// facebook
facebookPageAccessToken: env.FACEBOOK_PAGE_ACCESS_TOKEN,
facebookAppSecret: env.FACEBOOK_APP_SECRET,
facebookApiVersion: env.FACEBOOK_API_VERSION || 'v2.10',
facebookVerifyToken: env.FACEBOOK_VERIFY_TOKEN || 'karma',
// external data stores
onadataApiToken: env.ONADATA_API_TOKEN,
rapidproApiToken: env.RAPIDPRO_API_TOKEN,
rapidproGroups: env.RAPIDPRO_GROUPS ? JSON.parse(env.RAPIDPRO_GROUPS) : [],
// logging and error reporting
sentryDSN: env.SENTRY_DSN,
karmaAccessLogFile: env.KARMA_ACCESS_LOG_FILE || 'bot.access.log',
debugTranslations: env.DEBUG_TRANSLATIONS === 'true' || false,
};
|
Allow feed, rss, and atom prefixes in URL validator. | import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
| import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
Handle links with leading double slashes | function matchAll(str, regex) {
var matches = [];
while (result = regex.exec(str)) {
matches.push(result[1]);
}
return matches;
}
angular.module('reeder.helpers', []).
filter('postDateFormatter', function() {
return function(unformatted_date) {
var date = new Date(unformatted_date);
return moment(date).format('dddd, h:m a');
};
}).
filter('postFormatter', function() {
return function(post) {
var content = post.content;
var regex = /<img.*?src=['|"](.*?)['|"]/gi;
var matches = matchAll(content, regex);
if (matches.length > 0) {
for (i in matches) {
var url = matches[i];
if (!url.match(/^http(s?):/)) {
var new_url = post.feed.site_url;
if (url.substring(0, 2) != '//') {
if (url[0] == '/') new_url += url;
else new_url += '/' + url;
content = content.replace(url, new_url);
}
}
}
}
return content;
}
}); | function matchAll(str, regex) {
var matches = [];
while (result = regex.exec(str)) {
matches.push(result[1]);
}
return matches;
}
angular.module('reeder.helpers', []).
filter('postDateFormatter', function() {
return function(unformatted_date) {
var date = new Date(unformatted_date);
return moment(date).format('dddd, h:m a');
};
}).
filter('postFormatter', function() {
return function(post) {
var content = post.content;
var regex = /<img.*?src=['|"](.*?)['|"]/gi;
var matches = matchAll(content, regex);
if (matches.length > 0) {
for (i in matches) {
var url = matches[i];
if (!url.match(/^http(s?):/)) {
var new_url = post.feed.site_url;
if (url[0] == '/') new_url += url;
else new_url += '/' + url;
content = content.replace(url, new_url);
}
}
}
return content;
}
}); |
Create a new intent for each launching intent | package com.alexstyl.specialdates.addevent.bottomsheet;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
import java.util.List;
final public class IntentResolver {
private final PackageManager packageManager;
public IntentResolver(PackageManager packageManager) {
this.packageManager = packageManager;
}
List<IntentOptionViewModel> createViewModelsFor(Intent intent) {
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
List<IntentOptionViewModel> viewModels = new ArrayList<>(resolveInfos.size());
for (ResolveInfo resolveInfo : resolveInfos) {
Drawable icon = resolveInfo.loadIcon(packageManager);
String label = String.valueOf(resolveInfo.loadLabel(packageManager));
Intent launchingIntent = new Intent(intent.getAction());
launchingIntent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
viewModels.add(new IntentOptionViewModel(icon, label, launchingIntent));
}
return viewModels;
}
}
| package com.alexstyl.specialdates.addevent.bottomsheet;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
import java.util.List;
final public class IntentResolver {
private final PackageManager packageManager;
public IntentResolver(PackageManager packageManager) {
this.packageManager = packageManager;
}
List<IntentOptionViewModel> createViewModelsFor(Intent intent) {
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
List<IntentOptionViewModel> viewModels = new ArrayList<>(resolveInfos.size());
for (ResolveInfo resolveInfo : resolveInfos) {
Drawable icon = resolveInfo.loadIcon(packageManager);
String label = String.valueOf(resolveInfo.loadLabel(packageManager));
viewModels.add(new IntentOptionViewModel(icon, label, intent));
}
return viewModels;
}
}
|
Fix the way to get local ip | package main
import (
"io/ioutil"
"net"
"os"
"regexp"
"strings"
)
var (
newlinePattern = regexp.MustCompile("\r\n|\r|\n")
)
func getLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
ipnet, ok := address.(*net.IPNet)
if !ok {
continue
}
if ipnet.IP.IsLoopback() {
continue
}
if ipnet.IP.To4() == nil {
continue
}
return ipnet.IP.String()
}
return ""
}
func removeWrapperPrefix(str string) (string, bool) {
const prefix = "dor-"
had := strings.HasPrefix(str, prefix)
return strings.TrimPrefix(str, prefix), had
}
func loadHelpFile(file string) (summary, description string) {
f, err := os.Open(file)
if err != nil {
return
}
b, err := ioutil.ReadAll(f)
if err != nil {
return
}
description = string(b[:])
summary = newlinePattern.Split(description, 2)[0]
return
}
| package main
import (
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
)
var (
newlinePattern = regexp.MustCompile("\r\n|\r|\n")
)
func getLocalIP() string {
for _, i := range []string{"en0", "en1", "en2"} {
cmd := exec.Command("ipconfig", "getifaddr", i)
b, err := cmd.Output()
if err != nil {
continue
}
if len(b) > 0 {
return strings.Trim(string(b[:]), "\n")
}
}
return ""
}
func removeWrapperPrefix(str string) (string, bool) {
const prefix = "dor-"
had := strings.HasPrefix(str, prefix)
return strings.TrimPrefix(str, prefix), had
}
func loadHelpFile(file string) (summary, description string) {
f, err := os.Open(file)
if err != nil {
return
}
b, err := ioutil.ReadAll(f)
if err != nil {
return
}
description = string(b[:])
summary = newlinePattern.Split(description, 2)[0]
return
}
|
AGF: Add OIS/OOS to constructor and add fields | package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private ObjectInputStream ois;
private ObjectOutputStream oos;
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame (ObjectInputStream ois, ObjectOutputStream oos) {
// Initialize comms
this.oos = oos;
this.ois = ois;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
| package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* Runs the GUI by which an event administrator can input results.
*
* @author MathSquared
*
*/
public class AdminGuiFrame extends JFrame {
private JPanel contentPane;
/**
* Create the frame.
*/
public AdminGuiFrame () {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
|
Correct the check of use HTTPS in Tornado file. | from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import tornado.options
import server
import os
use_https = False
if use_https:
default_port = 443
else:
default_port = 80
tornado.options.define("port", default=default_port, help="run on the given port", type=int)
# Overwrite the port from the Heroku run from Procfile.
tornado.options.parse_command_line()
appPath = os.path.dirname(os.path.realpath(__file__))
if __name__ == '__main__':
if use_https:
http_server = HTTPServer(WSGIContainer(server.app), ssl_options={
"certfile": appPath + '/ssl.crt',
"keyfile": appPath + '/ssl.key'
})
else:
http_server = HTTPServer(WSGIContainer(server.app))
http_server.listen(tornado.options.options.port)
IOLoop.instance().start() | from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import tornado.options
import server
import os
use_https = False
if use_https:
default_port = 80
else:
default_port = 443
tornado.options.define("port", default=default_port, help="run on the given port", type=int)
# Overwrite the port from the Heroku run from Procfile.
tornado.options.parse_command_line()
appPath = os.path.dirname(os.path.realpath(__file__))
if __name__ == '__main__':
if use_https:
http_server = HTTPServer(WSGIContainer(server.app), ssl_options={
"certfile": appPath + '/ssl.crt',
"keyfile": appPath + '/ssl.key'
})
else:
http_server = HTTPServer(WSGIContainer(server.app))
http_server.listen(tornado.options.options.port)
IOLoop.instance().start() |
Use the same packages for installing with pip and distutils | from setuptools import setup, find_packages
version = '0.1'
setup(name='mamba',
version=version,
description="",
long_description=open('README.md').read(),
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='',
author_email='',
url='',
license='MIT/X11',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[line for line in open('requirements.txt')],
entry_points={
'console_scripts': [
'mamba = mamba.cli:main'
]
})
| from setuptools import setup, find_packages
version = '0.1'
setup(name='mamba',
version=version,
description="",
long_description=open('README.md').read(),
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='',
author_email='',
url='',
license='MIT/X11',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[],
entry_points={
'console_scripts': [
'mamba = mamba.cli:main'
]
})
|
test: Change the info function name | #!/usr/bin/env python3
import sys
import os
import unittest
import libaur.printer as printer
import libaur.aur as aur
class PrinterBadInput(unittest.TestCase):
def test_string_input_dlpkgs(self):
'''download_pkg should fail with string input as first arg'''
self.assertRaises(TypeError, printer.download_pkgs, 'foo',
'/tmp/.pywer_test_suite')
def test_string_input_ppsi(self):
'''pretty_print_simple_info should fail with string input as first arg'''
self.assertRaises(TypeError, printer.pretty_print_info, 'foo')
def test_string_input_ppu(self):
'''pretty_print_updpkgs should fail with string input pkgs arg'''
self.assertRaises(TypeError, printer.pretty_print_updpkgs, pkgs='foo')
# Add a mini-json server so that we can test output as well
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python3
import sys
import os
import unittest
import libaur.printer as printer
import libaur.aur as aur
class PrinterBadInput(unittest.TestCase):
def test_string_input_dlpkgs(self):
'''download_pkg should fail with string input as first arg'''
self.assertRaises(TypeError, printer.download_pkgs, 'foo',
'/tmp/.pywer_test_suite')
def test_string_input_ppsi(self):
'''pretty_print_simple_info should fail with string input as first arg'''
self.assertRaises(TypeError, printer.pretty_print_simple_info, 'foo')
def test_string_input_ppu(self):
'''pretty_print_updpkgs should fail with string input pkgs arg'''
self.assertRaises(TypeError, printer.pretty_print_updpkgs, pkgs='foo')
# Add a mini-json server so that we can test output as well
if __name__ == '__main__':
unittest.main()
|
Webcam: Use log instead of fmt
Signed-off-by: kfei <1da1ad03e627cea4baf20871022464fcc6a4b2c4@kfei.net> | package v4l2
import (
"log"
)
// #include "webcam_wrapper.h"
import "C"
import "unsafe"
var w *C.webcam_t
func OpenWebcam(path string, width, height int) {
dev := C.CString(path)
defer C.free(unsafe.Pointer(dev))
w = C.go_open_webcam(dev, C.int(width), C.int(height))
// The following defer statement introduces a `double free or corruption`
// error since it's already freezed in C:
//
// defer C.free(unsafe.Pointer(w))
// Now open the device
log.Println("Webcam opened")
}
func GrabFrame() []byte {
buf := C.go_grab_frame(w)
result := C.GoBytes(unsafe.Pointer(buf.start), C.int(buf.length))
// Free the buffer (better way for this?)
if unsafe.Pointer(buf.start) != unsafe.Pointer(uintptr(0)) {
C.free(unsafe.Pointer(buf.start))
}
return result
}
func CloseWebcam() {
if C.go_close_webcam(w) == 0 {
log.Println("Webcam closed")
}
}
| package v4l2
import "fmt"
// #include "webcam_wrapper.h"
import "C"
import "unsafe"
var w *C.webcam_t
func OpenWebcam(path string, width, height int) {
dev := C.CString(path)
defer C.free(unsafe.Pointer(dev))
w = C.go_open_webcam(dev, C.int(width), C.int(height))
// The following defer statement introduces a `double free or corruption`
// error since it's already freezed in C:
//
// defer C.free(unsafe.Pointer(w))
// Now open the device
fmt.Println("Webcam opened")
}
func GrabFrame() []byte {
buf := C.go_grab_frame(w)
result := C.GoBytes(unsafe.Pointer(buf.start), C.int(buf.length))
// Free the buffer (better way for this?)
if unsafe.Pointer(buf.start) != unsafe.Pointer(uintptr(0)) {
C.free(unsafe.Pointer(buf.start))
}
return result
}
func CloseWebcam() {
if C.go_close_webcam(w) == 0 {
fmt.Println("Webcam closed")
}
}
|
Fix W1505: Using deprecated method assertEquals() | # -*- coding: utf-8 -*-
from django.urls.base import reverse
from survey.models import Response, Survey
from survey.tests.base_test import BaseTest
class TestConfirmView(BaseTest):
def get_first_response(self, survey_name):
survey = Survey.objects.get(name=survey_name)
responses = Response.objects.filter(survey=survey)
response = responses.all()[0]
url = reverse("survey-confirmation", args=(response.interview_uuid,))
return self.client.get(url)
def test_editable_survey(self):
response = self.get_first_response("Unicode问卷")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "come back and change them")
def test_uneditable_survey(self):
response = self.get_first_response("Test survëy")
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, "come back and change them")
| # -*- coding: utf-8 -*-
from django.urls.base import reverse
from survey.models import Response, Survey
from survey.tests.base_test import BaseTest
class TestConfirmView(BaseTest):
def get_first_response(self, survey_name):
survey = Survey.objects.get(name=survey_name)
responses = Response.objects.filter(survey=survey)
response = responses.all()[0]
url = reverse("survey-confirmation", args=(response.interview_uuid,))
return self.client.get(url)
def test_editable_survey(self):
response = self.get_first_response("Unicode问卷")
self.assertEquals(response.status_code, 200)
self.assertContains(response, "come back and change them")
def test_uneditable_survey(self):
response = self.get_first_response("Test survëy")
self.assertEquals(response.status_code, 200)
self.assertNotContains(response, "come back and change them")
|
Implement system configurations load from file. | import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self.template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self.db_file_path = config['DB']['DB_PATH']
# create tables
self.db_control = DBControl(self.db_file_path)
self.db_control.create_tables()
self.db_control.close_connect()
def insert_article(self, file_path):
self.db_control = DBControl(self.db_file_path)
article = BloArticle(self.template_dir)
article.load_from_file(file_path)
self.db_control.insert_article(article)
self.db_control.close_connect()
| from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, db_file_path, template_dir=""):
self.template_dir = template_dir
# create tables
self.db_file_path = db_file_path
self.db_control = DBControl(self.db_file_path)
self.db_control.create_tables()
self.db_control.close_connect()
def insert_article(self, file_path):
self.db_control = DBControl(self.db_file_path)
article = BloArticle(self.template_dir)
article.load_from_file(file_path)
self.db_control.insert_article(article)
self.db_control.close_connect()
|
Fix the 'base' attribute for ng-apps | <!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="alternate" type="application/rss+xml" title="<?= get_bloginfo('name'); ?> Feed" href="<?= esc_url(get_feed_link()); ?>">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700' rel='stylesheet' type='text/css'>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/dae2ada1-fb62-4216-ab20-8072b137a586.css"/>
<link type="text/css" rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/dist/styles/icons.svg.css"/>
<?php wp_head(); ?>
<?php if (is_page_template('template-timeline.php') || is_page_template('template-stories.php')) {
$parts = explode('/', rtrim($_SERVER['REQUEST_URI'], '/'));
$base = $parts[1];
?>
<base href="/<?php echo $base; ?>/"></base>
<?php } ?>
</head>
| <!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="alternate" type="application/rss+xml" title="<?= get_bloginfo('name'); ?> Feed" href="<?= esc_url(get_feed_link()); ?>">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700' rel='stylesheet' type='text/css'>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/dae2ada1-fb62-4216-ab20-8072b137a586.css"/>
<link type="text/css" rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/dist/styles/icons.svg.css"/>
<?php wp_head(); ?>
<base href="/history/"></base>
</head>
|
Add model definitions for join tables. | package model
import (
"github.com/materials-commons/mcstore/pkg/db/schema"
)
// Groups is a default model for the usergroups table.
var Groups = &rModel{
schema: schema.Group{},
table: "usergroups",
}
// Users is a default model for the users table.
var Users = &rModel{
schema: schema.User{},
table: "users",
}
// Dirs is a default model for the datadirs table.
var Dirs = &rModel{
schema: schema.Directory{},
table: "datadirs",
}
// Files is a default model for the datafiles table
var Files = &rModel{
schema: schema.File{},
table: "datafiles",
}
// Projects is a default model for the projects table
var Projects = &rModel{
schema: schema.Project{},
table: "projects",
}
// Project files
var ProjectFiles = &rModel{
schema: schema.Project2DataFile{},
table: "project2datafile",
}
// Project directories
var ProjectDirs = &rModel{
schema: schema.Project2DataDir{},
table: "project2datadir",
}
// Directory files
var DirFiles = &rModel{
schema: schema.DataDir2DataFile{},
table: "datadir2datafile",
}
| package model
import (
"github.com/materials-commons/mcstore/pkg/db/schema"
)
// Groups is a default model for the usergroups table.
var Groups = &rModel{
schema: schema.Group{},
table: "usergroups",
}
// Users is a default model for the users table.
var Users = &rModel{
schema: schema.User{},
table: "users",
}
// Dirs is a default model for the datadirs table.
var Dirs = &rModel{
schema: schema.Directory{},
table: "datadirs",
}
// DirsDenorm is a default model for the denormalized datadirs_denorm table
var DirsDenorm = &rModel{
schema: schema.DataDirDenorm{},
table: "datadirs_denorm",
}
// Files is a default model for the datafiles table
var Files = &rModel{
schema: schema.File{},
table: "datafiles",
}
// Projects is a default model for the projects table
var Projects = &rModel{
schema: schema.Project{},
table: "projects",
}
|
Change size of donation popup | /*
* Author: Pierre-Henry Soria <hello@ph7cms.com>
* Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
var $validationBox = (function () {
$.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) {
$.colorbox({
width: '100%',
width: '200px',
height: '155px',
speed: 500,
scrolling: false,
html: $(oData).find('#box_block')
})
})
});
$validationBox();
| /*
* Author: Pierre-Henry Soria <hello@ph7cms.com>
* Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
var $validationBox = (function () {
$.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) {
$.colorbox({
width: '100%',
maxWidth: '450px',
maxHeight: '85%',
speed: 500,
scrolling: false,
html: $(oData).find('#box_block')
})
})
});
$validationBox();
|
Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date | """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", either the 'id' string
or the object itself can be used as argument. Similar consideration
holds for lists of id's.
For instance if "photo_id" is expected you can give call the function
with named argument "photo = PhotoObject" or with the id string
"photo_id = id_string".
Author : Alexis Mignon (c)
email : alexis.mignon_at_gmail.com
Date : 05/08/2011
"""
try:
from objects import *
import objects
import upload as Upload
from upload import upload,replace
except Exception, e:
print "Could not all modules"
print type(e), e
from auth import set_auth_handler
from method_call import set_keys,enable_cache,disable_cache
#~ def set_auth_handler(auth_handler):
#~ if isinstance(auth_handler,str):
#~ ah = AuthHandler.load(auth_handler)
#~ set_auth_handler(ah)
#~ else :
#~ objects.AUTH_HANDLER = auth_handler
#~ Upload.AUTH_HANDLER = auth_handler
#~ api.AUTH_HANDLER = auth_handler
| """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", either the 'id' string
or the object itself can be used as argument. Similar consideration
holds for lists of id's.
For instance if "photo_id" is expected you can give call the function
with named argument "photo = PhotoObject" or with the id string
"photo_id = id_string".
Author : Alexis Mignon (c)
email : alexis.mignon_at_gmail.com
Date : 05/08/2011
"""
from objects import *
import objects
from auth import set_auth_handler
import upload as Upload
from upload import upload,replace
from method_call import set_keys,enable_cache,disable_cache
#~ def set_auth_handler(auth_handler):
#~ if isinstance(auth_handler,str):
#~ ah = AuthHandler.load(auth_handler)
#~ set_auth_handler(ah)
#~ else :
#~ objects.AUTH_HANDLER = auth_handler
#~ Upload.AUTH_HANDLER = auth_handler
#~ api.AUTH_HANDLER = auth_handler
|
Move inline comment to class docstring | from flask_assets import Bundle, Environment, Filter
class ConcatFilter(Filter):
"""
Filter that merges files, placing a semicolon between them.
Fixes issues caused by missing semicolons at end of JS assets, for example
with last statement of jquery.pjax.js.
"""
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters=('cssmin','cssrewrite'),
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters=('cssmin','cssrewrite'),
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
Set version number as 0.5.1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 1)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 0)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Support both remote URL styles in gh-deploy. | import subprocess
import os
def gh_deploy(config):
if not os.path.exists('.git'):
print 'Cannot deploy - this directory does not appear to be a git repository'
return
print "Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir']
try:
subprocess.check_call(['ghp-import', '-p', config['site_dir']])
except:
return
# TODO: Also check for CNAME file
url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
url = url.decode('utf-8').strip()
if 'github.com/' in url:
host, path = url.split('github.com/', 1)
else:
host, path = url.split('github.com:', 1)
username, repo = path.split('/', 1)
if repo.endswith('.git'):
repo = repo[:-len('.git')]
url = 'http://%s.github.io/%s' % (username, repo)
print 'Your documentation should shortly be available at: ' + url
| import subprocess
import os
def gh_deploy(config):
if not os.path.exists('.git'):
print 'Cannot deploy - this directory does not appear to be a git repository'
return
print "Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir']
try:
subprocess.check_call(['ghp-import', '-p', config['site_dir']])
except:
return
url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
url = url.decode('utf-8').strip()
host, path = url.split('github.com/', 1)
username, repo = path.split('/', 1)
if repo.endswith('.git'):
repo = repo[:-len('.git')]
print 'Your documentation should shortly be available at: http://%s.github.io/%s' % (username, repo)
|
Modify lldb_suite.py to enable python debugging
Summary:
pudb and pdb interfere with the behavior of the inspect module. calling
`inspect.getfile(inspect.currentframe())` returns a different result
depending on whether or not you're in a debugger. Calling
`os.path.abspath` on the result of `inspect.getfile(...)` normalizes the
result between the two environments.
Patch by Nathan Lanza <lanza@fb.com>
Differential Revision: https://reviews.llvm.org/D49620
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@338923 91177308-0d34-0410-b5e6-96231b3b80d8 | import inspect
import os
import sys
def find_lldb_root():
lldb_root = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
while True:
lldb_root = os.path.dirname(lldb_root)
if lldb_root is None:
return None
test_path = os.path.join(lldb_root, "use_lldb_suite_root.py")
if os.path.isfile(test_path):
return lldb_root
return None
lldb_root = find_lldb_root()
if lldb_root is not None:
import imp
fp, pathname, desc = imp.find_module("use_lldb_suite_root", [lldb_root])
try:
imp.load_module("use_lldb_suite_root", fp, pathname, desc)
finally:
if fp:
fp.close()
| import inspect
import os
import sys
def find_lldb_root():
lldb_root = os.path.dirname(inspect.getfile(inspect.currentframe()))
while True:
lldb_root = os.path.dirname(lldb_root)
if lldb_root is None:
return None
test_path = os.path.join(lldb_root, "use_lldb_suite_root.py")
if os.path.isfile(test_path):
return lldb_root
return None
lldb_root = find_lldb_root()
if lldb_root is not None:
import imp
fp, pathname, desc = imp.find_module("use_lldb_suite_root", [lldb_root])
try:
imp.load_module("use_lldb_suite_root", fp, pathname, desc)
finally:
if fp:
fp.close()
|
Clean up more gingerly on errors.
As a code quality thing in general, unbounded cleanups on error paths are a bad idea. With filesystems that are being tied in pretzel knots, sextuply so.
A more ideal form of this in the future might do some checking for crossing over mount lines, and abort if found, but I'm not actually sure that's possible; I notice git *does* correctly detect bind mount traversals, for example. Something with inspecting proc/mount *should* have the power, modulo really nasty races, I'd think? Future work.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us> | package flak
import (
"os"
"path/filepath"
"github.com/spacemonkeygo/errors"
)
/*
Creates a directory, calls the given function, and removes the dir again afterward.
The created path is handed to the given function (cwd is untouched).
Multiple parent dirs will be created if necessary. These will not be
removed afterwards.
If the function panics, the dir will *not* be removed. (We're using this
in the executor code (n.b. todo refactor it to that package) where mounts
are flying: we strongly want to avoid a recursive remove in case an error
was raised from mount cleanup!)
*/
func WithDir(f func(string), dirs ...string) {
// Mkdirs
if len(dirs) < 1 {
panic(errors.ProgrammerError.New("WithDir must have at least one sub-directory"))
}
tempPath := filepath.Join(dirs...)
err := os.MkdirAll(tempPath, 0755)
if err != nil {
panic(errors.IOError.Wrap(err))
}
// Lambda
f(tempPath)
// Cleanup
// this is intentionally not in a defer or try/finally -- it's critical we *don't* do this for all errors.
// specifically, if there's a placer error? hooooly shit DO NOT proceed on a bunch of deletes;
// in a worst case scenario that placer error might have been failure to remove a bind from the host.
// and that would leave a wormhole straight to hell which we should really NOT pump energy into.
err = os.RemoveAll(tempPath)
if err != nil {
// TODO: we don't want to panic here, more like a debug log entry, "failed to remove tempdir."
// Can accomplish once we add logging.
panic(errors.IOError.Wrap(err))
}
}
| package flak
import (
"os"
"path/filepath"
"github.com/spacemonkeygo/errors"
"github.com/spacemonkeygo/errors/try"
)
// Runs a function with a tempdir, cleaning up afterward.
func WithDir(f func(string), dirs ...string) {
if len(dirs) < 1 {
panic(errors.ProgrammerError.New("Must have at least one sub-folder for tempdir"))
}
tempPath := filepath.Join(dirs...)
// Tempdir wants parent path to exist
err := os.MkdirAll(tempPath, 0755)
if err != nil {
panic(errors.IOError.Wrap(err))
}
try.Do(func() {
f(tempPath)
}).Finally(func() {
err := os.RemoveAll(tempPath)
if err != nil {
// TODO: we don't want to panic here, more like a debug log entry, "failed to remove tempdir."
// Can accomplish once we add logging.
panic(errors.IOError.Wrap(err))
}
}).Done()
}
|
Add constructor to pass data | package com.example.todocloud.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.todocloud.R;
import com.example.todocloud.data.Todo;
import java.util.List;
public class TodoAdapterTest extends RecyclerView.Adapter<TodoAdapterTest.MyViewHolder> {
private List<Todo> todosList;
public TodoAdapterTest(List<Todo> todosList) {
this.todosList = todosList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todo_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Todo todo = todosList.get(position);
holder.title.setText(todo.getTitle());
}
@Override
public int getItemCount() {
return todosList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
}
}
}
| package com.example.todocloud.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.todocloud.R;
import com.example.todocloud.data.Todo;
import java.util.List;
public class TodoAdapterTest extends RecyclerView.Adapter<TodoAdapterTest.MyViewHolder> {
private List<Todo> todosList;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todo_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Todo todo = todosList.get(position);
holder.title.setText(todo.getTitle());
}
@Override
public int getItemCount() {
return todosList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
}
}
}
|
Change game name to Fishy | package nl.github.martijn9612.fishy;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
public class Main extends BasicGame
{
public Main(String gamename)
{
super(gamename);
}
@Override
public void init(GameContainer gc) throws SlickException {}
@Override
public void update(GameContainer gc, int i) throws SlickException {}
@Override
public void render(GameContainer gc, Graphics g) throws SlickException
{
g.drawString("Hello World!", 100, 100);
}
public static void main(String[] args)
{
try
{
AppGameContainer appgc;
appgc = new AppGameContainer(new Main("Fishy"));
appgc.setDisplayMode(640, 480, false);
appgc.start();
}
catch (SlickException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | package nl.github.martijn9612.fishy;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
public class Main extends BasicGame
{
public Main(String gamename)
{
super(gamename);
}
@Override
public void init(GameContainer gc) throws SlickException {}
@Override
public void update(GameContainer gc, int i) throws SlickException {}
@Override
public void render(GameContainer gc, Graphics g) throws SlickException
{
g.drawString("Hello World!", 100, 100);
}
public static void main(String[] args)
{
try
{
AppGameContainer appgc;
appgc = new AppGameContainer(new Main("Simple Slick Game"));
appgc.setDisplayMode(640, 480, false);
appgc.start();
}
catch (SlickException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
Remove unnecessary return in ResponseToObjects | module.exports = ResponseToObjects;
var Transform = require('readable-stream/transform');
var inherits = require('inherits');
var isArray = require('is-array');
/**
* Parse written Livefyre API Responses (strings or objects) into a
* readable stream of objects from response.data
* If data is an array, each item of the array will be emitted separately
* If an error response is written in, emit an error event
*/
function ResponseToObjects(opts) {
opts = opts || {};
opts.objectMode = true;
Transform.call(this, opts);
}
inherits(ResponseToObjects, Transform);
/**
* Required by stream/transform
*/
ResponseToObjects.prototype._transform = function (response, encoding, done) {
var err;
if (typeof response === 'string') {
response = JSON.parse(response);
}
if (response.status === 'error') {
err = new Error('ResponseToObjects transform had an error response written in');
err.response = response;
this.emit('error', err);
return;
}
var data = response.data;
if ( ! data) {
err = new Error('Response has no data');
err.response = response;
this.emit('error', err);
return;
}
if ( ! isArray(data)) {
data = [data];
}
data.forEach(this.push.bind(this));
done();
};
| module.exports = ResponseToObjects;
var Transform = require('readable-stream/transform');
var inherits = require('inherits');
var isArray = require('is-array');
/**
* Parse written Livefyre API Responses (strings or objects) into a
* readable stream of objects from response.data
* If data is an array, each item of the array will be emitted separately
* If an error response is written in, emit an error event
*/
function ResponseToObjects(opts) {
opts = opts || {};
opts.objectMode = true;
return Transform.call(this, opts);
}
inherits(ResponseToObjects, Transform);
/**
* Required by stream/transform
*/
ResponseToObjects.prototype._transform = function (response, encoding, done) {
var err;
if (typeof response === 'string') {
response = JSON.parse(response);
}
if (response.status === 'error') {
err = new Error('ResponseToObjects transform had an error response written in');
err.response = response;
this.emit('error', err);
return;
}
var data = response.data;
if ( ! data) {
err = new Error('Response has no data');
err.response = response;
this.emit('error', err);
return;
}
if ( ! isArray(data)) {
data = [data];
}
data.forEach(this.push.bind(this));
done();
};
|
Move SpanishDefaults out of Language class, for pickle | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...lemmatizerlookup import Lemmatizer
from ...attrs import LANG
from ...util import update_exc
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = dict(TAG_MAP)
stop_words = set(STOP_WORDS)
@classmethod
def create_lemmatizer(cls, nlp=None):
return Lemmatizer(LOOKUP)
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
| # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...language import Language
from ...lemmatizerlookup import Lemmatizer
from ...attrs import LANG
from ...util import update_exc
class Spanish(Language):
lang = 'es'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = dict(TAG_MAP)
stop_words = set(STOP_WORDS)
@classmethod
def create_lemmatizer(cls, nlp=None):
return Lemmatizer(LOOKUP)
__all__ = ['Spanish']
|
Improve the elFinder connector on MediaManager Module | <?php
$elFinderPath = APPDIR .'Modules/MediaManager/Lib/elFinder/';
require $elFinderPath .'elFinderConnector.class.php';
require $elFinderPath .'elFinder.class.php';
require $elFinderPath .'elFinderVolumeDriver.class.php';
require $elFinderPath .'elFinderVolumeLocalFileSystem.class.php';
/**
* Simple function to demonstrate how to control file access using "accessControl" callback.
* This method will disable accessing files/folders starting from '.' (dot)
*
* @param string $attr attribute name (read|write|locked|hidden)
* @param string $path file path relative to volume root directory started with directory separator
* @return bool|null
**/
function access($attr, $path, $data, $volume)
{
return (strpos(basename($path), '.') === 0) // if file/folder begins with '.' (dot)
? ! ($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true
: null; // else elFinder decide it itself
}
// Retrieve the options.
$options = Config::get('elfinder');
// Create a elFinder instance.
$elfinder = new elFinder($options);
// Create a elFinder Connector instance.
$connector = new elFinderConnector($elfinder, true);
// Run the elFinder Connector.
$connector->run();
| <?php
$elFinderPath = APPDIR .'Modules/MediaManager/Lib/elFinder/';
require $elFinderPath .'elFinderConnector.class.php';
require $elFinderPath .'elFinder.class.php';
require $elFinderPath .'elFinderVolumeDriver.class.php';
require $elFinderPath .'elFinderVolumeLocalFileSystem.class.php';
/**
* Simple function to demonstrate how to control file access using "accessControl" callback.
* This method will disable accessing files/folders starting from '.' (dot)
*
* @param string $attr attribute name (read|write|locked|hidden)
* @param string $path file path relative to volume root directory started with directory separator
* @return bool|null
**/
function access($attr, $path, $data, $volume)
{
return (strpos(basename($path), '.') === 0) // if file/folder begins with '.' (dot)
? ! ($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true
: null; // else elFinder decide it itself
}
// Retrieve the options.
$options = Config::get('elfinder');
// Create a elFinder instance.
$elfinder = new \elFinder($options);
$connector = new \elFinderConnector($elfinder, true);
// Run the elFinder Connector.
$connector->run();
|
Fix OAuth integration for all wiki families
Earlier you needed to edit config file to set family to
whatever you were working on, even if you constructed a
Site object referring to other website. This would cause
funky errors about 'Logged in as X, expected None' errors.
Fix by listing almost all the families people will want to
use! | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del custom_path
# Things that should be non-easily-overridable
for fam in (
'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia',
'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity',
'wikidata', 'mediawiki'
):
usernames[fam]['*'] = os.environ['JPY_USER']
del fam
# If OAuth integration is available, take it
if 'CLIENT_ID' in os.environ:
authenticate['*'] = (
os.environ['CLIENT_ID'],
os.environ['CLIENT_SECRET'],
os.environ['ACCESS_KEY'],
os.environ['ACCESS_SECRET']
)
| import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del custom_path
# Things that should be non-easily-overridable
usernames[family]['*'] = os.environ['JPY_USER']
# If OAuth integration is available, take it
if 'CLIENT_ID' in os.environ:
authenticate['*'] = (
os.environ['CLIENT_ID'],
os.environ['CLIENT_SECRET'],
os.environ['ACCESS_KEY'],
os.environ['ACCESS_SECRET']
)
|
Add "name" for filter shop tokens | package com.satispay.protocore.dh;
import com.satispay.protocore.dh.beans.*;
import retrofit2.http.*;
import rx.Observable;
/**
* This interface describes the API exposed for the DH network requests.
*/
public interface DH {
/**
* This method performs the first step of the DH process
*
* @param exchangeRequestBean the bean containing all the information needed to complete the first dh step {@link ExchangeRequestBean}
* @return an Observable that emit the network response
*/
@POST("v2/dh/exchange")
Observable<ExchangeResponseBean> exchange(@Body ExchangeRequestBean exchangeRequestBean);
@POST("v2/dh/challenge")
Observable<DHEncryptedResponseBean> challenge(@Body DHEncryptedRequestBean DHEncryptedRequestBean);
@POST("v2/dh/verify")
Observable<DHEncryptedResponseBean> tokenVerification(@Body DHEncryptedRequestBean tokenVerificationRequestBean);
/********************
* token generation *
********************/
@GET("v2/device_token_recoveries/shops")
Observable<TokenRecoveryResponseBean> tokenRecoveryShopList(@Query("code") String code, @Query("name") String name, @Query("starting_after") String startingAfter);
@POST("v2/device_token_recoveries/shops/{id}/device_tokens")
Observable<Void> tokenRecoverySend(@Path("id") String id, @Body SendTokenRequestBean sendTokenRequestBean);
}
| package com.satispay.protocore.dh;
import com.satispay.protocore.dh.beans.*;
import retrofit2.http.*;
import rx.Observable;
/**
* This interface describes the API exposed for the DH network requests.
*/
public interface DH {
/**
* This method performs the first step of the DH process
*
* @param exchangeRequestBean the bean containing all the information needed to complete the first dh step {@link ExchangeRequestBean}
* @return an Observable that emit the network response
*/
@POST("v2/dh/exchange")
Observable<ExchangeResponseBean> exchange(@Body ExchangeRequestBean exchangeRequestBean);
@POST("v2/dh/challenge")
Observable<DHEncryptedResponseBean> challenge(@Body DHEncryptedRequestBean DHEncryptedRequestBean);
@POST("v2/dh/verify")
Observable<DHEncryptedResponseBean> tokenVerification(@Body DHEncryptedRequestBean tokenVerificationRequestBean);
/********************
* token generation *
********************/
@GET("v2/device_token_recoveries/shops")
Observable<TokenRecoveryResponseBean> tokenRecoveryShopList(@Query("code") String code, @Query("starting_after") String startingAfter);
@POST("v2/device_token_recoveries/shops/{id}/device_tokens")
Observable<Void> tokenRecoverySend(@Path("id") String id, @Body SendTokenRequestBean sendTokenRequestBean);
}
|
Make sure tone 1 is on record of the database | var result = {};
load('./lib/bopomofo_encoder.js');
if (!stringsAreUTF8()) {
throw 'You need UTF-8 enabled SpiderMonkey to do cook the data.';
quit();
}
var line;
while (line = readline()) {
line = line.split(' ');
if (line[1].indexOf('_punctuation_') !== -1) continue;
var str = line[1]
.replace(/([^\u02ca\u02c7\u02cb\u02d9])(\-|$)/g, '$1 $2')
.replace(/\-/g, '');
str = BopomofoEncoder.encode(str);
switch (arguments[0]) {
case 'words':
default:
if (str.length > 1) continue;
break;
case 'phrases':
if (str.length === 1) continue;
break;
}
if (!result[str]) {
result[str] = [];
}
result[str].push([line[0], parseFloat(line[2])]);
}
for (syllables in result) {
result[syllables] = result[syllables].sort(
function(a, b) {
return (b[1] - a[1]);
}
);
}
var jsonStr = JSON.stringify(result).replace(/\],/g, '],\n');
print(jsonStr);
quit(0);
| var result = {};
load('./lib/bopomofo_encoder.js');
if (!stringsAreUTF8()) {
throw 'You need UTF-8 enabled SpiderMonkey to do cook the data.';
quit();
}
var line;
while (line = readline()) {
line = line.split(' ');
if (line[1].indexOf('_punctuation_') !== -1) continue;
var str = BopomofoEncoder.encode(line[1].replace(/\-/g, ''));
switch (arguments[0]) {
case 'words':
default:
if (str.length > 1) continue;
break;
case 'phrases':
if (str.length === 1) continue;
break;
}
if (!result[str]) {
result[str] = [];
}
result[str].push([line[0], parseFloat(line[2])]);
}
for (syllables in result) {
result[syllables] = result[syllables].sort(
function(a, b) {
return (b[1] - a[1]);
}
);
}
var jsonStr = JSON.stringify(result).replace(/\],/g, '],\n');
print(jsonStr);
quit(0);
|
:lipstick: Use correct external link icon | import React, { useState } from 'react';
import { IconExternalLinkSmallOutline } from '@teamleader/ui-icons';
import Box from '../../box';
import Link from '../../link';
import theme from './theme.css';
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
}, callback);
};
const LinkEntity = ({ entityKey, contentState, children }) => {
const [showOpenLinkIcon, setShowOpenLinkIcon] = useState();
const { url } = contentState.getEntity(entityKey).getData();
const openLink = () => {
window.open(url, 'blank');
};
const toggleShowOpenLinkIcon = () => {
setShowOpenLinkIcon(!showOpenLinkIcon);
};
return (
<Box display="inline-block" onMouseEnter={toggleShowOpenLinkIcon} onMouseLeave={toggleShowOpenLinkIcon}>
<Link className={theme['link']} href="" inherit={false} onClick={(event) => event.preventDefault()}>
{children}
</Link>
{showOpenLinkIcon && <IconExternalLinkSmallOutline onClick={openLink} className={theme['icon']} />}
</Box>
);
};
export default {
strategy: findLinkEntities,
component: LinkEntity,
};
| import React, { useState } from 'react';
import { IconChevronRightSmallOutline } from '@teamleader/ui-icons';
import Box from '../../box';
import Link from '../../link';
import theme from './theme.css';
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
}, callback);
};
const LinkEntity = ({ entityKey, contentState, children }) => {
const [showOpenLinkIcon, setShowOpenLinkIcon] = useState();
const { url } = contentState.getEntity(entityKey).getData();
const openLink = () => {
window.open(url, 'blank');
};
const toggleShowOpenLinkIcon = () => {
setShowOpenLinkIcon(!showOpenLinkIcon);
};
return (
<Box display="inline-block" onMouseEnter={toggleShowOpenLinkIcon} onMouseLeave={toggleShowOpenLinkIcon}>
<Link className={theme['link']} href="" inherit={false} onClick={(event) => event.preventDefault()}>
{children}
</Link>
{showOpenLinkIcon && <IconChevronRightSmallOutline onClick={openLink} className={theme['icon']} />}
</Box>
);
};
export default {
strategy: findLinkEntities,
component: LinkEntity,
};
|
Remove duplicate code, leave comment about circular imports | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HASJOB_ENV')
mail = Mail()
mail.init_app(app)
assets = Environment(app)
# Imported here to prevent circular imports
from uploads import configure
from search import configure
uploads.configure()
search.configure()
# Second, setup assets
assets = Environment(app)
js = Bundle('js/libs/jquery-1.5.1.min.js',
'js/libs/jquery.textarea-expander.js',
'js/libs/tiny_mce/jquery.tinymce.js',
'js/libs/jquery.form.js',
'js/scripts.js',
filters='jsmin', output='js/packed.js')
assets.register('js_all', js)
# Third, after config, import the models and views
import hasjob.models
import hasjob.views
if environ.get('HASJOB_ENV') == 'prod':
import hasjob.loghandler
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HASJOB_ENV')
mail = Mail()
mail.init_app(app)
assets = Environment(app)
from uploads import configure
from search import configure
uploads.configure()
search.configure()
# Second, setup assets
assets = Environment(app)
js = Bundle('js/libs/jquery-1.5.1.min.js',
'js/libs/jquery.textarea-expander.js',
'js/libs/tiny_mce/jquery.tinymce.js',
'js/libs/jquery.form.js',
'js/scripts.js',
filters='jsmin', output='js/packed.js')
assets.register('js_all', js)
# Third, after config, import the models and views
import hasjob.models
import hasjob.views
from uploads import configure
from search import configure
uploads.configure()
search.configure()
if environ.get('HASJOB_ENV') == 'prod':
import hasjob.loghandler
|
Add pep8 to build deps | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
|
Fix for the static analysis acceptance test. | import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
| import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
Put sourceMappingURL on a newline
Firefox and IE expect the url to be on its own line and not at the end of an existing line. | var path = require("path");
module.exports = function(bundle){
if(bundle.source.map) {
var filename = path.basename(removePlugin(bundleName(bundle))) + "." +
bundle.buildType;
bundle.source.code += wrap(filename, bundle.buildType);
}
};
var pluginExp = /\..+!$/;
function removePlugin(name) {
return name.replace(pluginExp, "");
}
function bundleName(bundle) {
var name = bundle.name || bundle.bundles[0] || bundle.nodes[0].load.name;
return name .replace("bundles/", "").replace(/\..+!/, "");
}
function wrap(filename, buildType) {
switch(buildType) {
case "css":
return "\n/*# sourceMappingURL=" + filename + ".map */";
default:
return "\n//# sourceMappingURL=" + filename + ".map";
}
}
| var path = require("path");
module.exports = function(bundle){
if(bundle.source.map) {
var filename = path.basename(removePlugin(bundleName(bundle))) + "." +
bundle.buildType;
bundle.source.code += wrap(filename, bundle.buildType);
}
};
var pluginExp = /\..+!$/;
function removePlugin(name) {
return name.replace(pluginExp, "");
}
function bundleName(bundle) {
var name = bundle.name || bundle.bundles[0] || bundle.nodes[0].load.name;
return name .replace("bundles/", "").replace(/\..+!/, "");
}
function wrap(filename, buildType) {
switch(buildType) {
case "css":
return " /*# sourceMappingURL=" + filename + ".map */";
default:
return " //# sourceMappingURL=" + filename + ".map";
}
}
|
Sort stub element type definitions | /*
* Copyright 2015 Marek Kaput
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rustidea.psi.types;
import org.rustidea.stubs.types.*;
public interface RsStubElementTypes {
RsAttributeElementType ATTRIBUTE = RsAttributeElementType.INSTANCE;
RsAttributeItemElementType ATTRIBUTE_ITEM = RsAttributeItemElementType.INSTANCE;
RsAttributeItemListElementType ATTRIBUTE_ITEM_LIST = RsAttributeItemListElementType.INSTANCE;
RsDocElementType DOC = RsDocElementType.INSTANCE;
RsLifetimeElementType LIFETIME = RsLifetimeElementType.INSTANCE;
RsLifetimeTypeParameterElementType LIFETIME_TYPE_PARAMETER = RsLifetimeTypeParameterElementType.INSTANCE;
RsPathComponentElementType PATH_COMPONENT = RsPathComponentElementType.INSTANCE;
RsPathElementType PATH = RsPathElementType.INSTANCE;
RsTypeParameterElementType TYPE_PARAMETER = RsTypeParameterElementType.INSTANCE;
RsTypeParameterListElementType TYPE_PARAMETER_LIST = RsTypeParameterListElementType.INSTANCE;
RsWhereClauseElementType WHERE_CLAUSE = RsWhereClauseElementType.INSTANCE;
}
| /*
* Copyright 2015 Marek Kaput
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rustidea.psi.types;
import org.rustidea.stubs.types.*;
public interface RsStubElementTypes {
RsLifetimeElementType LIFETIME = RsLifetimeElementType.INSTANCE;
RsTypeParameterElementType TYPE_PARAMETER = RsTypeParameterElementType.INSTANCE;
RsLifetimeTypeParameterElementType LIFETIME_TYPE_PARAMETER = RsLifetimeTypeParameterElementType.INSTANCE;
RsTypeParameterListElementType TYPE_PARAMETER_LIST = RsTypeParameterListElementType.INSTANCE;
RsWhereClauseElementType WHERE_CLAUSE = RsWhereClauseElementType.INSTANCE;
RsPathElementType PATH = RsPathElementType.INSTANCE;
RsPathComponentElementType PATH_COMPONENT = RsPathComponentElementType.INSTANCE;
RsDocElementType DOC = RsDocElementType.INSTANCE;
RsAttributeElementType ATTRIBUTE = RsAttributeElementType.INSTANCE;
RsAttributeItemElementType ATTRIBUTE_ITEM = RsAttributeItemElementType.INSTANCE;
RsAttributeItemListElementType ATTRIBUTE_ITEM_LIST = RsAttributeItemListElementType.INSTANCE;
}
|
Fix hashing for Python 3 | try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
if request.user.is_authenticated():
return request.user.username
else:
try:
s = ''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s.encode('utf-8')).hexdigest()
except KeyError:
return None
| try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
if request.user.is_authenticated():
return request.user.username
else:
try:
s = u''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s).hexdigest()
except KeyError:
return None
|
Clarify why test_import is failing under importlib. | """Run Python's standard test suite using importlib.__import__.
Tests known to fail because of assumptions that importlib (properly)
invalidates are automatically skipped if the entire test suite is run.
Otherwise all command-line options valid for test.regrtest are also valid for
this script.
XXX FAILING
test_import
execution bit
file name differing between __file__ and co_filename (r68360 on trunk)
"""
import importlib
import sys
from test import regrtest
if __name__ == '__main__':
__builtins__.__import__ = importlib.__import__
exclude = ['--exclude',
'test_frozen', # Does not expect __loader__ attribute
'test_pkg', # Does not expect __loader__ attribute
'test_pydoc', # Does not expect __loader__ attribute
]
# Switching on --exclude implies running all test but the ones listed, so
# only use it when one is not running an explicit test
if len(sys.argv) == 1:
# No programmatic way to specify tests to exclude
sys.argv.extend(exclude)
regrtest.main(quiet=True, verbose2=True)
| """Run Python's standard test suite using importlib.__import__.
Tests known to fail because of assumptions that importlib (properly)
invalidates are automatically skipped if the entire test suite is run.
Otherwise all command-line options valid for test.regrtest are also valid for
this script.
XXX FAILING
test_import # execution bit, exception name differing, file name differing
between code and module (?)
"""
import importlib
import sys
from test import regrtest
if __name__ == '__main__':
__builtins__.__import__ = importlib.__import__
exclude = ['--exclude',
'test_frozen', # Does not expect __loader__ attribute
'test_pkg', # Does not expect __loader__ attribute
'test_pydoc', # Does not expect __loader__ attribute
]
# Switching on --exclude implies running all test but the ones listed, so
# only use it when one is not running an explicit test
if len(sys.argv) == 1:
# No programmatic way to specify tests to exclude
sys.argv.extend(exclude)
regrtest.main(quiet=True, verbose2=True)
|
Use temp config for add test | package cli
import (
"io/ioutil"
"log"
"os"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
func ExampleAddCommand() {
f, err := ioutil.TempFile("", "aws-config")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name())
os.Setenv("AWS_CONFIG_FILE", f.Name())
os.Setenv("AWS_ACCESS_KEY_ID", "llamas")
os.Setenv("AWS_SECRET_ACCESS_KEY", "rock")
os.Setenv("AWS_VAULT_BACKEND", "file")
os.Setenv("AWS_VAULT_FILE_PASSPHRASE", "password")
defer os.Unsetenv("AWS_ACCESS_KEY_ID")
defer os.Unsetenv("AWS_SECRET_ACCESS_KEY")
defer os.Unsetenv("AWS_VAULT_BACKEND")
defer os.Unsetenv("AWS_VAULT_FILE_PASSPHRASE")
app := kingpin.New(`aws-vault`, ``)
ConfigureGlobals(app)
ConfigureAddCommand(app)
kingpin.MustParse(app.Parse([]string{"add", "--env", "foo"}))
// Output:
// Added credentials to profile "foo" in vault
}
| package cli
import (
"os"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
func ExampleAddCommand() {
os.Setenv("AWS_ACCESS_KEY_ID", "llamas")
os.Setenv("AWS_SECRET_ACCESS_KEY", "rock")
os.Setenv("AWS_VAULT_BACKEND", "file")
os.Setenv("AWS_VAULT_FILE_PASSPHRASE", "password")
defer os.Unsetenv("AWS_ACCESS_KEY_ID")
defer os.Unsetenv("AWS_SECRET_ACCESS_KEY")
defer os.Unsetenv("AWS_VAULT_BACKEND")
defer os.Unsetenv("AWS_VAULT_FILE_PASSPHRASE")
app := kingpin.New(`aws-vault`, ``)
ConfigureGlobals(app)
ConfigureAddCommand(app)
kingpin.MustParse(app.Parse([]string{"add", "--env", "foo"}))
// Output:
// Added credentials to profile "foo" in vault
}
|
Use ConcurrentCopyOnWriteArraySet -- could alternatively provide a Comparator | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;
import com.yahoo.vespa.athenz.api.AthenzService;
import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
*
* @author bjorncs
*/
public class ServiceIdentityProviderListenerHelper {
private final Set<ServiceIdentityProvider.Listener> listeners = new CopyOnWriteArraySet<>();
private final AthenzService identity;
public ServiceIdentityProviderListenerHelper(AthenzService identity) {
this.identity = identity;
}
public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
listeners.add(listener);
}
public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
listeners.remove(listener);
}
public void onCredentialsUpdate(SSLContext sslContext) {
listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
}
public void clearListeners() {
listeners.clear();
}
}
| // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identity;
import com.yahoo.vespa.athenz.api.AthenzService;
import javax.net.ssl.SSLContext;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* A helper class managing {@link ServiceIdentityProvider.Listener} instances for implementations of {@link ServiceIdentityProvider}.
*
* @author bjorncs
*/
public class ServiceIdentityProviderListenerHelper {
private final Set<ServiceIdentityProvider.Listener> listeners = new ConcurrentSkipListSet<>();
private final AthenzService identity;
public ServiceIdentityProviderListenerHelper(AthenzService identity) {
this.identity = identity;
}
public void addIdentityListener(ServiceIdentityProvider.Listener listener) {
listeners.add(listener);
}
public void removeIdentityListener(ServiceIdentityProvider.Listener listener) {
listeners.remove(listener);
}
public void onCredentialsUpdate(SSLContext sslContext) {
listeners.forEach(l -> l.onCredentialsUpdate(sslContext, identity));
}
public void clearListeners() {
listeners.clear();
}
}
|
Fix typo in migration file | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MakeTeamNameNullable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('teams', function (Blueprint $table) {
$table->text('name')->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('teams', function (Blueprint $table) {
$table->text('name')->nullable(false)->change();
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MakeTeamNameNullable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('teams', function (Blueprint $table) {
$table->boolean('name')->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('teams', function (Blueprint $table) {
$table->boolean('name')->nullable(false)->change();
});
}
}
|
Fix application trai doc-tag return | <?php
/**
* Trait for application object handling
*
* @file ApplicationTrait.php
*
* PHP version 5.4+
*
* @author Yancharuk Alexander <alex at itvault dot info>
* @copyright © 2012-2016 Alexander Yancharuk
* @date 2016-10-21 16:44
* @license The BSD 3-Clause License
* <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
*/
namespace Application;
trait ApplicationTrait
{
protected $application;
/**
* Get application object
*
* @return $this
*/
public function getApplication()
{
return $this->application;
}
/**
* Set application
*
* @param mixed $application
*
* @return $this
*/
public function setApplication($application)
{
$this->application = $application;
return $this;
}
}
| <?php
/**
* Trait for application object handling
*
* @file ApplicationTrait.php
*
* PHP version 5.4+
*
* @author Yancharuk Alexander <alex at itvault dot info>
* @copyright © 2012-2016 Alexander Yancharuk
* @date 2016-10-21 16:44
* @license The BSD 3-Clause License
* <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
*/
namespace Application;
trait ApplicationTrait
{
protected $application;
/**
* Get application object
*
* @return mixed
*/
public function getApplication()
{
return $this->application;
}
/**
* Set application
*
* @param mixed $application
*
* @return $this
*/
public function setApplication($application)
{
$this->application = $application;
return $this;
}
}
|
Update the PyPI version to 0.2.10 | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Remove author and category from single posts | <?php while (have_posts()) : the_post() ?>
<article <?php post_class() ?>>
<div class="visible-print">
<p><?php echo esc_html(get_permalink()) ?></p>
</div>
<header>
<h1 class="entry-title"><?php the_title() ?></h1>
<?php get_template_part('templates/entry-meta') ?>
</header>
<div class="entry-content">
<?php the_content() ?>
</div>
<footer class="single">
<p>
<?php echo get_the_tag_list('<p><strong>Tags:</strong> ', ',', '</p>'); ?>
</p>
</footer>
</article>
<?php share_icons(get_the_ID()) ?>
<?php comments_template('/templates/comments.php') ?>
<?php endwhile ?>
| <?php while (have_posts()) : the_post() ?>
<article <?php post_class() ?>>
<div class="visible-print">
<p><?php echo esc_html(get_permalink()) ?></p>
</div>
<header>
<h1 class="entry-title"><?php the_title() ?></h1>
<?php get_template_part('templates/entry-meta') ?>
</header>
<div class="entry-content">
<?php the_content() ?>
</div>
<footer class="single">
<p>
<strong>By:</strong> <?php gds_byline(); ?>
<strong>Category:</strong> <?php echo get_the_category_list(', ') ?>
</p>
<p>
<?php echo get_the_tag_list('<p><strong>Tags:</strong> ', ',', '</p>'); ?>
</p>
</footer>
</article>
<?php share_icons(get_the_ID()) ?>
<?php comments_template('/templates/comments.php') ?>
<?php endwhile ?>
|
Add response if no topics are set | import logging
import time
import os
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
def build_response(message):
topics = ""
for i, j in enumerate(message['Items']):
topics += "{0}: {1}\n".format(i + 1, j['topic'])
if not topics:
topics = "No topics for this date have been set"
return {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": topics
}
}
}
def lookup_discussion_topics(event, context):
#debug print for lex event data
print(event)
table = dynamodb.Table(os.environ['DYNAMODB_TABLE_TOPICS'])
team = event['currentIntent']['slots']['GetTeam']
date = event['currentIntent']['slots']['GetQueryDay']
filter_expression = Key('date').eq(date) & Key('team').eq(team);
response = table.scan(
FilterExpression=filter_expression,
)
print("Query succeeded:")
return build_response(response)
| import logging
import time
import os
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
def build_response(message):
topics = ""
for i, j in enumerate(message['Items']):
topics += "{0}: {1}\n".format(i + 1, j['topic'])
return {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": topics
}
}
}
def lookup_discussion_topics(event, context):
#debug print for lex event data
print(event)
table = dynamodb.Table(os.environ['DYNAMODB_TABLE_TOPICS'])
team = event['currentIntent']['slots']['GetTeam']
date = event['currentIntent']['slots']['GetQueryDay']
filter_expression = Key('date').eq(date) & Key('team').eq(team);
response = table.scan(
FilterExpression=filter_expression,
)
print("Query succeeded:")
return build_response(response)
|
Use the hex representation of the UUID. | from setuptools import setup, find_packages
import os
import os.path as op
import uuid
ver_file = os.path.join('popylar', 'version.py')
with open(ver_file) as f:
exec(f.read())
popylar_path = op.join(op.expanduser('~'), '.popylar')
uid = uuid.uuid1()
fhandle = open(popylar_path, 'a')
fhandle.write(uid.hex)
fhandle.close()
PACKAGES = find_packages()
opts = dict(name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
platforms=PLATFORMS,
version=VERSION,
requires=REQUIRES)
if __name__ == '__main__':
setup(**opts)
| from setuptools import setup, find_packages
import os
import os.path as op
import uuid
ver_file = os.path.join('popylar', 'version.py')
with open(ver_file) as f:
exec(f.read())
popylar_path = op.join(op.expanduser('~'), '.popylar')
uid = uuid.uuid1()
fhandle = open(popylar_path, 'a')
fhandle.write(uid)
fhandle.close()
PACKAGES = find_packages()
opts = dict(name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
platforms=PLATFORMS,
version=VERSION,
requires=REQUIRES)
if __name__ == '__main__':
setup(**opts)
|
Fix package name in entry point | #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
url='https://github.com/guykisel/pre-commit-robotframework-tidy',
version='0.0.1dev0',
author='Guy Kisel',
author_email='guy.kisel@gmail.com',
platforms='any',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent',
],
packages=find_packages('.', exclude=('tests*', 'testing*')),
install_requires=install_requires,
entry_points={
'console_scripts': [
('python-robotframework-tidy = '
'pre_commit_robotframework_tidy.rf_tify:main'),
],
},
)
| #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
url='https://github.com/guykisel/pre-commit-robotframework-tidy',
version='0.0.1dev0',
author='Guy Kisel',
author_email='guy.kisel@gmail.com',
platforms='any',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent',
],
packages=find_packages('.', exclude=('tests*', 'testing*')),
install_requires=install_requires,
entry_points={
'console_scripts': [
'python-robotframework-tidy = pre_commit_hook.rf_tify:main',
],
},
)
|
Delete 'borad_slug' parameter on 'new_comment' url | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
|
Clean up doc updating, make sure collab changes also update markers | import {Step, applyStep} from "./step"
import {nullMap, MapResult} from "./map"
export class TransformResult {
constructor(doc, map = nullMap) {
this.doc = doc
this.map = map
}
}
export class Transform {
constructor(doc) {
this.docs = [doc]
this.steps = []
this.maps = []
}
get doc() {
return this.docs[this.docs.length - 1]
}
get before() {
return this.docs[0]
}
step(step, from, to, pos, param) {
if (typeof step == "string")
step = new Step(step, from, to, pos, param)
let result = applyStep(this.doc, step)
if (result) {
this.steps.push(step)
this.maps.push(result.map)
this.docs.push(result.doc)
}
return result
}
map(pos, bias) {
let deleted = false
for (let i = 0; i < this.maps.length; i++) {
let result = this.maps[i].map(pos, bias)
pos = result.pos
if (result.deleted) deleted = true
}
return new MapResult(pos, deleted)
}
}
| import {Step, applyStep} from "./step"
import {nullMap} from "./map"
export class TransformResult {
constructor(doc, map = nullMap) {
this.doc = doc
this.map = map
}
}
export class Transform {
constructor(doc) {
this.docs = [doc]
this.steps = []
this.maps = []
}
get doc() {
return this.docs[this.docs.length - 1]
}
get before() {
return this.docs[0]
}
step(step, from, to, pos, param) {
if (typeof step == "string")
step = new Step(step, from, to, pos, param)
let result = applyStep(this.doc, step)
if (result) {
this.steps.push(step)
this.maps.push(result.map)
this.docs.push(result.doc)
}
return result
}
map(pos, bias = 0) {
for (let i = 0; i < this.maps.length; i++)
pos = this.maps[i].map(pos, bias).pos
return pos
}
}
|
Fix dependencies: zeit.workflow is contained in the zeit.cms egg | # Copyright (c) 2011 gocept gmbh & co. kg
# See also LICENSE.txt
from setuptools import setup, find_packages
setup(
name='zeit.content.video',
version='2.0.5dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.content.video',
description="""\
""",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='gocept proprietary',
namespace_packages=['zeit', 'zeit.content'],
install_requires=[
'gocept.form',
'gocept.selenium',
'grokcore.component',
'lxml',
'pytz',
'setuptools',
'zeit.cms>=1.51.1dev',
'zeit.connector',
'zeit.solr',
'zope.annotation',
'zope.app.zcmlfiles',
'zope.component',
'zope.dublincore',
'zope.formlib',
'zope.interface',
'zope.schema',
'zope.traversing',
],
)
| # Copyright (c) 2011 gocept gmbh & co. kg
# See also LICENSE.txt
from setuptools import setup, find_packages
setup(
name='zeit.content.video',
version='2.0.5dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.content.video',
description="""\
""",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='gocept proprietary',
namespace_packages=['zeit', 'zeit.content'],
install_requires=[
'gocept.form',
'gocept.selenium',
'grokcore.component',
'lxml',
'pytz',
'setuptools',
'zeit.cms>=1.51.1dev',
'zeit.connector',
'zeit.solr',
'zeit.workflow',
'zope.annotation',
'zope.app.zcmlfiles',
'zope.component',
'zope.dublincore',
'zope.formlib',
'zope.interface',
'zope.schema',
'zope.traversing',
],
)
|
[applicaiton] Fix selector bug in unmounting component. | "use strict";
/*global document*/
var React = require('react');
/**
* Map containing all the mounted components.
* @type {Object}
*/
var mountedComponents = {};
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A selector on a DOM node.
* @param {object} options - Options for the component rendering.
* @return {undefined} - Return nothing.
*/
module.exports = function(component, selector, options){
options = options || {};
//Unmount component if there is one mounted.
if(mountedComponents[selector]){
React.unmountComponentAtNode(document.querySelector(selector));
console.log('component unmounted');
}
React.render(
React.createElement(component, options.props, options.data),
document.querySelector(selector)
);
//Save the fact that a comonent is mounted.
mountedComponents[selector] = true;
console.log('Mounted components : ', mountedComponents);
};
| "use strict";
/*global document*/
var React = require('react');
/**
* Map containing all the mounted components.
* @type {Object}
*/
var mountedComponents = {};
/**
* Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector - A selector on a DOM node.
* @param {object} options - Options for the component rendering.
* @return {undefined} - Return nothing.
*/
module.exports = function(component, selector, options){
options = options || {};
//Unmount component if there is one mounted.
if(mountedComponents[selector]){
React.unmountComponentAtNode(document.getElementById(selector));
console.log('component unmounted');
}
React.render(
React.createElement(component, options.props, options.data),
document.querySelector(selector)
);
//Save the fact that a comonent is mounted.
mountedComponents[selector] = true;
console.log('Mounted components : ', mountedComponents);
};
|
Use a closure and remove the close link. | (function($) {
$("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'></div></div>");
$("head").append("<link href='http://github.com/plus2/uat_director/raw/master/lib/uat_director/stylesheets/uat_director.css' media='screen' rel='stylesheet' type='text/css'>");
$(function() {
$("#uat-bar a.go").click(function() {
$.ajax({
url: '/uat_director',
success: function(response) {
$(".pop-over").append(response);
$(".pop-over").slideDown();
}
});
});
$("#uat-bar a.close").click(function() {
$(".pop-over").slideUp(function() {
$(".pop-over ol").remove();
});
});
});
})(jQuery);
| $("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'><a class='close' href='#'>close</a></div></div>");
$("head").append("<link href='http://github.com/plus2/uat_director/raw/master/lib/uat_director/stylesheets/uat_director.css' media='screen' rel='stylesheet' type='text/css'>");
$(function() {
$("#uat-bar a.go").click(function() {
$.ajax({
url: '/uat_director',
success: function(response) {
$(".pop-over").append(response);
$(".pop-over").slideDown();
}
});
});
$("#uat-bar a.close").click(function() {
$(".pop-over").slideUp(function() {
$(".pop-over ol").remove();
});
});
});
|
Remove delay when responding to messages
Not needed anymore.
Fixes #123 | """Handles message receiving for GroupMe provider."""
import logging
import json
import time
import flask
from c3po.provider.groupme import send
APP = flask.Flask(__name__)
APP.config['DEBUG'] = True
SUCCESS = ('', 200)
@APP.route('/groupme/<bot_id>', methods=['POST'])
def receive_message(bot_id):
"""Processes a message and returns a response."""
logging.info("Request data: %s", flask.request.data)
msg_data = json.loads(flask.request.data)
group_id = msg_data['group_id']
name = msg_data['name']
text = msg_data['text']
time_sent = float(msg_data['created_at'])
picture_url = None
attachments = msg_data['attachments']
if attachments:
if attachments[0]['type'] == 'image':
picture_url = attachments[0]['url']
if not bot_id or not group_id or not name or (not text and not picture_url):
flask.abort(400)
logging.info("Group ID: %s", group_id)
logging.info("Name: %s", name)
logging.info("Text: %s", text)
msg = send.GroupmeMessage(bot_id, name, picture_url, text, time_sent)
if name == msg.settings.bot_name:
logging.info("Ignoring request since it's coming from the bot.")
return SUCCESS
msg.process_message()
return SUCCESS
| """Handles message receiving for GroupMe provider."""
import logging
import json
import time
import flask
from c3po.provider.groupme import send
APP = flask.Flask(__name__)
APP.config['DEBUG'] = True
SUCCESS = ('', 200)
@APP.route('/groupme/<bot_id>', methods=['POST'])
def receive_message(bot_id):
"""Processes a message and returns a response."""
time.sleep(.1)
logging.info("Request data: %s", flask.request.data)
msg_data = json.loads(flask.request.data)
group_id = msg_data['group_id']
name = msg_data['name']
text = msg_data['text']
time_sent = float(msg_data['created_at'])
picture_url = None
attachments = msg_data['attachments']
if attachments:
if attachments[0]['type'] == 'image':
picture_url = attachments[0]['url']
if not bot_id or not group_id or not name or (not text and not picture_url):
flask.abort(400)
logging.info("Group ID: %s", group_id)
logging.info("Name: %s", name)
logging.info("Text: %s", text)
msg = send.GroupmeMessage(bot_id, name, picture_url, text, time_sent)
if name == msg.settings.bot_name:
logging.info("Ignoring request since it's coming from the bot.")
return SUCCESS
msg.process_message()
return SUCCESS
|
Fix instrument does not exist for id bug in survey launch receiver | package org.adaptlab.chpir.android.survey.Receivers;
import org.adaptlab.chpir.android.survey.SurveyActivity;
import org.adaptlab.chpir.android.survey.SurveyFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class SurveyLaunchReceiver extends BroadcastReceiver {
private static final String TAG = "SurveyLaunchReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Long instrumentId = intent.getLongExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, -1);
Log.i(TAG, "Received broadcast to launch survey for instrument with remote id " + instrumentId);
if (instrumentId > -1) {
Intent i = new Intent(context, SurveyActivity.class);
i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
} | package org.adaptlab.chpir.android.survey.Receivers;
import org.adaptlab.chpir.android.survey.SurveyActivity;
import org.adaptlab.chpir.android.survey.SurveyFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class SurveyLaunchReceiver extends BroadcastReceiver {
private static final String TAG = "SurveyLaunchReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Long instrumentId = intent.getLongExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, -1);
Log.i(TAG, "Received broadcast to launch survey for instrument with remote id " + instrumentId);
Intent i = new Intent(context, SurveyActivity.class);
i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
} |
Update default target to 10 | <?php
use Illuminate\Database\Migrations\Migration;
class AddDefaultTarget extends Migration
{
protected $tableName;
protected $keyColumn;
protected $valueColumn;
public function __construct()
{
$this->tableName = Config::get('settings.table');
$this->keyColumn = Config::get('settings.keyColumn');
$this->valueColumn = Config::get('settings.valueColumn');
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table($this->tableName)->updateOrInsert([
$this->keyColumn => 'target',
], [
$this->valueColumn => 10,
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table($this->tableName)->where($this->keyColumn, 'target')->delete();
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
class AddDefaultTarget extends Migration
{
protected $tableName;
protected $keyColumn;
protected $valueColumn;
public function __construct()
{
$this->tableName = Config::get('settings.table');
$this->keyColumn = Config::get('settings.keyColumn');
$this->valueColumn = Config::get('settings.valueColumn');
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table($this->tableName)->updateOrInsert([
$this->keyColumn => 'target',
], [
$this->valueColumn => 0,
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table($this->tableName)->where($this->keyColumn, 'target')->delete();
}
}
|
Add rAF and rIC to jsdom browser globals | const { JSDOM } = require('jsdom');
function getBrowserGlobals(html) {
const dom = new JSDOM(html);
const { window } = dom;
const noop = function noop() {};
const EventSource = noop;
const navigator = {
userAgent: 'loki',
};
let localStorageData = {};
const localStorage = {
setItem(id, val) {
localStorageData[id] = String(val);
},
getItem(id) {
return localStorageData[id] ? localStorageData[id] : undefined;
},
removeItem(id) {
delete localStorageData[id];
},
clear() {
localStorageData = {};
},
};
const matchMedia = () => ({ matches: true });
const globals = Object.assign({}, window, {
navigator,
localStorage,
matchMedia,
EventSource,
requestAnimationFrame: noop,
requestIdleCallback: noop,
console: {
log: noop,
warn: noop,
error: noop,
},
});
globals.window = globals;
globals.global = globals;
return globals;
}
module.exports = getBrowserGlobals;
| const { JSDOM } = require('jsdom');
function getBrowserGlobals(html) {
const dom = new JSDOM(html);
const { window } = dom;
const noop = function noop() {};
const EventSource = noop;
const navigator = {
userAgent: 'loki',
};
let localStorageData = {};
const localStorage = {
setItem(id, val) {
localStorageData[id] = String(val);
},
getItem(id) {
return localStorageData[id] ? localStorageData[id] : undefined;
},
removeItem(id) {
delete localStorageData[id];
},
clear() {
localStorageData = {};
},
};
const matchMedia = () => ({ matches: true });
window.EventSource = EventSource;
const globals = Object.assign({}, window, {
navigator,
localStorage,
matchMedia,
EventSource,
setInterval: noop,
console: {
log: noop,
warn: noop,
error: noop,
},
});
globals.global = globals;
return globals;
}
module.exports = getBrowserGlobals;
|
Select the message text in twilio | from flask import request
import requests
from ..utils.status import get_status
from ..utils.reminders import create_reminder
import twilio.twiml
import json
import dateutil
def call():
resp = twilio.twiml.Response()
resp.record(timeout=10, transcribe=True,
transcribeCallback='http://queri.me/rec', )
return str(resp)
def text():
b = request.form.get('Body','')
phone = request.form.get('From','')
wit = requests.get('https://api.wit.ai/message?v=20140905&q=%s' % b, headers={'Authorization':'Bearer L3VB34V6YTDFO4BRXNDQNAYMVOOF4BHB'}).text
intent = json.loads(wit)['outcomes'][0]['intent']
print json.loads(wit)
if intent == 'get_status':
m = get_status(wit, phone)
elif intent == 'remind':
entities = json.loads(wit)['outcomes'][0]['entities']
date = dateutil.parser.parse(entities['time'][0]['value']['from'])
text = entities['message'][0]['value']
m = create_reminder(date, text, phone)
else:
m = "Hmm? Try again please :("
# Send to wit.ai for processing
resp = twilio.twiml.Response()
resp.message(m)
return str(resp)
def rec():
print request.form.get('TranscriptionText','')
return ''
| from flask import request
import requests
from ..utils.status import get_status
from ..utils.reminders import create_reminder
import twilio.twiml
import json
import dateutil
def call():
resp = twilio.twiml.Response()
resp.record(timeout=10, transcribe=True,
transcribeCallback='http://queri.me/rec', )
return str(resp)
def text():
b = request.form.get('Body','')
phone = request.form.get('From','')
wit = requests.get('https://api.wit.ai/message?v=20140905&q=%s' % b, headers={'Authorization':'Bearer L3VB34V6YTDFO4BRXNDQNAYMVOOF4BHB'}).text
intent = json.loads(wit)['outcomes'][0]['intent']
print json.loads(wit)
if intent == 'get_status':
m = get_status(wit, phone)
elif intent == 'remind':
entities = json.loads(wit)['outcomes'][0]['entities']
date = dateutil.parser.parse(entities['time'][0]['value']['from'])
text = entities['message']
m = create_reminder(date, text, phone)
else:
m = "Hmm? Try again please :("
# Send to wit.ai for processing
resp = twilio.twiml.Response()
resp.message(m)
return str(resp)
def rec():
print request.form.get('TranscriptionText','')
return ''
|
Revert the extension table reservation | let db;
try {
db = require("rethinkdbdash")(require("./config.json").connectionOpts);
} catch (err) {
console.error("You haven't installed rethinkdbdash npm module or you don't have configured the bot yet! Please do so.");
}
(async function () {
if (!db) return;
const dbs = await db.tableList();
if (!dbs.includes("blacklist")) await db.tableCreate("blacklist");
if (!dbs.includes("session")) await db.tableCreate("session");
if (!dbs.includes("configs")) await db.tableCreate("configs");
if (!dbs.includes("feedback")) await db.tableCreate("feedback");
if (!dbs.includes("tags")) await db.tableCreate("tags");
if (!dbs.includes("profile")) await db.tableCreate("profile");
if (!dbs.includes("modlog")) await db.tableCreate("modlog");
return console.log("All set up!");
})(); | let db;
try {
db = require("rethinkdbdash")(require("./config.json").connectionOpts);
} catch (err) {
console.error("You haven't installed rethinkdbdash npm module or you don't have configured the bot yet! Please do so.");
}
(async function () {
if (!db) return;
const dbs = await db.tableList();
if (!dbs.includes("blacklist")) await db.tableCreate("blacklist");
if (!dbs.includes("session")) await db.tableCreate("session");
if (!dbs.includes("configs")) await db.tableCreate("configs");
if (!dbs.includes("feedback")) await db.tableCreate("feedback");
if (!dbs.includes("tags")) await db.tableCreate("tags");
if (!dbs.includes("profile")) await db.tableCreate("profile");
if (!dbs.includes("modlog")) await db.tableCreate("modlog");
if (!dbs.includes("extensions")) await db.tableCreate("extensions");
return console.log("All set up!");
})(); |
Raise an error in __get() | <?php
namespace WPMissing;
class Post {
function __construct($id) {
$this->_post = get_post($id);
$this->id = (int)$this->_post->ID;
}
function __get($name) {
switch ($name) {
case 'title':
return get_the_title($this->id);
break;
case 'html_content':
global $post;
$old_post = $post;
setup_postdata(get_post($this->_post));
$return = get_the_content();
$post = $old_post;
return $return;
break;
}
$trace = debug_backtrace();
trigger_error(sprintf('Undefined property via __get(): %s in %s on line %s'), $name, $trace[0]['file'], $trace[0]['line'], E_USER_ERROR);
return null;
}
}
| <?php
namespace WPMissing;
class Post {
function __construct($id) {
$this->_post = get_post($id);
$this->id = (int)$this->_post->ID;
}
function __get($name) {
switch ($name) {
case 'id':
return $this->id;
break;
case 'title':
return get_the_title($this->id);
break;
case 'html_content':
global $post;
$old_post = $post;
setup_postdata(get_post($this->_post));
$return = get_the_content();
$post = $old_post;
return $return;
break;
}
return null;
}
}
|
Update http status code when creating a new message | import presenter from '../../presenter/message';
import messageRepository from '../../repository/message';
import * as message from '../../services/message';
export async function list (req, res) {
res.send(
200,
presenter(
await message.list(
getRepositories()
)
)
);
}
export async function create (req, res) {
res.send(
201,
presenter(
await message.create(
getRepositories(),
req.body,
)
)
);
}
export async function detail (req, res) {
res.send(
200,
presenter(
await message.detail(
getRepositories(),
req.params.id,
)
)
);
}
export async function update (req, res) {
req.body.id = req.params.id; // eslint-disable-line no-param-reassign
res.send(
200,
presenter(
await message.update(
getRepositories(),
req.body,
)
)
);
}
export async function remove (req, res) {
res.send(
200,
presenter(
await message.remove(
getRepositories(),
req.params.id,
)
)
);
}
function getRepositories () {
return {
message: messageRepository(),
};
}
| import presenter from '../../presenter/message';
import messageRepository from '../../repository/message';
import * as message from '../../services/message';
export async function list (req, res) {
res.send(
200,
presenter(
await message.list(
getRepositories()
)
)
);
}
export async function create (req, res) {
res.send(
200,
presenter(
await message.create(
getRepositories(),
req.body,
)
)
);
}
export async function detail (req, res) {
res.send(
200,
presenter(
await message.detail(
getRepositories(),
req.params.id,
)
)
);
}
export async function update (req, res) {
req.body.id = req.params.id; // eslint-disable-line no-param-reassign
res.send(
200,
presenter(
await message.update(
getRepositories(),
req.body,
)
)
);
}
export async function remove (req, res) {
res.send(
200,
presenter(
await message.remove(
getRepositories(),
req.params.id,
)
)
);
}
function getRepositories () {
return {
message: messageRepository(),
};
}
|
Use the HttpResponseRedirect for redirection. | from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return HttpResponseRedirect("%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"]))
| from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return "%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.