text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change str method for unknow user | from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
activation_code = models.CharField(max_length=255, default="0000")
fcm_registration_id = models.CharField(max_length=255, blank=True)
def __str__(self):
if self.user:
if self.fcm_registration_id:
return '%s - profile with activated mobile app.' % self.user.username
else:
return '%s - profile.' % self.user.username
else:
return 'Profile with unknown user'
| from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
activation_code = models.CharField(max_length=255, default="0000")
fcm_registration_id = models.CharField(max_length=255, blank=True)
def __str__(self):
if self.user:
if self.fcm_registration_id:
return '%s - profile with activated mobile app.' % self.user.username
else:
return '%s - profile.' % self.user.username
else:
return 'Profile unknown user'
|
Revise output vertex_distances_d to shortest_path_d | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from ds_binary_heap_tuple import BinaryHeap
def dijkstra(weighted_graph_d, start_vertex):
inf = float('inf')
shortest_path_d = {
vertex: inf for vertex in weighted_graph_d
}
shortest_path_d[start_vertex] = 0
bh = BinaryHeap()
# TODO: Continue Dijkstra's algorithm.
def main():
weighted_graph_d = {
'u': {'v': 2, 'w': 5, 'x': 1},
'v': {'u': 2, 'w': 3, 'x': 2},
'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5},
'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1},
'y': {'w': 1, 'x': 1, 'z': 1},
'z': {'w': 5, 'y': 1}
}
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from ds_binary_heap_tuple import BinaryHeap
def dijkstra(weighted_graph_d, start_vertex):
inf = float('inf')
vertex_distances_d = {
vertex: inf for vertex in weighted_graph_d
}
vertex_distances_d[start_vertex] = 0
bh = BinaryHeap()
# TODO: Continue Dijkstra's algorithm.
def main():
weighted_graph_d = {
'u': {'v': 2, 'w': 5, 'x': 1},
'v': {'u': 2, 'w': 3, 'x': 2},
'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5},
'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1},
'y': {'w': 1, 'x': 1, 'z': 1},
'z': {'w': 5, 'y': 1}
}
if __name__ == '__main__':
main()
|
Remove question regarding scope in functions | var data = {
"title": "Funktioner",
"questions": [
{
"description": "När en tupel skickas som argument till en funktion skickas en",
"alternatives": ["Kopia", "Referens"],
"answer": "Referens"
}, {
"description": "När ett heltal skickas som argument till en funktion skickas en",
"alternatives": ["Kopia", "Referens"],
"answer": "Kopia"
}, {
"description": "Kan en funktion A komma åt en lokal variabel i en annan funktion B om en referens till variabeln ej skickats som parameter?",
"alternatives": ["Ja", "Nej", "Endast om A är en inre funktion till B"],
"answer": "Endast om A är en inre funktion till B"
}
]
}
| var data = {
"title": "Funktioner",
"questions": [
{
"description": "När en tupel skickas som argument till en funktion skickas en",
"alternatives": ["Kopia", "Referens"],
"answer": "Referens"
}, {
"description": "När ett heltal skickas som argument till en funktion skickas en",
"alternatives": ["Kopia", "Referens"],
"answer": "Kopia"
}, {
"description": "Kan en funktion A komma åt en lokal variabel i en annan funktion B om en referens till variabeln ej skickats som parameter?",
"alternatives": ["Ja", "Nej", "Endast om A är en inre funktion till B"],
"answer": "Endast om A är en inre funktion till B"
}, {
"description": "Finns två variabler med olika namn men på olika nivåer kan du aldrig veta vilken som kommer användas",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}
]
}
|
Add default drop item string to prevent NPE | package dmillerw.quadrum.common.lib.data;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.item.Item;
import net.minecraft.util.MathHelper;
import java.util.Random;
/**
* @author dmillerw
*/
public class Drop {
private static Random random = new Random();
private Item dropItem;
public String item = "";
public int damage = 0;
public String amount = "1";
public Item getDrop() {
if (dropItem == null) {
dropItem = GameData.getItemRegistry().getRaw(item);
}
return dropItem;
}
public int getDropAmount() {
if (!amount.contains("-")) {
return Integer.parseInt(amount);
} else {
int low = Integer.parseInt(amount.substring(0, amount.indexOf("-")));
int high = Integer.parseInt(amount.substring(amount.indexOf("-") + 1, amount.length()));
return MathHelper.getRandomIntegerInRange(random, low, high);
}
}
}
| package dmillerw.quadrum.common.lib.data;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.item.Item;
import net.minecraft.util.MathHelper;
import java.util.Random;
/**
* @author dmillerw
*/
public class Drop {
private static Random random = new Random();
private Item dropItem;
public String item;
public int damage = 0;
public String amount = "1";
public Item getDrop() {
if (dropItem == null) {
dropItem = GameData.getItemRegistry().getRaw(item);
}
return dropItem;
}
public int getDropAmount() {
if (!amount.contains("-")) {
return Integer.parseInt(amount);
} else {
int low = Integer.parseInt(amount.substring(0, amount.indexOf("-")));
int high = Integer.parseInt(amount.substring(amount.indexOf("-") + 1, amount.length()));
return MathHelper.getRandomIntegerInRange(random, low, high);
}
}
}
|
[Join] Check if we're already in the channel; Improved parameter parsing | from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsLength < 1:
replytext = "Please provide a channel for me to join"
else:
channel = message.messageParts[0].lower()
if channel.startswith('#'):
channel = channel.lstrip('#')
if '#' + channel in message.bot.channelsUserList:
replytext = "I'm already there, waiting for you. You're welcome!"
elif channel not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress):
replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission"
else:
replytext = "All right, I'll go to #{}. See you there!".format(channel)
message.bot.join(channel)
message.reply(replytext, "say")
| from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsLength < 1:
replytext = "Please provide a channel for me to join"
else:
channel = message.messageParts[0]
if channel.replace('#', '') not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress):
replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission"
else:
replytext = "All right, I'll go to {}. See you there!".format(channel)
message.bot.join(channel)
message.reply(replytext, "say") |
Add wider description for wheel and egg packages | from setuptools import setup, find_packages
setup(
name="virgil-sdk",
version="5.0.0",
packages=find_packages(),
install_requires=[
'virgil-crypto',
],
author="Virgil Security",
author_email="support@virgilsecurity.com",
url="https://virgilsecurity.com/",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Security :: Cryptography",
],
license="BSD",
description="""
Virgil Security provides a set of APIs for adding security to any application. In a few simple steps you can encrypt communication, securely store data, provide passwordless login, and ensure data integrity.
Virgil SDK allows developers to get up and running with Virgil API quickly and add full end-to-end (E2EE) security to their existing digital solutions to become HIPAA and GDPR compliant and more.(изменено)
Virgil Python Crypto Library is a high-level cryptographic library that allows you to perform all necessary operations for secure storing and transferring data and everything required to become HIPAA and GDPR compliant.
""",
long_description="Virgil keys service SDK",
)
| from setuptools import setup, find_packages
setup(
name="virgil-sdk",
version="5.0.0",
packages=find_packages(),
install_requires=[
'virgil-crypto',
],
author="Virgil Security",
author_email="support@virgilsecurity.com",
url="https://virgilsecurity.com/",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Security :: Cryptography",
],
license="BSD",
description="Virgil keys service SDK",
long_description="Virgil keys service SDK",
)
|
Set validation to false when copying a schema | /* (c) 2014 LinkedIn Corp. 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.
*/
package com.linkedin.uif.fork;
import org.apache.avro.Schema;
/**
* A wrapper class for {@link org.apache.avro.Schema} that is also {@link Copyable}.
*
* @author ynli
*/
public class CopyableSchema implements Copyable<Schema> {
private final Schema schema;
public CopyableSchema(Schema schema) {
this.schema = schema;
}
@Override
public Schema copy()
throws CopyNotSupportedException {
return new Schema.Parser().setValidate(false).parse(this.schema.toString());
}
}
| /* (c) 2014 LinkedIn Corp. 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.
*/
package com.linkedin.uif.fork;
import org.apache.avro.Schema;
/**
* A wrapper class for {@link org.apache.avro.Schema} that is also {@link Copyable}.
*
* @author ynli
*/
public class CopyableSchema implements Copyable<Schema> {
private final Schema schema;
public CopyableSchema(Schema schema) {
this.schema = schema;
}
@Override
public Schema copy() throws CopyNotSupportedException {
return new Schema.Parser().parse(this.schema.toString());
}
}
|
Use Node.js module export, since ES6 export breaks build.
Signed-off-by: André Jaenisch <2c685275bd32aff3e28a84de6a3e3ac9f1b2b901@posteo.de> | /*
Copyright 2018 André Jaenisch
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.
*/
/**
* @module logger
*/
const log = require("loglevel");
// This is to demonstrate, that you can use any namespace you want.
// Namespaces allow you to turn on/off the logging for specific parts of the
// application.
// An idea would be to control this via an environment variable (on Node.js).
// See https://www.npmjs.com/package/debug to see how this could be implemented
// Part of #332 is introducing a logging library in the first place.
const DEFAULT_NAME_SPACE = "matrix";
const logger = log.getLogger(DEFAULT_NAME_SPACE);
logger.setLevel(log.levels.DEBUG);
/**
* Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}.
* Can be tailored down to specific use cases if needed.
*/
module.exports = logger;
| /*
Copyright 2018 André Jaenisch
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.
*/
/**
* @module logger
*/
const log = require("loglevel");
// This is to demonstrate, that you can use any namespace you want.
// Namespaces allow you to turn on/off the logging for specific parts of the
// application.
// An idea would be to control this via an environment variable (on Node.js).
// See https://www.npmjs.com/package/debug to see how this could be implemented
// Part of #332 is introducing a logging library in the first place.
const DEFAULT_NAME_SPACE = "matrix";
const logger = log.getLogger(DEFAULT_NAME_SPACE);
logger.setLevel(log.levels.DEBUG);
/**
* Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}.
* Can be tailored down to specific use cases if needed.
*/
export default logger;
|
Change order for the override when override isnt null | import React from 'react'
import getDisplayName from 'recompose/getDisplayName'
import wrapDisplayName from 'recompose/wrapDisplayName'
import { withPropsFromContext } from 'react-context-props'
import deepMerge from 'deepmerge'
export default Target => {
const name = getDisplayName(Target)
const WithOverrideFromContext = withPropsFromContext([name])(props => {
const Override = props[name]
const propsWithoutOverride = { ...props }
delete propsWithoutOverride[name]
if (typeof Override === 'function') {
return <Override {...propsWithoutOverride} />
} else if (Override != null) {
return <Target {...deepMerge(propsWithoutOverride, Override)} />
} else {
return <Target {...propsWithoutOverride} />
}
})
WithOverrideFromContext.displayName = wrapDisplayName(Target, 'withOverrideFromContext')
return WithOverrideFromContext
}
| import React from 'react'
import getDisplayName from 'recompose/getDisplayName'
import wrapDisplayName from 'recompose/wrapDisplayName'
import { withPropsFromContext } from 'react-context-props'
import deepMerge from 'deepmerge'
export default Target => {
const name = getDisplayName(Target)
const WithOverrideFromContext = withPropsFromContext([name])(props => {
const Override = props[name]
const propsWithoutOverride = { ...props }
delete propsWithoutOverride[name]
if (typeof Override === 'function') {
return <Override {...propsWithoutOverride} />
} else if (Override != null) {
return <Target {...deepMerge(Override, propsWithoutOverride)} />
} else {
return <Target {...propsWithoutOverride} />
}
})
WithOverrideFromContext.displayName = wrapDisplayName(Target, 'withOverrideFromContext')
return WithOverrideFromContext
}
|
Clarify why columns must modify node id | 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS, {
beforeCreate: function(node) {
// Last updated time in source node means data changed so it has to modify node.id
node.setAttributeToModifyId('updatedAt');
}
});
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Columns have to modify Node.id().
// When a `select * from table` might end in a different set of columns we want to have a different node.
// Current table triggers don't check DDL changes.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
| 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS, {
beforeCreate: function(node) {
// Last updated time in source node means data changed so it has to modify node.id
node.setAttributeToModifyId('updatedAt');
}
});
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Makes columns affecting Node.id().
// When a `select * from table` might end in a different set of columns
// we want to have a different node.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
|
:bug: Fix using cooldown from options rather than from object | 'use strict';
const BaseStep = require('./base-step');
const KiteAPI = require('kite-api');
const {retryPromise} = require('kite-connector/lib/utils');
const Metrics = require('../../ext/telemetry/metrics');
module.exports = class Authenticate extends BaseStep {
constructor(options = {}) {
super(options);
this.cooldown = options.cooldown || 1500;
this.tries = options.tries || 10;
}
start(state, install) {
if (!state.account || !state.account.sessionId) {
return Promise.reject();
}
install.updateState({authenticate: {done: false}});
return retryPromise(() =>
KiteAPI.authenticateSessionID(state.account.sessionId), this.tries, this.cooldown)
.then(() =>
retryPromise(() => KiteAPI.isUserAuthenticated(), this.tries, this.cooldown))
.then(() => {
Metrics.Tracker.trackEvent('kite_installer_user_authenticated');
install.updateState({authenticate: {done: true}});
});
}
};
| 'use strict';
const BaseStep = require('./base-step');
const KiteAPI = require('kite-api');
const {retryPromise} = require('kite-connector/lib/utils');
const Metrics = require('../../ext/telemetry/metrics');
module.exports = class Authenticate extends BaseStep {
constructor(options = {}) {
super(options);
this.cooldown = options.cooldown || 1500;
this.tries = options.tries || 10;
}
start(state, install) {
if (!state.account || !state.account.sessionId) {
return Promise.reject();
}
install.updateState({authenticate: {done: false}});
return retryPromise(() =>
KiteAPI.authenticateSessionID(state.account.sessionId), this.tries, this.options.cooldown)
.then(() =>
retryPromise(() => KiteAPI.isUserAuthenticated(), this.tries, this.options.cooldown))
.then(() => {
Metrics.Tracker.trackEvent('kite_installer_user_authenticated');
install.updateState({authenticate: {done: true}});
});
}
};
|
Replace db host to localhost | from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
| from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'db',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
|
Add tenant id to Enrollment Certificate | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
public class EnrollmentCertificate {
String serial;
String pem;
int tenantId;
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getPem() {
return pem;
}
public void setPem(String pem) {
this.pem = pem;
}
}
| /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans;
public class EnrollmentCertificate {
String serial;
String pem;
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getPem() {
return pem;
}
public void setPem(String pem) {
this.pem = pem;
}
}
|
Fix test runner to accept 1 arg | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 1:
print 'Error: Exactly 1 argument required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = "tests"
main(SDK_PATH, TEST_PATH) | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules"""
def main(sdk_path, test_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 2:
print 'Error: Exactly 2 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = "tests"
main(SDK_PATH, TEST_PATH) |
fix(flow): Fix flow error in test store setup. | // @flow
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { routerReducer, routerMiddleware } from 'react-router-redux'
import { createMemoryHistory } from 'history'
import { createReducer } from 'redux-orm'
import createSagaMiddleware from 'redux-saga'
import sinon from 'sinon'
import orm from '../src/models/orm'
import * as reducers from '../src/reducers'
import sagas from './setupSagas'
export const history = createMemoryHistory()
export const dispatchSpy = sinon.spy()
const spyReducer = (state = {}, action) => {
dispatchSpy(action)
return state
}
export default function createStoreWithMiddleware() {
const reducer = combineReducers({
spyReducer,
orm: createReducer(orm),
...reducers,
router: routerReducer
})
const sagaMiddleware = createSagaMiddleware()
const middleware = [routerMiddleware(history), sagaMiddleware]
// $FlowFixMe: This is erroring for some reason
let store = createStore(reducer, applyMiddleware(...middleware))
sagaMiddleware.run(sagas)
return store
}
| // @flow
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { routerReducer, routerMiddleware } from 'react-router-redux'
import { createMemoryHistory } from 'history'
import { createReducer } from 'redux-orm'
import createSagaMiddleware from 'redux-saga'
import sinon from 'sinon'
import orm from '../src/models/orm'
import * as reducers from '../src/reducers'
import sagas from './setupSagas'
export const history = createMemoryHistory()
export const dispatchSpy = sinon.spy()
const spyReducer = (state = {}, action) => {
dispatchSpy(action)
return state
}
export default function createStoreWithMiddleware() {
const reducer = combineReducers({
spyReducer,
orm: createReducer(orm),
...reducers,
router: routerReducer
})
const sagaMiddleware = createSagaMiddleware()
const middleware = [routerMiddleware(history), sagaMiddleware]
let store = createStore(reducer, applyMiddleware(...middleware))
sagaMiddleware.run(sagas)
return store
}
|
Create public directory on new app | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Local dependencies.
const packageJSON = require('../json/package.json.js');
/**
* Copy required files for the generated application
*/
module.exports = {
moduleDir: path.resolve(__dirname, '..'),
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
after: require('./after'),
targets: {
// Main package.
'package.json': {
jsonfile: packageJSON
},
// Copy dot files.
'.editorconfig': {
copy: 'editorconfig'
},
'.gitignore': {
copy: 'gitignore'
},
'.npmignore': {
copy: 'npmignore'
},
// Copy Markdown files with some information.
'README.md': {
template: 'README.md'
},
// Empty data directory.
'data': {
folder: {}
},
// Empty API directory.
'api': {
folder: {}
},
// Empty plugins directory.
'plugins': {
folder: {}
}
// Empty public directory.
'public': {
folder: {}
}
}
};
| 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Local dependencies.
const packageJSON = require('../json/package.json.js');
/**
* Copy required files for the generated application
*/
module.exports = {
moduleDir: path.resolve(__dirname, '..'),
templatesDirectory: path.resolve(__dirname, '..', 'templates'),
before: require('./before'),
after: require('./after'),
targets: {
// Main package.
'package.json': {
jsonfile: packageJSON
},
// Copy dot files.
'.editorconfig': {
copy: 'editorconfig'
},
'.gitignore': {
copy: 'gitignore'
},
'.npmignore': {
copy: 'npmignore'
},
// Copy Markdown files with some information.
'README.md': {
template: 'README.md'
},
// Empty data directory.
'data': {
folder: {}
},
// Empty API directory.
'api': {
folder: {}
},
// Empty plugins directory.
'plugins': {
folder: {}
}
}
};
|
Move https middleware up front | const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 4000;
const app = express();
// Enforce HTTPS
function enforceHTTPS(request, response, next) {
if (process.env.NODE_ENV === 'development') return next();
if (request.headers['x-forwarded-proto'] !== 'https') {
const httpsUrl = ['https://', request.headers.host, request.url].join('');
return response.redirect(httpsUrl);
}
return next();
}
app.use(enforceHTTPS);
// API endpoints
app.get('/api/hello', (req, res) => {
res.set('Content-Type', 'application/json');
res.json({ message: 'Hello from the server!' });
});
// Serve any static files.
app.use(express.static(path.resolve(__dirname, '../client/build')));
// All remaining requests return the React app, so it can handle routing.
app.get('*', (request, response) => {
response.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});
// Start the server
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}.`);
}); | const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 4000;
const app = express();
// API endpoints
app.get('/api/hello', (req, res) => {
res.set('Content-Type', 'application/json');
res.json({ message: 'Hello from the server!' });
});
// Serve any static files.
app.use(express.static(path.resolve(__dirname, '../client/build')));
// All remaining requests return the React app, so it can handle routing.
app.get('*', (request, response) => {
response.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});
// Enforce HTTPS
function enforceHTTPS(request, response, next) {
if (process.env.NODE_ENV === 'development') return next();
if (request.headers['x-forwarded-proto'] !== 'https') {
const httpsUrl = ['https://', request.headers.host, request.url].join('');
return response.redirect(httpsUrl);
}
return next();
}
app.use(enforceHTTPS);
// Start the server
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}.`);
}); |
Set a high limit on the query to retrieve all the maplayers | const mapBaseLayers = require('../../../public/static/map/map-base-layers.config.json')
async function fetchMap(resolver, query) {
const result = await fetch(process.env.GRAPHQL_ENDPOINT, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
}),
})
const json = await result.json()
return json.data[resolver]
}
export function getMapBaseLayers() {
return mapBaseLayers
}
export async function getMapLayers() {
const query = `{ mapLayerSearch(input: { limit: 9999 }) { results { id title url params layers external detailUrl detailItem detailIsShape noDetail authScope type } } }`
const { results: mapLayerResults } = await fetchMap('mapLayerSearch', query)
return mapLayerResults
}
export async function getPanelLayers() {
const query = `{ mapCollectionSearch(input: { limit: 9999 }) { results { id title mapLayers { id title legendItems { id title url params layers iconUrl imageRule notSelectable noDetail } authScope imageRule iconUrl url params layers detailUrl detailItem detailIsShape type noDetail minZoom maxZoom } } } }`
const { results: mapPanelLayerResults } = await fetchMap('mapCollectionSearch', query)
return mapPanelLayerResults
}
| const mapBaseLayers = require('../../../public/static/map/map-base-layers.config.json')
async function fetchMap(resolver, query) {
const result = await fetch(process.env.GRAPHQL_ENDPOINT, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
}),
})
const json = await result.json()
return json.data[resolver]
}
export function getMapBaseLayers() {
return mapBaseLayers
}
export async function getMapLayers() {
const query = `{ mapLayerSearch { results { id title url params layers external detailUrl detailItem detailIsShape noDetail authScope type } } }`
const { results: mapLayerResults } = await fetchMap('mapLayerSearch', query)
return mapLayerResults
}
export async function getPanelLayers() {
const query = `{ mapCollectionSearch { results { id title mapLayers { id title legendItems { id title url params layers iconUrl imageRule notSelectable noDetail } authScope imageRule iconUrl url params layers detailUrl detailItem detailIsShape type noDetail minZoom maxZoom } } } }`
const { results: mapPanelLayerResults } = await fetchMap('mapCollectionSearch', query)
return mapPanelLayerResults
}
|
Add gevent as an extra requirement | #!/usr/bin/env python
from distutils.core import setup
# README = "/".join([os.path.dirname(__file__), "README.md"])
# with open(README) as file:
# long_description = file.read()
setup(
name='graphitesend',
version='0.4.0',
description='A simple interface for sending metrics to Graphite',
author='Danny Lawrence',
author_email='dannyla@linux.com',
url='https://github.com/daniellawrence/graphitesend',
# package_dir={'': ''},
packages=['graphitesend'],
long_description="https://github.com/daniellawrence/graphitesend",
entry_points={
'console_scripts': [
'graphitesend = graphitesend.graphitesend:cli',
],
},
extras_require = {
'asynchronous': ['gevent>=1.0.0'],
}
)
| #!/usr/bin/env python
from distutils.core import setup
# README = "/".join([os.path.dirname(__file__), "README.md"])
# with open(README) as file:
# long_description = file.read()
setup(
name='graphitesend',
version='0.4.0',
description='A simple interface for sending metrics to Graphite',
author='Danny Lawrence',
author_email='dannyla@linux.com',
url='https://github.com/daniellawrence/graphitesend',
# package_dir={'': ''},
packages=['graphitesend'],
long_description="https://github.com/daniellawrence/graphitesend",
entry_points={
'console_scripts': [
'graphitesend = graphitesend.graphitesend:cli',
],
}
)
|
Add ability to update the votes for an answer in the poll
This is needed by the app so we can update poll results after voting without needing to redownload the whole page | package api.forum.thread;
/**
* The Class Answer.
* Stores information about an possible answer selection
* for a Poll
*
* @author Gwindow
*/
public class Answer {
/**
* The answer text
*/
private String answer;
/**
* The percent of votes it's gotten
*/
private Number percent;
/**
* The ratio of votes it's gotten
*/
private Number ratio;
/**
* Get the answer text
*
* @return the answer text
*/
public String getAnswer(){
return this.answer;
}
/**
* Get the percent of votes the answers received
*
* @return the percent of votes received
*/
public Number getPercent(){
return this.percent;
}
/**
* Get the ratio of votes the answers received
*
* @return the ratio of votes received
*/
public Number getRatio(){
return this.ratio;
}
/**
* Update the percentage of votes this answer has received
*
* @param votes votes for this answer
* @param total total votes in the poll
*/
public void setVotes(int votes, int total){
percent = ((float)votes) / total;
}
@Override
public String toString(){
return "Answer [getAnswer=" + getAnswer() + ", getPercent=" + getPercent() + ", getRatio=" + getRatio() + "]";
}
}
| package api.forum.thread;
/**
* The Class Answer.
* Stores information about an possible answer selection
* for a Poll
*
* @author Gwindow
*/
public class Answer {
/**
* The answer text
*/
private String answer;
/**
* The percent of votes it's gotten
*/
private Number percent;
/**
* The ratio of votes it's gotten
*/
private Number ratio;
/**
* Get the answer text
*
* @return the answer text
*/
public String getAnswer(){
return this.answer;
}
/**
* Get the percent of votes the answers received
*
* @return the percent of votes received
*/
public Number getPercent(){
return this.percent;
}
/**
* Get the ratio of votes the answers received
*
* @return the ratio of votes received
*/
public Number getRatio(){
return this.ratio;
}
@Override
public String toString(){
return "Answer [getAnswer=" + getAnswer() + ", getPercent=" + getPercent() + ", getRatio=" + getRatio() + "]";
}
}
|
Change events name to adapt to client | var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
codebox.workspace.path()
.then(function(path) {
var watcher = Watcher(path, 2);
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('fs:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('fs:modified', files);
});
codebox.logger.log("File watcher started");
});
};
| var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
codebox.workspace.path()
.then(function(path) {
var watcher = Watcher(path, 2);
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('watcher:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('watcher:modified', files);
});
codebox.logger.log("File watcher started");
});
};
|
Use python2 pyyaml instead of python3. | import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
|
Use old import toc name to avoid migration problems | <?php
return [
'csv' => [
'delimiter' => ';',
'enclosure' => '"',
'escape' => '\\',
'single_item' => false,
'first_row_as_keys' => false,
'keys' => [],
],
'date.backend' => 'Y-m-d',
'date.frontend' => 'Y-m-d',
'date.view' => 'd.m.Y',
'datetime.backend' => 'Y-m-d H:i:s',
'datetime.frontend' => 'Y-m-d\TH:i',
'datetime.view' => 'd.m.Y H:i',
'i18n.charset' => 'utf-8',
'i18n.lang' => 'de',
'i18n.locale' => 'de-DE',
'i18n.timezone' => 'Europe/Berlin',
'import.end' => '<!-- IMPORT_END -->',
'import.start' => '<!-- IMPORT_START -->',
'import.toc' => 'toc.txt',
'limit.admin' => 20,
'limit.index' => 20,
'limit.pager' => 5,
'page.url' => '.html',
'privilege' => '_all_',
'project' => 1,
'theme' => 'base',
'time.backend' => 'H:i:s',
'time.frontend' => 'H:i',
'time.view' => 'H:i',
];
| <?php
return [
'csv' => [
'delimiter' => ';',
'enclosure' => '"',
'escape' => '\\',
'single_item' => false,
'first_row_as_keys' => false,
'keys' => [],
],
'date.backend' => 'Y-m-d',
'date.frontend' => 'Y-m-d',
'date.view' => 'd.m.Y',
'datetime.backend' => 'Y-m-d H:i:s',
'datetime.frontend' => 'Y-m-d\TH:i',
'datetime.view' => 'd.m.Y H:i',
'i18n.charset' => 'utf-8',
'i18n.lang' => 'de',
'i18n.locale' => 'de-DE',
'i18n.timezone' => 'Europe/Berlin',
'import.end' => '<!-- IMPORT_END -->',
'import.start' => '<!-- IMPORT_START -->',
'import.toc' => 'import.csv',
'limit.admin' => 20,
'limit.index' => 20,
'limit.pager' => 5,
'page.url' => '.html',
'privilege' => '_all_',
'project' => 1,
'theme' => 'base',
'time.backend' => 'H:i:s',
'time.frontend' => 'H:i',
'time.view' => 'H:i',
];
|
Fix for PHP < 5.6 | <?php namespace Stolz\HtmlTidy;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['stolz.tidy'];
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
// Merge user's configuration
$this->mergeConfigFrom(__DIR__ . '/config.php', 'tidy');
// Bind 'stolz.tidy' shared component to the IoC container
$this->app->singleton('stolz.tidy', function ($app) {
return new Tidy($app['config']['tidy']);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
// Register paths to be published by 'vendor:publish' artisan command
$this->publishes([
__DIR__ . '/config.php' => config_path('tidy.php'),
]);
}
}
| <?php namespace Stolz\HtmlTidy;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Path to the default config file.
*
* @var string
*/
protected $configFile = __DIR__ . '/config.php';
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['stolz.tidy'];
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
// Merge user's configuration
$this->mergeConfigFrom($this->configFile, 'tidy');
// Bind 'stolz.tidy' shared component to the IoC container
$this->app->singleton('stolz.tidy', function ($app) {
return new Tidy($app['config']['tidy']);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
// Register paths to be published by 'vendor:publish' artisan command
$this->publishes([
$this->configFile => config_path('tidy.php'),
]);
}
}
|
Set bplan default email to english as default | from adhocracy4.emails import Email
class OfficeWorkerNotification(Email):
template_name = 'meinberlin_bplan/emails/office_worker_notification'
@property
def office_worker_email(self):
project = self.object.project
return project.externalproject.bplan.office_worker_email
def get_receivers(self):
return [self.office_worker_email]
def get_context(self):
context = super().get_context()
context['project'] = self.object.project
return context
class SubmitterConfirmation(Email):
template_name = 'meinberlin_bplan/emails/submitter_confirmation'
def get_receivers(self):
return [self.object.email]
def get_context(self):
context = super().get_context()
context['project'] = self.object.project
return context
| from adhocracy4.emails import Email
class OfficeWorkerNotification(Email):
template_name = 'meinberlin_bplan/emails/office_worker_notification'
@property
def office_worker_email(self):
project = self.object.project
return project.externalproject.bplan.office_worker_email
def get_receivers(self):
return [self.office_worker_email]
def get_context(self):
context = super().get_context()
context['project'] = self.object.project
return context
class SubmitterConfirmation(Email):
template_name = 'meinberlin_bplan/emails/submitter_confirmation'
fallback_language = 'de'
def get_receivers(self):
return [self.object.email]
def get_context(self):
context = super().get_context()
context['project'] = self.object.project
return context
|
Add exception handling for output | from i3pystatus import IntervalModule
from subprocess import check_output, CalledProcessError
class Shell(IntervalModule):
"""
Shows output of shell command
"""
color = "#FFFFFF"
error_color = "#FF0000"
settings = (
("command", "command to be executed"),
("color", "standard color"),
("error_color", "color to use when non zero exit code is returned")
)
required = ("command",)
def run(self):
try:
out = check_output(self.command, shell=True)
color = self.color
except CalledProcessError as e:
out = e.output
color = self.error_color
out = out.decode("UTF-8").replace("\n", " ")
try:
if out[-1] == " ":
out = out[:-1]
except:
out = ""
self.output = {
"full_text": out,
"color": color
}
| from i3pystatus import IntervalModule
from subprocess import check_output, CalledProcessError
class Shell(IntervalModule):
"""
Shows output of shell command
"""
color = "#FFFFFF"
error_color = "#FF0000"
settings = (
("command", "command to be executed"),
("color", "standard color"),
("error_color", "color to use when non zero exit code is returned")
)
required = ("command",)
def run(self):
try:
out = check_output(self.command, shell=True)
color = self.color
except CalledProcessError as e:
out = e.output
color = self.error_color
out = out.decode("UTF-8").replace("\n", " ")
if out[-1] == " ":
out = out[:-1]
self.output = {
"full_text": out,
"color": color
}
|
Rename thenApply function to then | 'use strict';
var _ = require('lodash');
var httpConfigurable = {};
httpConfigurable.initHttpConfigurable = function() {
this.thenApplies = [];
this.headers = {};
};
httpConfigurable.header = function(headerKey, headerValue) {
this.headers[headerKey] = headerValue;
return this;
};
httpConfigurable.contentType = function(mimeType) {
return this.header('Content-Type', mimeType);
};
httpConfigurable.accept = function(mimeType) {
return this.header('Accept', mimeType);
};
httpConfigurable.then = function(onFulfilled, onRejected, onProgress) {
var applies = {
onFulfilled: onFulfilled,
onRejected: onRejected,
onProgress: onProgress
};
this.thenApplies.push(applies);
return this;
};
httpConfigurable.thenApply = httpConfigurable.then;
httpConfigurable.mergeThenApplies = function(_thenApplies) {
_.extend(this.thenApplies, _thenApplies);
};
module.exports = httpConfigurable;
| 'use strict';
var _ = require('lodash');
var httpConfigurable = {};
httpConfigurable.initHttpConfigurable = function() {
this.thenApplies = [];
this.headers = {};
};
httpConfigurable.header = function(headerKey, headerValue) {
this.headers[headerKey] = headerValue;
return this;
};
httpConfigurable.contentType = function(mimeType) {
return this.header('Content-Type', mimeType);
};
httpConfigurable.accept = function(mimeType) {
return this.header('Accept', mimeType);
};
httpConfigurable.thenApply = function(onFulfilled, onRejected, onProgress) {
var applies = {
onFulfilled: onFulfilled,
onRejected: onRejected,
onProgress: onProgress
};
this.thenApplies.push(applies);
return this;
};
httpConfigurable.mergeThenApplies = function(_thenApplies) {
_.extend(this.thenApplies, _thenApplies);
};
module.exports = httpConfigurable;
|
Insert into 'entries' using prepared statements, with submission ID | <?php
$date =& $_REQUEST["date"];
$user =& $_REQUEST["user"];
$priority =& $_REQUEST["priority"];
$text =& $_REQUEST["text"];
if (isset($_REQUEST["submission"])) {
$sid = intval($_REQUEST["submission"]);
} else {
$sid = null;
}
require_once 'icat.php';
$db = init_db();
$_SESSION['entry_username'] = $user;
$stmt = mysqli_prepare($db, 'INSERT INTO entries (contest_time, user, priority, text, submission_id) VALUES ((SELECT MAX(contest_time) AS last_submission FROM submissions), ?, ?, ?, ?)');
mysqli_stmt_bind_param($stmt, 'sisi', $user, $priority, $text, $sid);
mysqli_stmt_execute($stmt);
$error = mysqli_stmt_error($stmt);
if ($error === '') {
print("okay");
} else {
print("error: " . $error);
}
mysqli_stmt_close($stmt);
| <?php
$date =& $_REQUEST["date"];
$user =& $_REQUEST["user"];
$priority =& $_REQUEST["priority"];
$text =& $_REQUEST["text"];
require_once 'icat.php';
$db = init_db();
$_SESSION['entry_username'] = $user;
$result = mysqli_query($db,
"insert into entries (contest_time, user, priority, text) values " .
sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);
if ($result) {
print("okay");
} else {
print("error: " . mysqli_error($db));
}
?>
|
Store output in a subdirectory | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
output_dir = 'output'
def main():
# Make our output directory, if it doesn't exist.
if not os.path.exists(output_dir):
os.makedirs(output_dir)
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid='
errors = 0
i = 1
while True:
req = Request(url_base + str(i))
try:
f = urlopen(req)
sys.stdout.write('.')
sys.stdout.flush()
errors = 0
local_file = open(str(i) + '.html', 'w')
local_file.write(f.read())
local_file.close()
except HTTPError as e:
sys.stdout.write(' ')
sys.stdout.flush()
errors += 1
i += 1
if errors >= 100:
break
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
def main():
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid='
errors = 0
i = 1
while True:
req = Request(url_base + str(i))
try:
f = urlopen(req)
sys.stdout.write('.')
sys.stdout.flush()
errors = 0
local_file = open(str(i) + '.html', 'w')
local_file.write(f.read())
local_file.close()
except HTTPError as e:
sys.stdout.write(' ')
sys.stdout.flush()
errors += 1
i += 1
if errors >= 100:
break
if __name__ == "__main__":
main()
|
directory: Move AllowedCurrencies from store into directory package | // Copyright 2015, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package directory
import (
"strings"
"github.com/corestoreio/csfw/config"
"golang.org/x/text/language"
)
type Currency struct {
// https://godoc.org/golang.org/x/text/language
c language.Currency
}
// BaseCurrencyCode retrieves application base currency code
func BaseCurrencyCode(cr config.Reader) (language.Currency, error) {
base, err := cr.GetString(config.Path(PathCurrencyBase))
if err != nil && err != config.ErrKeyNotFound {
return language.Currency{}, err
}
return language.ParseCurrency(base)
}
// AllowedCurrencies returns all installed currencies from global scope.
func AllowedCurrencies(cr config.Reader) ([]string, error) {
installedCur, err := cr.GetString(config.Path(PathSystemCurrencyInstalled))
if err != nil && err != config.ErrKeyNotFound {
return nil, err
}
// TODO use internal model of PathSystemCurrencyInstalled defined in package directory
return strings.Split(installedCur, ","), nil
}
| // Copyright 2015, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package directory
import (
"github.com/corestoreio/csfw/config"
"golang.org/x/text/language"
)
type Currency struct {
// https://godoc.org/golang.org/x/text/language
c language.Currency
}
// BaseCurrencyCode retrieves application base currency code
func BaseCurrencyCode(cr config.Reader) (language.Currency, error) {
base, err := cr.GetString(config.Path(PathCurrencyBase))
if err != nil && err != config.ErrKeyNotFound {
return language.Currency{}, err
}
return language.ParseCurrency(base)
}
|
fix: Remove redundant transformations and fix locale transformations | import { omit, pick } from 'lodash/object'
import { find, reduce } from 'lodash/collection'
/**
* Default transformer methods for each kind of entity.
*
* In the case of assets it also changes the asset url to the upload property
* as the whole upload process needs to be followed again.
*/
export function contentTypes (contentType) {
return contentType
}
export function entries (entry) {
return entry
}
export function assets (asset) {
asset.fields = pick(asset.fields, 'title', 'description')
asset.fields.file = reduce(
asset.fields.file,
(newFile, file, locale) => {
newFile[locale] = omit(file, 'url', 'details')
newFile[locale].upload = 'http:' + file.url
return newFile
},
{}
)
return asset
}
export function locales (locale, destinationLocales) {
const transformedLocale = pick(locale, 'code', 'name', 'contentManagementApi', 'contentDeliveryApi', 'fallback_code', 'optional')
const destinationLocale = find(destinationLocales, {code: locale.code})
if (destinationLocale) {
transformedLocale.sys = pick(destinationLocale.sys, 'id')
}
return transformedLocale
}
| import { omit, pick } from 'lodash/object'
import { find, reduce } from 'lodash/collection'
/**
* Default transformer methods for each kind of entity.
* For most cases these just remove information that is specific to the content
* existing in a space (date created, version, etc), which the new space will
* generate by itself.
*
* In the case of assets it also changes the asset url to the upload property
* as the whole upload process needs to be followed again.
*/
export function contentTypes (contentType) {
const transformedContentType = omit(contentType, 'sys')
transformedContentType.sys = pick(contentType.sys, 'id')
return transformedContentType
}
export function entries (entry) {
const transformedEntry = omit(entry, 'sys')
transformedEntry.sys = pick(entry.sys, 'id')
return transformedEntry
}
export function assets (asset) {
const transformedAsset = omit(asset, 'sys')
transformedAsset.sys = pick(asset.sys, 'id')
transformedAsset.fields = pick(asset.fields, 'title', 'description')
transformedAsset.fields.file = reduce(
asset.fields.file,
(newFile, file, locale) => {
newFile[locale] = omit(file, 'url', 'details')
newFile[locale].upload = 'http:' + file.url
return newFile
},
{}
)
return transformedAsset
}
export function locales (locale, destinationLocales) {
const transformedLocale = pick(locale, 'code', 'name', 'contentManagementApi', 'contentDeliveryApi')
const destinationLocale = find(destinationLocales, {code: locale.code})
if (destinationLocale) {
transformedLocale.sys = pick(destinationLocale.sys, 'id')
}
return transformedLocale
}
|
Fix contact page fatal error. | <?php
global $wp_query;
$slider_or_image = '';
$page_parent_image = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : '';
$page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : '';
$page_google_map = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : '';
if ( $page_parent_image ) {
$slider_or_image = wp_get_attachment_image( $page_parent_image, 'full' );
} else if ( is_front_page() ) {
$slider_or_image = do_shortcode( '[responsive_slider]' );
} else if ( $page_parent_animation ) {
$slider_or_image = get_template_part('templates/animation');
} else if ( $page_google_map ) {
$options = get_option('plugin_options');
$slider_or_image = $options['vobe_google_map_code'];
}
echo $slider_or_image;
?> | <?php
global $wp_query;
$slider_or_image = '';
$page_parent_image = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : '';
$page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : '';
$page_google_map = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : '';
if ( $page_parent_image ) {
$slider_or_image = wp_get_attachment_image( $page_parent_image, 'full' );
} else if ( is_front_page() ) {
$slider_or_image = do_shortcode( '[responsive_slider]' );
} else if ( $page_parent_animation ) {
$slider_or_image = get_template_part('templates/animation');
} else if ( $page_google_map ) {
$options = $get_option('plugin_options');
$slider_or_image = $options['vobe_google_map_code'];
}
echo $slider_or_image;
?> |
BUMP to -2 for bug reporting. | package net.i2p.router;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import net.i2p.CoreVersion;
/**
* Expose a version string
*
*/
public class RouterVersion {
public final static String ID = "$Revision: 1.548 $ $Date: 2008-06-07 23:00:00 $";
public final static String VERSION = "0.6.5";
public final static long BUILD = 2;
public static void main(String args[]) {
System.out.println("I2P Router version: " + VERSION + "-" + BUILD);
System.out.println("Router ID: " + RouterVersion.ID);
System.out.println("I2P Core version: " + CoreVersion.VERSION);
System.out.println("Core ID: " + CoreVersion.ID);
}
}
| package net.i2p.router;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import net.i2p.CoreVersion;
/**
* Expose a version string
*
*/
public class RouterVersion {
public final static String ID = "$Revision: 1.548 $ $Date: 2008-06-07 23:00:00 $";
public final static String VERSION = "0.6.5";
public final static long BUILD = 1;
public static void main(String args[]) {
System.out.println("I2P Router version: " + VERSION + "-" + BUILD);
System.out.println("Router ID: " + RouterVersion.ID);
System.out.println("I2P Core version: " + CoreVersion.VERSION);
System.out.println("Core ID: " + CoreVersion.ID);
}
}
|
fix(hr): Use event_status instead of status
Training Feedback DocType has event_status field (not status)
This was broken since PR #10379, PR #17197 made this failure explicit. | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
event_status = None
for e in training_event.employees:
if e.employee == self.employee:
event_status = 'Feedback Submitted'
break
if event_status:
frappe.db.set_value("Training Event", self.training_event, "event_status", event_status)
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
status = None
for e in training_event.employees:
if e.employee == self.employee:
status = 'Feedback Submitted'
break
if status:
frappe.db.set_value("Training Event", self.training_event, "status", status)
|
Upgrade libchromiumcontent to use the static_library build | #!/usr/bin/env python
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
| #!/usr/bin/env python
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
|
[DBAL-184] Fix Binding Type for BIGINT | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Type that maps a database BIGINT to a PHP string.
*
* @author robo
* @since 2.0
*/
class BigIntType extends Type
{
public function getName()
{
return Type::BIGINT;
}
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getBigIntTypeDeclarationSQL($fieldDeclaration);
}
public function getBindingType()
{
return \PDO::PARAM_STR;
}
} | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Type that maps a database BIGINT to a PHP string.
*
* @author robo
* @since 2.0
*/
class BigIntType extends Type
{
public function getName()
{
return Type::BIGINT;
}
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getBigIntTypeDeclarationSQL($fieldDeclaration);
}
public function getBindingType()
{
return \PDO::PARAM_INT;
}
} |
Tweak irc mock to create a new spy per instance of an irc client | /*
* Mock replacement for 'irc'.
*/
"use strict";
var generatedClients = {};
function Client(addr, nick, opts) {
generatedClients[addr+nick] = this;
console.log("GC: %s",Object.keys(generatedClients));
this.addListener = jasmine.createSpy("Client.addListener(event, fn)");
this.connect = jasmine.createSpy("Client.connect(fn)");
this.whois = jasmine.createSpy("Client.whois(nick, fn)");
this.join = jasmine.createSpy("Client.join(channel, fn)");
this.action = jasmine.createSpy("Client.action(channel, text)");
this.ctcp = jasmine.createSpy("Client.ctcp(channel, kind, text)");
this.say = jasmine.createSpy("Client.say(channel, text)");
};
module.exports.Client = Client;
// ===== helpers
module.exports._find = function(addr, nick) {
return generatedClients[addr+nick];
};
module.exports._reset = function() {
generatedClients = {};
}; | /*
* Mock replacement for 'irc'.
*/
"use strict";
var generatedClients = {};
function Client(addr, nick, opts) {
generatedClients[addr+nick] = this;
};
Client.prototype = {
addListener: jasmine.createSpy("Client.addListener(event, fn)"),
connect: jasmine.createSpy("Client.connect(fn)"),
whois: jasmine.createSpy("Client.whois(nick, fn)"),
join: jasmine.createSpy("Client.join(channel, fn)"),
action: jasmine.createSpy("Client.action(channel, text)"),
ctcp: jasmine.createSpy("Client.ctcp(channel, kind, text)"),
say: jasmine.createSpy("Client.say(channel, text)")
};
module.exports.Client = Client;
// ===== helpers
module.exports._find = function(addr, nick) {
return generatedClients[addr+nick];
};
module.exports._reset = function() {
generatedClients = {};
}; |
Add a test restriction type for non-low end devices.
Renames small memory -> low end device to be consistent with our APIs.
BUG=308353
NOTRY=true
R=dtrainor@chromium.org
Review URL: https://codereview.chromium.org/52953003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@232073 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base.test.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for listing restrictions for a test method. For example, if a test method is only
* applicable on a phone with small memory:
* @Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_SMALL_MEMORY})
* Test classes are free to define restrictions and enforce them using reflection at runtime.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Restriction {
/** Specifies the test is only valid on phone form factors. */
public static final String RESTRICTION_TYPE_PHONE = "Phone";
/** Specifies the test is only valid on tablet form factors. */
public static final String RESTRICTION_TYPE_TABLET = "Tablet";
/** Specifies the test is only valid on low end devices that have less memory. */
public static final String RESTRICTION_TYPE_LOW_END_DEVICE = "Low_End_Device";
/** Specifies the test is only valid on non-low end devices. */
public static final String RESTRICTION_TYPE_NON_LOW_END_DEVICE = "Non_Low_End_Device";
/**
* @return A list of restrictions.
*/
public String[] value();
} | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base.test.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for listing restrictions for a test method. For example, if a test method is only
* applicable on a phone with small memory:
* @Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_SMALL_MEMORY})
* Test classes are free to define restrictions and enforce them using reflection at runtime.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Restriction {
/** Specifies the test is only valid on phone form factors. */
public static final String RESTRICTION_TYPE_PHONE = "Phone";
/** Specifies the test is only valid on tablet form factors. */
public static final String RESTRICTION_TYPE_TABLET = "Tablet";
/** Specifies the test is only valid on devices with a small amount of memory. */
public static final String RESTRICTION_TYPE_SMALL_MEMORY = "Small_Memory";
/**
* @return A list of restrictions.
*/
public String[] value();
} |
Remove dumb int use statement | <?php
namespace App\Storage;
use Amp\Mysql\Pool;
use Kelunik\Chat\Storage\RoomPermissionStorage;
use Kelunik\Chat\Storage\RoomStorage;
class MysqlRoomPermissionStorage implements RoomPermissionStorage {
private $mysql;
private $roomStorage;
public function __construct(Pool $mysql, RoomStorage $roomStorage) {
$this->mysql = $mysql;
}
public function getPermissions(int $user, int $room) {
$query = yield $this->mysql->prepare("SELECT `permissions` FROM `room_user` WHERE `user_id` = ? && `room_id` = ?", [
$user, $room,
]);
$result = yield $query->fetch();
if ($result) {
$permissions = json_decode($result["permissions"]);
return array_flip($permissions);
}
$room = yield $this->roomStorage->get($room);
if (!$room) {
return [];
}
if ($room->public) {
return array_flip(["read"]);
}
return [];
}
} | <?php
namespace App\Storage;
use Amp\Mysql\Pool;
use Kelunik\Chat\Storage\int;
use Kelunik\Chat\Storage\RoomPermissionStorage;
use Kelunik\Chat\Storage\RoomStorage;
class MysqlRoomPermissionStorage implements RoomPermissionStorage {
private $mysql;
private $roomStorage;
public function __construct(Pool $mysql, RoomStorage $roomStorage) {
$this->mysql = $mysql;
}
public function getPermissions(int $user, int $room) {
$query = yield $this->mysql->prepare("SELECT `permissions` FROM `room_user` WHERE `user_id` = ? && `room_id` = ?", [
$user, $room,
]);
$result = yield $query->fetch();
if ($result) {
$permissions = json_decode($result["permissions"]);
return array_flip($permissions);
}
$room = yield $this->roomStorage->get($room);
if (!$room) {
return [];
}
if ($room->public) {
return array_flip(["read"]);
}
return [];
}
} |
Fix package name to keep Eclipse happy. | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* A fake use case intended for use verifying that 'voltdb init --classes' works with non-trivial use cases.
* The theme is querying translations for 'Hello' in different languages.
*/
package org.voltdb_testprocs.fakeusecase.greetings; | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* A fake use case intended for use verifying that 'voltdb init --classes' works with non-trivial use cases.
* The theme is querying translations for 'Hello' in different languages.
*/
package fakeusecase.greetings; |
Change PyPI trove classifier for license terms. | import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
| import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
Change map download code to be case insensitive | """Model for handling operations on map data"""
import json
def persist_map(map_data, metadata, cursor, player_id):
"""Method for persisting map data"""
serialized_map_data = json.dumps(map_data)
map_sql = """INSERT INTO maps
(download_code, map_hash, player_id)
VALUES (%s, %s, %s)"""
cursor.execute(map_sql, (metadata['code'], metadata['hash'], player_id))
last_id_sql = "SELECT LAST_INSERT_ID()"
cursor.execute(last_id_sql)
last_id = cursor.fetchone()
map_data_sql = "INSERT INTO maps_data (map_id, json) VALUES (%s, %s)"
cursor.execute(map_data_sql, (last_id[0], serialized_map_data))
def find_map(map_code, cursor):
"""Method for retrieving map data"""
map_code_sql = "SELECT id FROM maps WHERE download_code = %s"
cursor.execute(map_code_sql, (map_code.upper(),))
map_id = cursor.fetchone()
if not map_id:
return None
map_data_sql = "SELECT json FROM maps_data WHERE map_id = %s"
cursor.execute(map_data_sql, (map_id[0],))
map_data = cursor.fetchone()
return json.loads(map_data[0])
| """Model for handling operations on map data"""
import json
def persist_map(map_data, metadata, cursor, player_id):
"""Method for persisting map data"""
serialized_map_data = json.dumps(map_data)
map_sql = """INSERT INTO maps
(download_code, map_hash, player_id)
VALUES (%s, %s, %s)"""
cursor.execute(map_sql, (metadata['code'], metadata['hash'], player_id))
last_id_sql = "SELECT LAST_INSERT_ID()"
cursor.execute(last_id_sql)
last_id = cursor.fetchone()
map_data_sql = "INSERT INTO maps_data (map_id, json) VALUES (%s, %s)"
cursor.execute(map_data_sql, (last_id[0], serialized_map_data))
def find_map(map_code, cursor):
"""Method for retrieving map data"""
map_code_sql = "SELECT id FROM maps WHERE download_code = %s"
cursor.execute(map_code_sql, (map_code,))
map_id = cursor.fetchone()
if not map_id:
return None
map_data_sql = "SELECT json FROM maps_data WHERE map_id = %s"
cursor.execute(map_data_sql, (map_id[0],))
map_data = cursor.fetchone()
return json.loads(map_data[0])
|
Use img tag instead of script tag for WebMetricReportingDAO | /**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
name: 'WebMetricsReportingDAO',
package: 'com.google.analytics',
extendsModel: 'com.google.analytics.AbstractMetricsReportingDAO',
imports: [
'document'
],
methods: {
send_: function(o, data, sink) {
var e = this.document.createElement('img');
e.src = this.endpoint + "?" + data;
}
}
});
| /**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
name: 'WebMetricsReportingDAO',
package: 'com.google.analytics',
extendsModel: 'com.google.analytics.AbstractMetricsReportingDAO',
imports: [
'document'
],
methods: {
send_: function(o, data, sink) {
var e = this.document.createElement('script');
e.onload = function() {
sink && sink.put && sink.put(o);
e.remove();
};
e.onerror = function() {
sink && sink.error && sink.error();
e.remove();
};
e.src = this.endpoint + "?" + data;
this.document.head.appendChild(e);
}
}
});
|
Fix funtion calls in test file | var psd = require("./psd-api.js");
/* Starts the psd-api below */
/* SAMPLE OBJECT TESTCASES */
/* PASSED */
// psd.get({lastName: "Abdalla"}); /* PASSED */
// psd.get({email: "hea113"}); /* PASSED */
// psd.get({userID: "hea113"}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: ""}); /* PASSED */
// psd.get({firstName: "", lastName: "Abdalla"}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: "Abdalla"}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: "Abdalla" , userID: "hea113"}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: "Abdalla" , userID: ""}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: "Abdalla" , userID: "hea113", email: "hea113@psu.edu"}); /* PASSED */
// psd.get({firstName: "Hozaifa", lastName: "Abdalla" , userID: "", email: "hea113@psu.edu"}); /* PASSED */
// psd.get({email: "yehya@psu.edu"});
psd.get("Hozaifa"); | var psd = require("./psd-api.js");
/* Starts the psd-api below */
/* SAMPLE OBJECT TESTCASES */
/* PASSED */
// psd({lastName: "Abdalla"}); /* PASSED */
// psd({email: "hea113"}); /* PASSED */
// psd({userID: "hea113"}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: ""}); /* PASSED */
// psd({firstName: "", lastName: "Abdalla"}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: "Abdalla"}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: "Abdalla" , userID: "hea113"}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: "Abdalla" , userID: ""}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: "Abdalla" , userID: "hea113", email: "hea113@psu.edu"}); /* PASSED */
// psd({firstName: "Hozaifa", lastName: "Abdalla" , userID: "", email: "hea113@psu.edu"}); /* PASSED */
// psd({
// email: "yehya@psu.edu"
// });
psd.get("Hozaifa"); |
Add comment to send func | import { HUB } from './hub';
import config from './config';
export function post (apiUrl, data) {
const payload = JSON.stringify(data);
const url = config.API_ROOT + apiUrl;
GM_xmlhttpRequest({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'X-Fbtrex-Version': config.VERSION,
'X-Fbtrex-Build': config.BUILD
},
data: payload,
onload: function (response) {
HUB.event('syncReponse', { url: url, response: response });
},
onerror: function (error) {
// We are parsing the payload because `data` will be modified by the handers/sync.js::sync function.
HUB.event('syncError', { url: url, data: JSON.parse(payload), error: error});
}
});
}
export const postTimeline = post.bind(null, 'timelines');
export const postDOM = post.bind(null, 'dom');
| import { HUB } from './hub';
import config from './config';
export function post (apiUrl, data) {
const payload = JSON.stringify(data);
const url = config.API_ROOT + apiUrl;
GM_xmlhttpRequest({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'X-Fbtrex-Version': config.VERSION,
'X-Fbtrex-Build': config.BUILD
},
data: payload,
onload: function (response) {
HUB.event('syncReponse', { url: url, response: response });
},
onerror: function (error) {
HUB.event('syncError', { url: url, data: JSON.parse(payload), error: error});
}
});
}
export const postTimeline = post.bind(null, 'timelines');
export const postDOM = post.bind(null, 'dom');
|
Fix int extractor (greedy > lazy) | # re_set.py
# Module for generating regex rules
# r1
import re
class Ree:
float = None
number = None
page_number = None
extract_int = None
@staticmethod
def init():
Ree.is_float()
Ree.is_number()
Ree.is_page_number('')
Ree.extract_int_compile()
@staticmethod
def is_page_number(page_param):
Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param))
@staticmethod
def is_float(price_sep=',.'):
Ree.float = re.compile('(?P<price>\d+([{}]\d+)?)'.format(price_sep))
@staticmethod
def is_number():
Ree.number = re.compile('^\d+$')
@staticmethod
def extract_int_compile():
Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$')
| # re_set.py
# Module for generating regex rules
# r1
import re
class Ree:
float = None
number = None
page_number = None
extract_int = None
@staticmethod
def init():
Ree.is_float()
Ree.is_number()
Ree.is_page_number('')
Ree.extract_int_compile()
@staticmethod
def is_page_number(page_param):
Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param))
@staticmethod
def is_float(price_sep=',.'):
Ree.float = re.compile('(?P<price>\d+([{}]\d+)?)'.format(price_sep))
@staticmethod
def is_number():
Ree.number = re.compile('^\d+$')
@staticmethod
def extract_int_compile():
Ree.extract_int = re.compile('^.+(?P<int>\d+).+$')
|
Trim slash suffix from the server URL | package main
import (
"crypto/tls"
"fmt"
"os"
"strings"
"github.com/codegangsta/cli"
"github.com/drone/drone-go/drone"
"github.com/jackspirou/syscerts"
)
type handlerFunc func(*cli.Context, drone.Client) error
// handle wraps the command function handlers and
// sets up the environment.
func handle(c *cli.Context, fn handlerFunc) {
var token = c.GlobalString("token")
var server = strings.TrimSuffix(c.GlobalString("server"), "/")
// if no server url is provided we can default
// to the hosted Drone service.
if len(server) == 0 {
fmt.Println("Error: you must provide the Drone server address.")
os.Exit(1)
}
if len(token) == 0 {
fmt.Println("Error: you must provide your Drone access token.")
os.Exit(1)
}
// attempt to find system CA certs
certs := syscerts.SystemRootsPool()
tlsConfig := &tls.Config{RootCAs: certs}
// create the drone client with TLS options
client := drone.NewClientTokenTLS(server, token, tlsConfig)
// handle the function
if err := fn(c, client); err != nil {
println(err.Error())
os.Exit(1)
}
}
| package main
import (
"crypto/tls"
"fmt"
"os"
"github.com/codegangsta/cli"
"github.com/drone/drone-go/drone"
"github.com/jackspirou/syscerts"
)
type handlerFunc func(*cli.Context, drone.Client) error
// handle wraps the command function handlers and
// sets up the environment.
func handle(c *cli.Context, fn handlerFunc) {
var token = c.GlobalString("token")
var server = c.GlobalString("server")
// if no server url is provided we can default
// to the hosted Drone service.
if len(server) == 0 {
fmt.Println("Error: you must provide the Drone server address.")
os.Exit(1)
}
if len(token) == 0 {
fmt.Println("Error: you must provide your Drone access token.")
os.Exit(1)
}
// attempt to find system CA certs
certs := syscerts.SystemRootsPool()
tlsConfig := &tls.Config{RootCAs: certs}
// create the drone client with TLS options
client := drone.NewClientTokenTLS(server, token, tlsConfig)
// handle the function
if err := fn(c, client); err != nil {
println(err.Error())
os.Exit(1)
}
}
|
Use logger is method isSorted | package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Collection is unordered at element " + current);
}
return false;
}
}
return true;
}
}
| package com.alexrnl.commons.utils;
import java.util.Iterator;
import java.util.Objects;
import java.util.logging.Logger;
/**
* Utilities on collections.<br />
* @author Alex
*/
public final class CollectionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(CollectionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private CollectionUtils () {
super();
}
/**
* Check if a collection is sorted.<br />
* @param collection
* the collection to check.
* @return <code>true</code> if the collection is sorted.
*/
public static <T extends Comparable<? super T>> boolean isSorted (final Iterable<T> collection) {
Objects.requireNonNull(collection);
final Iterator<T> it = collection.iterator();
while (it.hasNext()) {
final T current = it.next();
if (it.hasNext() && current.compareTo(it.next()) > 0) {
return false;
}
}
return true;
}
}
|
Test DEBUG to serve static files by django | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns(
'',
(r'^auth/', include('helios_auth.urls')),
(r'^helios/', include('helios.urls')),
(r'^', include('server_ui.urls')),
(r'^admin/', include(admin.site.urls))
)
if settings.DEBUG: # otherwise, they should be served by a webserver like apache
urlpatterns += patterns(
'',
# SHOULD BE REPLACED BY APACHE STATIC PATH
(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}),
(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}),
(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}),
(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}),
(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'})
)
| # -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns(
'',
(r'^auth/', include('helios_auth.urls')),
(r'^helios/', include('helios.urls')),
# SHOULD BE REPLACED BY APACHE STATIC PATH
(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}),
(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}),
(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}),
(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}),
(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'}),
(r'^', include('server_ui.urls')),
(r'^admin/', include(admin.site.urls))
)
|
Swap out modules in py2 mode in a cleaner fashion.
PiperOrigin-RevId: 288526813
Change-Id: I86efd4d804c0c873856307cf4a969270eb7bbae8 | # Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Miscellaneous utilities that don't fit anywhere else."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import sys
import six
class BasicRef(object):
"""This shim emulates the nonlocal keyword in Py2-compatible source."""
def __init__(self, init_value):
self.value = init_value
def deprecated_py2_support(module_name):
"""Swaps calling module with a Py2-specific implementation. Noop in Py3."""
if six.PY2:
legacy_module = importlib.import_module(module_name + '_deprecated_py2')
sys.modules[module_name] = legacy_module
| # Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Miscellaneous utilities that don't fit anywhere else."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import sys
import types
import six
class BasicRef(object):
"""This shim emulates the nonlocal keyword in Py2-compatible source."""
def __init__(self, init_value):
self.value = init_value
def deprecated_py2_support(module_name):
"""Swaps calling module with a Py2-specific implementation. Noop in Py3."""
if six.PY2:
legacy_module = importlib.import_module(module_name + '_deprecated_py2')
current_module = sys.modules[module_name]
for name, target_val in legacy_module.__dict__.items():
if isinstance(target_val, types.FunctionType):
replacement = types.FunctionType(
target_val.__code__, current_module.__dict__, target_val.__name__,
target_val.__defaults__, target_val.__closure__)
current_module.__dict__[name] = replacement
|
Document using Java 9 because that's what Travis-CI uses. | package edu.pdx.cs410J.grader;
import jdk.javadoc.doclet.Doclet;
import jdk.javadoc.doclet.DocletEnvironment;
import jdk.javadoc.doclet.Reporter;
import javax.lang.model.SourceVersion;
import javax.tools.Diagnostic;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* This <A
* href="https://docs.oracle.com/javase/9/docs/api/jdk/javadoc/doclet/package-summary.html">doclet</A>
* extracts the API documentation (Javadocs)
* from a student's project submission and produces a text summary of
* them. It is used for grading a student's Javadocs.
*
* @author David Whitlock
* @since Summer 2004 (rewritten for Java 6 in Summer 2018)
*/
public class APIDocumentationDoclet implements Doclet {
private Reporter reporter;
@Override
public void init(Locale locale, Reporter reporter) {
this.reporter = reporter;
}
@Override
public String getName() {
return "API Documentation Doclet";
}
@Override
public Set<? extends Option> getSupportedOptions() {
return new HashSet<>();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_9;
}
@Override
public boolean run(DocletEnvironment environment) {
reporter.print(Diagnostic.Kind.NOTE, "Doclet.run()");
return true;
}
}
| package edu.pdx.cs410J.grader;
import jdk.javadoc.doclet.Doclet;
import jdk.javadoc.doclet.DocletEnvironment;
import jdk.javadoc.doclet.Reporter;
import javax.lang.model.SourceVersion;
import javax.tools.Diagnostic;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* This <A
* href="https://docs.oracle.com/javase/9/docs/api/jdk/javadoc/doclet/package-summary.html">doclet</A>
* extracts the API documentation (Javadocs)
* from a student's project submission and produces a text summary of
* them. It is used for grading a student's Javadocs.
*
* @author David Whitlock
* @since Summer 2004 (rewritten for Java 6 in Summer 2018)
*/
public class APIDocumentationDoclet implements Doclet {
private Reporter reporter;
@Override
public void init(Locale locale, Reporter reporter) {
this.reporter = reporter;
}
@Override
public String getName() {
return "API Documentation Doclet";
}
@Override
public Set<? extends Option> getSupportedOptions() {
return new HashSet<>();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_10;
}
@Override
public boolean run(DocletEnvironment environment) {
reporter.print(Diagnostic.Kind.NOTE, "Doclet.run()");
return true;
}
}
|
Support for Lastuser push notifications. | # -*- coding: utf-8 -*-
from flask import Response, redirect, flash
from flask.ext.lastuser.sqlalchemy import UserManager
from coaster.views import get_next_url
from hasjob import app, lastuser
from hasjob.models import db, User
lastuser.init_usermanager(UserManager(db, User))
@app.route('/login')
@lastuser.login_handler
def login():
return {'scope': 'id email organizations'}
@app.route('/logout')
@lastuser.logout_handler
def logout():
flash(u"You are now logged out", category='info')
return get_next_url()
@app.route('/login/redirect')
@lastuser.auth_handler
def lastuserauth():
# Save the user object
db.session.commit()
return redirect(get_next_url())
@app.route('/login/notify')
@lastuser.notification_handler
def lastusernotify(user):
# Save the user object
db.session.commit()
@lastuser.auth_error_handler
def lastuser_error(error, error_description=None, error_uri=None):
if error == 'access_denied':
flash("You denied the request to login", category='error')
return redirect(get_next_url())
return Response(u"Error: %s\n"
u"Description: %s\n"
u"URI: %s" % (error, error_description, error_uri),
mimetype="text/plain")
| # -*- coding: utf-8 -*-
from flask import Response, redirect, flash
from flask.ext.lastuser.sqlalchemy import UserManager
from coaster.views import get_next_url
from hasjob import app, lastuser
from hasjob.models import db, User
lastuser.init_usermanager(UserManager(db, User))
@app.route('/login')
@lastuser.login_handler
def login():
return {'scope': 'id email organizations'}
@app.route('/logout')
@lastuser.logout_handler
def logout():
flash(u"You are now logged out", category='info')
return get_next_url()
@app.route('/login/redirect')
@lastuser.auth_handler
def lastuserauth():
# Save the user object
db.session.commit()
return redirect(get_next_url())
@lastuser.auth_error_handler
def lastuser_error(error, error_description=None, error_uri=None):
if error == 'access_denied':
flash("You denied the request to login", category='error')
return redirect(get_next_url())
return Response(u"Error: %s\n"
u"Description: %s\n"
u"URI: %s" % (error, error_description, error_uri),
mimetype="text/plain")
|
Use eval-source-map to speed up rebuild performance | var path = require('path');
const jsSourcePath = path.join(__dirname, '/src/js');
const scssSourcePath = path.join(__dirname, '/src/scss');
module.exports = {
entry: [
path.join(__dirname, 'src/js/index.js')
],
output: {
path: path.join(__dirname, "public/"),
publicPath: "/",
filename: "app.min.js"
},
module: {
noParse: [
/aws\-sdk/
],
loaders: [{
test: /node_modules[\\\/]auth0-lock[\\\/].*\.js$/,
loaders: [
'transform-loader/cacheable?brfs',
'transform-loader/cacheable?packageify'
],
}, {
test: /node_modules[\\\/]auth0-lock[\\\/].*\.ejs$/,
loader: 'transform-loader/cacheable?ejsify',
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader'],
exclude: /node_modules/,
include: jsSourcePath
}, {
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap'],
include: scssSourcePath
}]
},
devtool: 'eval-source-map'
} | var path = require('path');
const jsSourcePath = path.join(__dirname, '/src/js');
const scssSourcePath = path.join(__dirname, '/src/scss');
module.exports = {
entry: [
path.join(__dirname, 'src/js/index.js')
],
output: {
path: path.join(__dirname, "public/"),
publicPath: "/",
filename: "app.min.js"
},
module: {
noParse: [
/aws\-sdk/
],
loaders: [{
test: /node_modules[\\\/]auth0-lock[\\\/].*\.js$/,
loaders: [
'transform-loader/cacheable?brfs',
'transform-loader/cacheable?packageify'
],
}, {
test: /node_modules[\\\/]auth0-lock[\\\/].*\.ejs$/,
loader: 'transform-loader/cacheable?ejsify',
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader'],
exclude: /node_modules/,
include: jsSourcePath
}, {
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap'],
include: scssSourcePath
}]
},
devtool: 'source-map'
} |
Add code http 200 as plain integer for compatibility | <?php
namespace Screamz\SecureDownloadBundle\Core\Classes\Response;
use Symfony\Component\HttpFoundation\Response;
/**
* Class BlobResponse
*
* This response should be used when you need to return a blob (Like base64 encoded image).
*
* @author Andréas HANSS <ahanss@kaliop.com>
*/
class BlobResponse extends Response
{
/**
* BlobResponse constructor.
*
* @param string $documentPath The path of the document to encode as B64
* @param int $status
* @param array $headers
*
*/
public function __construct($documentPath, $status = 200, array $headers = array())
{
$content = base64_encode(file_get_contents($documentPath));
$finfoMineType = finfo_open(FILEINFO_MIME_TYPE);
$headers['Content-Type'] = finfo_file($finfoMineType, $documentPath);
parent::__construct($content, $status, $headers);
}
} | <?php
namespace Screamz\SecureDownloadBundle\Core\Classes\Response;
use Symfony\Component\HttpFoundation\Response;
/**
* Class BlobResponse
*
* This response should be used when you need to return a blob (Like base64 encoded image).
*
* @author Andréas HANSS <ahanss@kaliop.com>
*/
class BlobResponse extends Response
{
/**
* BlobResponse constructor.
*
* @param string $documentPath The path of the document to encode as B64
* @param int $status
* @param array $headers
*
*/
public function __construct($documentPath, $status = self::HTTP_OK, array $headers = array())
{
$content = base64_encode(file_get_contents($documentPath));
$finfoMineType = finfo_open(FILEINFO_MIME_TYPE);
$headers['Content-Type'] = finfo_file($finfoMineType, $documentPath);
parent::__construct($content, $status, $headers);
}
} |
Replace syntax disallowed by eslint config | /* eslint no-console:0 */
// mocha/jsdom setup from:
// http://reactjsnews.com/testing-in-react/
import jsdom from 'jsdom';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
// https://github.com/producthunt/chai-enzyme
chai.use(chaiEnzyme());
// setup the simplest document possible
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
// get the window object out of the document
const win = doc.defaultView;
// set globals for mocha that make access to document and window feel
// natural in the test environment
global.document = doc;
global.window = win;
// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal(window) {
Object.keys(window).forEach((key) => {
if (key in global) {
return;
}
global[key] = window[key];
});
}
// take all properties of the window object and also attach it to the
// mocha global object
propagateToGlobal(win);
| /* eslint no-console:0 */
// mocha/jsdom setup from:
// http://reactjsnews.com/testing-in-react/
import jsdom from 'jsdom';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
// https://github.com/producthunt/chai-enzyme
chai.use(chaiEnzyme());
// setup the simplest document possible
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
// get the window object out of the document
const win = doc.defaultView;
// set globals for mocha that make access to document and window feel
// natural in the test environment
global.document = doc;
global.window = win;
// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal(window) {
for (const key of Object.keys(window)) {
if (key in global) {
// eslint-disable-next-line no-continue
continue;
}
global[key] = window[key];
}
}
// take all properties of the window object and also attach it to the
// mocha global object
propagateToGlobal(win);
|
Change startsWith param test method to be use with all version of nodejs | /**
* Homemade gulp options manager
*/
module.exports = {
options: null,
read: function(argv) {
var optionsClean = [];
argv.slice(2, argv.length).forEach(function(p) {
if (p.indexOf('--') === 0 && p.length !== 2) {
optionsClean.push(p.replace('--', ''));
}
});
return optionsClean;
},
has: function(param) {
if (!this.options) {
this.options = this.read(process.argv);
}
return (this.options.indexOf(param) !== -1);
}
};
| /**
* Homemade gulp options manager
*/
module.exports = {
options: null,
read: function(argv) {
var optionsClean = [];
argv.slice(2, argv.length).forEach(function(p) {
if (p.startsWith('--') && p.length !== 2) {
optionsClean.push(p.replace('--', ''));
}
});
return optionsClean;
},
has: function(param) {
if (!this.options) {
this.options = this.read(process.argv);
}
return (this.options.indexOf(param) !== -1);
}
};
|
Fix bug in Eloquent model update routine. | <?php namespace Illuminate\Workbench;
class Starter {
/**
* Load the workbench vendor auto-load files.
*
* @param string $path
* @param Illuminate\Filesystem $files
* @return void
*/
public static function start($path, $finder = null, $files = null)
{
$finder = $finder ?: new \Symfony\Component\Finder\Finder;
// We will use the finder to locate all "autoload.php" files in the workbench
// directory, then we will include them each so that they are able to load
// the appropriate classes and file used by the given workbench package.
$files = $files ?: new \Illuminate\Filesystem\Filesystem;
$autoloads = $finder->in($path)->files()->name('autoload.php');
foreach ($autoloads as $file)
{
$files->requireOnce($file->getRealPath());
}
}
}
| <?php namespace Illuminate\Workbench;
class Starter {
/**
* Load the workbench vendor auto-load files.
*
* @param string $path
* @param Illuminate\Filesystem $files
* @return void
*/
public static function start($path, $finder = null, $files = null)
{
$finder = $finder ?: new \Symfony\Component\Finder\Finder;
$files = $files ?: new \Illuminate\Filesystem\Filesystem;
// We will use the finder to locate all "autoload.php" files in the workbench
// directory, then we will include them each so that they are able to load
// the appropriate classes and file used by the given workbench package.
$autoloads = $finder->in($path)->files()->name('autoload.php');
foreach ($autoloads as $file)
{
$files->requireOnce($file->getRealPath());
}
}
}
|
Add our meta tag CSRF token to every ajax request | (function($){
$(function(){
$('.tooltipped').tooltip({delay: 50});
// Smooth scroll for links on the current page
$(document.body).on('click', 'a[href^="#"]', function (e) {
e.preventDefault();
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
var offset = 0;
if (target[0].id.indexOf("feature-") == 0) {
offset = 100;
}
$('html,body').animate({
scrollTop: target.offset().top - offset
}, 1000);
return false;
}
}
});
// Allow toasts to be dismissed with a click
$(document).on('click', '#toast-container .toast', function() {
$(this).fadeOut(function(){
$(this).remove();
});
});
// Setup all ajax queries to use the CSRF token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
})(jQuery); | (function($){
$(function(){
$('.tooltipped').tooltip({delay: 50});
// Smooth scroll for links on the current page
$(document.body).on('click', 'a[href^="#"]', function (e) {
e.preventDefault();
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
var offset = 0;
if (target[0].id.indexOf("feature-") == 0) {
offset = 100;
}
$('html,body').animate({
scrollTop: target.offset().top - offset
}, 1000);
return false;
}
}
});
// Allow toasts to be dismissed with a click
$(document).on('click', '#toast-container .toast', function() {
$(this).fadeOut(function(){
$(this).remove();
});
});
});
})(jQuery); |
Add functions to get case report links | var getUrl = function(url, callback) {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", callback);
oReq.open("GET", url);
oReq.send();
}
var extractHearingType = function(hearingRow) {
return hearingRow.querySelectorAll('td')[4].textContent.trim();
};
var extractCaseReportLink = function(hearingRow) {
return hearingRow.querySelectorAll('td')[2].querySelector('a').href.replace('criminalcalendar', 'criminalcasereport');
};
var isPrelim = function(hearingRow) {
return extractHearingType(hearingRow) == "PRELIMINARY HEARING";
};
var hearingNodes = function() {
return document.querySelectorAll('tr[id^="tr_row"]');
};
var nodeListToArray = function(nodeList) {
var a = [];
for (var i = 0, l = nodeList.length; i < l; i += 1) {
a[a.length] = nodeList[i];
};
return a;
};
var extractHearings = function() {
return nodeListToArray(hearingNodes());
};
var filterPrelims = function(hearings) {
return hearings.filter(isPrelim);
};
var hearings = extractHearings();
var prelims = filterPrelims(hearings);
var prelimLinks = prelims.forEach(extractCaseReportLink);
console.log("There are " + hearings.length + " hearings.");
console.log("There are " + prelims.length + " prelims.");
console.log(prelimLinks);
| var extractHearingType = function(hearingRow) {
return hearingRow.querySelectorAll('td')[4].textContent.trim();
};
var isPrelim = function(hearingRow) {
return extractHearingType(hearingRow) == "PRELIMINARY HEARING";
};
var hearingNodes = function() {
return document.querySelectorAll('tr[id^="tr_row"]');
};
var nodeListToArray = function(nodeList) {
var a = [];
for (var i = 0, l = nodeList.length; i < l; i += 1) {
a[a.length] = nodeList[i];
};
return a;
};
var extractHearings = function() {
return nodeListToArray(hearingNodes());
};
var filterPrelims = function(hearings) {
return hearings.filter(isPrelim);
};
var hearings = extractHearings();
var prelims = filterPrelims(hearings);
console.log("There are " + hearings.length + " hearings.");
console.log("There are " + prelims.length + " prelims.");
|
[pH7Tpl:Parsable] Remove useless "defined or exit" code | <?php
/***************************************************************************
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @category PH7 Template Engine
* @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license CC-BY License - http://creativecommons.org/licenses/by/3.0/
***************************************************************************/
namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;
interface Parsable
{
public function autoIncludeStatements();
public function includeStatements();
public function phpOpeningTag();
public function phpClosingTag();
public function phpOpeningTagWithEchoFunction();
public function ifStatement();
public function elseifStatement();
public function elseStatement();
public function forLoopStatement();
public function whileLoopStatement();
public function eachLoopStatement();
public function closingBlockStructures();
public function variable();
public function designModelFunction();
public function escapeFunction();
public function langFunctions();
public function literalFunction();
public function clearComment();
}
| <?php
/***************************************************************************
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @category PH7 Template Engine
* @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license CC-BY License - http://creativecommons.org/licenses/by/3.0/
***************************************************************************/
namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;
defined('PH7') or exit('Restricted access');
interface Parsable
{
public function autoIncludeStatements();
public function includeStatements();
public function phpOpeningTag();
public function phpClosingTag();
public function phpOpeningTagWithEchoFunction();
public function ifStatement();
public function elseifStatement();
public function elseStatement();
public function forLoopStatement();
public function whileLoopStatement();
public function eachLoopStatement();
public function closingBlockStructures();
public function variable();
public function designModelFunction();
public function escapeFunction();
public function langFunctions();
public function literalFunction();
public function clearComment();
}
|
feat: Enable deferred bootstrap mode for JPA
Fixes #250 | package amu.zhcet;
import amu.zhcet.email.EmailProperties;
import amu.zhcet.firebase.FirebaseProperties;
import amu.zhcet.security.SecureProperties;
import amu.zhcet.storage.StorageProperties;
import io.sentry.Sentry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.datatables.repository.DataTablesRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.config.BootstrapMode;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import javax.servlet.DispatcherType;
@SpringBootApplication
@EnableJpaRepositories(
repositoryFactoryBeanClass = DataTablesRepositoryFactoryBean.class,
bootstrapMode = BootstrapMode.DEFERRED)
@EnableConfigurationProperties({ApplicationProperties.class, SecureProperties.class,
EmailProperties.class, StorageProperties.class, FirebaseProperties.class})
public class CoreApplication {
public static void main(String[] args) {
Sentry.init();
SpringApplication.run(CoreApplication.class, args);
}
}
| package amu.zhcet;
import amu.zhcet.email.EmailProperties;
import amu.zhcet.firebase.FirebaseProperties;
import amu.zhcet.security.SecureProperties;
import amu.zhcet.storage.StorageProperties;
import io.sentry.Sentry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.datatables.repository.DataTablesRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import javax.servlet.DispatcherType;
@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = DataTablesRepositoryFactoryBean.class)
@EnableConfigurationProperties({ApplicationProperties.class, SecureProperties.class,
EmailProperties.class, StorageProperties.class, FirebaseProperties.class})
public class CoreApplication {
public static void main(String[] args) {
Sentry.init();
SpringApplication.run(CoreApplication.class, args);
}
}
|
Add logic for availability population | import random
import csv
from django.core.management.base import BaseCommand, CommandError
from portal.models import Location
class Command(BaseCommand):
"""
"""
def handle(self, *args, **options):
"""
"""
with open('availability.csv', 'rb') as availability_file:
reader = csv.DictReader(availability_file)
for row in reader:
try:
key = row['Key']
l = Location.objects.get(ecm_key=key)
l.availability = row['Availability']
l.save()
print l.availability
print ''
except:
print 'Uh oh!'
| import random
import csv
from django.core.management.base import BaseCommand, CommandError
from portal.models import Location
class Command(BaseCommand):
"""
"""
def handle(self, *args, **options):
"""
"""
with open('availability.csv', 'rb') as availability_file:
reader = csv.DictReader(availability_file)
for row in reader:
try:
key = row['Key']
l = Location.objects.get(ecm_key=key)
print l.site_name
|
Replace promise with async await and handle error cases | import fetch from 'node-fetch';
import { userModel } from '../models/index';
export const authenticatedWithToken = async (req, res, next) => {
if (req && req.cookies && req.cookies.jwt && req.headers && req.headers.csrf) {
let csrf = req.headers.csrf;
let jwt = req.cookies.jwt;
const opts = {
headers: {
csrf,
jwt
}
};
let res = await fetch('http://localhost:3002/signcheck', opts);
if (res.status === 401) {
return null;
}
let resJson = await res.json();
if (!resJson) {
next();
} else {
try {
let user = await userModel.findOne({name: resJson.name}).exec();
if (user) {
req.user = user;
next();
}
} catch (error) {
console.log(error)
}
}
} else {
req.err = 'Either the cookie or the token is missing';
next();
}
}; | import fetch from 'node-fetch';
import { userModel } from '../models/index';
export const authenticatedWithToken = (req, res, next) => {
let csrf;
let jwt;
if (req && req.cookies && req.headers){
csrf = req.headers.csrf;
jwt = req.cookies.jwt;
const opts = {
headers: {
csrf,
jwt
}
};
fetch('http://localhost:3002/signcheck', opts)
.then(res => {
if (res.status === 401) {
return null;
}
return res.json();
})
.then(user => {
if (!user) {
return next();
} else {
return userModel.findOne({name: user.name})
.then(user => {
req.user = user;
return next();
});
}
})
}
}; |
Fix nbits bug where value should be 8, instead of 16 | 'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var NBITS = 8;
// DIV2 //
/**
* FUNCTION: div2( x )
* Converts a nonnegative integer to a literal bit representation using the divide-by-2 algorithm.
*
* @param {Number} x - nonnegative integer
* @returns {String} bit representation
*/
function div2( x ) {
var str = '';
var i;
var y;
// We repeatedly divide by 2 and check for a remainder. If a remainder exists, the number is odd and we add a '1' bit...
i = NBITS;
while ( x > 0 && i ) {
y = x / 2;
x = floor( y );
if ( y === x ) {
str = '0' + str;
} else {
str = '1' + str;
}
i -= 1;
}
return str;
} // end FUNCTION div2()
// EXPORTS //
module.exports = div2;
| 'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var NBITS = 16;
// DIV2 //
/**
* FUNCTION: div2( x )
* Converts a nonnegative integer to a literal bit representation using the divide-by-2 algorithm.
*
* @param {Number} x - nonnegative integer
* @returns {String} bit representation
*/
function div2( x ) {
var str = '';
var i;
var y;
// We repeatedly divide by 2 and check for a remainder. If a remainder exists, the number is odd and we add a '1' bit...
i = NBITS;
while ( x > 0 && i ) {
y = x / 2;
x = floor( y );
if ( y === x ) {
str = '0' + str;
} else {
str = '1' + str;
}
i -= 1;
}
return str;
} // end FUNCTION div2()
// EXPORTS //
module.exports = div2;
|
Change profile call to auth/account | import { get, post, put } from '../lib/apiService';
export function getUser(id) {
return get('nominations', `users/${id}`);
}
export function getMe() {
return get('v2', 'auth/account');
}
export function getUserList(pageNumber = 1, search, affiliationId) {
pageNumber = pageNumber < 1 ? 1 : pageNumber;
return get('nominations', 'users', {
page: pageNumber,
search,
affiliationId
});
}
export function getPendingUserList(pageNumber = 1, search) {
return get('nominations', 'users/pending', {
page: pageNumber,
search: search
});
}
export function createUser(user) {
return post('nominations', 'users', user);
}
export function updateUser({ households, ...user }) {
return put('nominations', `users/${user.id}`, user);
}
export function approveUser(id) {
return post('nominations', `users/${id}/approve`);
}
export function declineUser(id) {
return post('nominations', `users/${id}/decline`);
}
| import { get, post, put } from '../lib/apiService';
export function getUser(id) {
return get('nominations', `users/${id}`);
}
export function getMe() {
return get('nominations', 'users/me/profile');
}
export function getUserList(pageNumber = 1, search, affiliationId) {
pageNumber = pageNumber < 1 ? 1 : pageNumber;
return get('nominations', 'users', {
page: pageNumber,
search,
affiliationId
});
}
export function getPendingUserList(pageNumber = 1, search) {
return get('nominations', 'users/pending', {
page: pageNumber,
search: search
});
}
export function createUser(user) {
return post('nominations', 'users', user);
}
export function updateUser({ households, ...user }) {
return put('nominations', `users/${user.id}`, user);
}
export function approveUser(id) {
return post('nominations', `users/${id}/approve`);
}
export function declineUser(id) {
return post('nominations', `users/${id}/decline`);
}
|
Allow a path prefix to be added to output | /*
* grunt-assets-map
* https://github.com/Peterbyte/grunt-assets-map
*
* Copyright (c) 2015 Peter Bouquet
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs');
module.exports = function(grunt) {
grunt.registerTask('assets_map', 'Creates a map of assets to versioned assets', function(){
var done = this.async();
var opts = this.options();
var hashedAssets = grunt.file.expand(opts.paths),
assetMap = {},
prefixPath = opts.prefixPath || "";
for(var assetIndex in hashedAssets) {
var asset = prefixPath+hashedAssets[assetIndex].replace(opts.stripPath, "");
var splitAsset = asset.split('.');
if(splitAsset.length >= 2) {
splitAsset.splice(splitAsset.length-2, 1);
var unhashedName = splitAsset.join(".");
assetMap[unhashedName] = asset;
}
}
var mapFileName = opts.fileName || 'asset-hash-map.json';
fs.writeFile(mapFileName, JSON.stringify(assetMap), function(err){
if(err) throw err;
grunt.log.writeln("Asset map written to '"+mapFileName+"' successfully");
done();
});
});
};
| /*
* grunt-assets-map
* https://github.com/Peterbyte/grunt-assets-map
*
* Copyright (c) 2015 Peter Bouquet
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs');
module.exports = function(grunt) {
grunt.registerTask('assets_map', 'Creates a map of assets to versioned assets', function(){
var done = this.async();
var opts = this.options();
var hashedAssets = grunt.file.expand(opts.paths),
assetMap = {};
for(var assetIndex in hashedAssets) {
var asset = hashedAssets[assetIndex].replace(opts.stripPath, "");
var splitAsset = asset.split('.');
if(splitAsset.length >= 2) {
splitAsset.splice(splitAsset.length-2, 1);
var unhashedName = splitAsset.join(".");
assetMap[unhashedName] = asset;
}
}
var mapFileName = opts.fileName || 'asset-hash-map.json';
fs.writeFile(mapFileName, JSON.stringify(assetMap), function(err){
if(err) throw err;
grunt.log.writeln("Asst map written to '"+mapFileName+"' successfully");
done();
});
});
};
|
Fix trivial unit test error that started when numpy version changed
The version of numpy brought in by pip changed, which changed some
test outputs in meaningless ways (ie, spaces), and
those meaningless changes broke a unit test with
assertEquals( "string literal", test(something) )
This change fixes the unit test error, without at all addressing
the underlying issue (hyper-sensitive string comparison). | #!/usr/bin/env python
import numpy as np
from pych.extern import Chapel
@Chapel()
def printArray(arr=np.ndarray):
"""
arr += 1;
writeln(arr);
"""
return None
if __name__ == "__main__":
arr = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
print arr
printArray(arr);
print arr
import testcase
# contains the general testing method, which allows us to gather output
import os.path
def test_modify_array_argument_reals():
out = testcase.runpy(os.path.realpath(__file__))
# The first time this test is run, it may contain output notifying that
# a temporary file has been created. The important part is that this
# expected output follows it (enabling the test to work for all runs, as
# the temporary file message won't occur in the second run) But that means
# we can't use ==
assert out.endswith("[ 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.]\n");
| #!/usr/bin/env python
import numpy as np
from pych.extern import Chapel
@Chapel()
def printArray(arr=np.ndarray):
"""
arr += 1;
writeln(arr);
"""
return None
if __name__ == "__main__":
arr = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
print arr
printArray(arr);
print arr
import testcase
# contains the general testing method, which allows us to gather output
import os.path
def test_modify_array_argument_reals():
out = testcase.runpy(os.path.realpath(__file__))
# The first time this test is run, it may contain output notifying that
# a temporary file has been created. The important part is that this
# expected output follows it (enabling the test to work for all runs, as
# the temporary file message won't occur in the second run) But that means
# we can't use ==
assert out.endswith("[ 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.]\n");
|
Add second alternative to solution | var MaxProduct = function(){};
/*
alternative could be to sort it in descending order and multiply the first two elements, but it would be slower.
arr.sort(function(a, b){
return b-a;
});
console.log(arr[0] * arr[1]);
return arr[0] * arr[1];
*/
MaxProduct.prototype.maxProduct = function(arr){
var biggest = -Infinity, next_biggest = -Infinity;
for (var i = 0, n = arr.length; i < n; ++i) {
var nr = +arr[i]; // convert to number first
if (nr > biggest) {
next_biggest = biggest; // save previous biggest value
biggest = nr;
} else if (nr < biggest && nr > next_biggest) {
next_biggest = nr; // new second biggest value
}
}
return biggest * next_biggest;
};
// second alternative
MaxProduct.prototype.maxProduct_v2 = function (a) {
var biggest = Math.max.apply(Math, a);
a.splice(a.indexOf(biggest), 1);
return biggest * Math.max.apply(Math, a);
};
module.exports = MaxProduct
| var MaxProduct = function(){};
/*
alternative could be to sort it in descending order and multiply the first two elements, but it would be slower.
arr.sort(function(a, b){
return b-a;
});
console.log(arr[0] * arr[1]);
return arr[0] * arr[1];
*/
MaxProduct.prototype.maxProduct = function(arr){
var biggest = -Infinity, next_biggest = -Infinity;
for (var i = 0, n = arr.length; i < n; ++i) {
var nr = +arr[i]; // convert to number first
if (nr > biggest) {
next_biggest = biggest; // save previous biggest value
biggest = nr;
} else if (nr < biggest && nr > next_biggest) {
next_biggest = nr; // new second biggest value
}
}
return biggest * next_biggest;
};
module.exports = MaxProduct
|
Fix PEP8: W292 no newline at end of file | class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
| class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales |
Reduce default sampling period to make testing easier | // Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
'use strict';
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var config = {
port: process.env.PA_MENTOR_PORT || 8080,
dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/pa-mentor-test',
updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
retryInterval: Math.max(SECOND, process.env.PA_MENTOR_RETRY_INTERVAL || MINUTE),
samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || DAY),
samplingBatchSize: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_BATCH_SIZE || 3 * HOUR),
maxGameDuration: 8 * HOUR // just a guess; used in the updater to do overlapping fetches to avoid missing games
};
module.exports = config;
| // Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
'use strict';
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var config = {
port: process.env.PA_MENTOR_PORT || 8080,
dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/pa-mentor-test',
updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
retryInterval: Math.max(SECOND, process.env.PA_MENTOR_RETRY_INTERVAL || MINUTE),
samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || 3 * DAY),
samplingBatchSize: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_BATCH_SIZE || 3 * HOUR),
maxGameDuration: 8 * HOUR // just a guess; used in the updater to do overlapping fetches to avoid missing games
};
module.exports = config;
|
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations | from oauthlib.common import generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
class BaseHashGenerator(object):
"""
All generators should extend this class overriding `.hash()` method.
"""
def hash(self):
raise NotImplementedError()
class ClientIdGenerator(BaseHashGenerator):
def hash(self):
"""
Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2
for Basic Authentication scheme
"""
client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "")
return oauthlib_generate_client_id(length=40, chars=client_id_charset)
class ClientSecretGenerator(BaseHashGenerator):
def hash(self):
return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET)
def generate_client_id():
"""
Generate a suitable client id
"""
client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS()
return client_id_generator.hash()
def generate_client_secret():
"""
Generate a suitable client secret
"""
client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS()
return client_secret_generator.hash()
| from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
class BaseHashGenerator(object):
"""
All generators should extend this class overriding `.hash()` method.
"""
def hash(self):
raise NotImplementedError()
class ClientIdGenerator(BaseHashGenerator):
def hash(self):
"""
Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2
for Basic Authentication scheme
"""
client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "")
return oauthlib_generate_client_id(length=40, chars=client_id_charset)
class ClientSecretGenerator(BaseHashGenerator):
def hash(self):
return oauthlib_generate_client_id(length=128)
def generate_client_id():
"""
Generate a suitable client id
"""
client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS()
return client_id_generator.hash()
def generate_client_secret():
"""
Generate a suitable client secret
"""
client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS()
return client_secret_generator.hash()
|
XWIKI-2054: Add Utility API to remove all non alpha numeric chartacters from some text
Use unicode escapes to properly use accented characters in the test.
git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7277 f329d543-caf0-0310-9063-dda96c69346f | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.util;
import junit.framework.TestCase;
/**
* Unit tests for {@link com.xpn.xwiki.util.Util}.
*
* @version $Id: $
*/
public class UtilTest extends TestCase
{
public void testConvertToAlphaNumeric()
{
assertEquals("Search", Util.convertToAlphaNumeric("Search"));
assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
assertEquals("e", Util.convertToAlphaNumeric("e$%#^()"));
assertEquals("e", Util.convertToAlphaNumeric(":\u0205!"));
}
}
| /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.util;
import junit.framework.TestCase;
/**
* Unit tests for {@link com.xpn.xwiki.util.Util}.
*
* @version $Id: $
*/
public class UtilTest extends TestCase
{
public void testConvertToAlphaNumeric()
{
assertEquals("Search", Util.convertToAlphaNumeric("Search"));
assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
assertEquals("e", Util.convertToAlphaNumeric("e$%#^()"));
}
}
|
Add missing config for cache folder permissions | <?php namespace OpenCFP\Provider;
use HTMLPurifier;
use HTMLPurifier_Config;
use Silex\Application;
use Silex\ServiceProviderInterface;
class HtmlPurifierServiceProvider implements ServiceProviderInterface
{
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
$app['purifier'] = $app->share(function ($app) {
$config = HTMLPurifier_Config::createDefault();
if ($app->config('cache.enabled')) {
$cachePermissions = 0755;
$config->set('Cache.SerializerPermissions', $cachePermissions);
$cacheDirectory = $app->config('paths.cache.purifier');
if (!is_dir($cacheDirectory)) {
mkdir($cacheDirectory, $cachePermissions, true);
}
$config->set('Cache.SerializerPath', $cacheDirectory);
}
return new HTMLPurifier($config);
});
}
/**
* {@inheritdoc}
*/
public function boot(Application $app)
{
}
}
| <?php namespace OpenCFP\Provider;
use HTMLPurifier;
use HTMLPurifier_Config;
use Silex\Application;
use Silex\ServiceProviderInterface;
class HtmlPurifierServiceProvider implements ServiceProviderInterface
{
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
$app['purifier'] = $app->share(function ($app) {
$config = HTMLPurifier_Config::createDefault();
if ($app->config('cache.enabled')) {
$cacheDirectory = $app->config('paths.cache.purifier');
if (!is_dir($cacheDirectory)) {
mkdir($cacheDirectory, 0755, true);
}
$config->set('Cache.SerializerPath', $cacheDirectory);
}
return new HTMLPurifier($config);
});
}
/**
* {@inheritdoc}
*/
public function boot(Application $app)
{
}
}
|
Use README.md for the long description. | #!/usr/bin/env python
# -*- coding: utf8 -*-
import os.path
from setuptools import setup, find_packages
def get_version():
"""
Loads the current module version from version.py and returns
it.
:returns: module version identifier.
:rtype: str
"""
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with open(version_file_path, 'rb') as fin:
# Compiling instead of passing the text straight to exec
# associates any errors with the correct file name.
code = compile(fin.read(), version_file_path, 'exec')
exec(code, {}, local_results)
return local_results['__version__']
if __name__ == '__main__':
with open('README.md', 'rb') as readme:
long_description = readme.read()
setup(
name='pytextql',
version=get_version(),
long_description=long_description,
packages=find_packages(),
include_package_data=True,
install_requires=[
'docopt'
],
scripts=[
'pytextql/pytextql'
]
)
| #!/usr/bin/env python
# -*- coding: utf8 -*-
import os.path
from setuptools import setup, find_packages
def get_version():
"""
Loads the current module version from version.py and returns
it.
:returns: module version identifier.
:rtype: str
"""
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with open(version_file_path, 'rb') as fin:
# Compiling instead of passing the text straight to exec
# associates any errors with the correct file name.
code = compile(fin.read(), version_file_path, 'exec')
exec(code, {}, local_results)
return local_results['__version__']
if __name__ == '__main__':
setup(
name='pytextql',
version=get_version(),
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
install_requires=[
'docopt'
],
scripts=[
'pytextql/pytextql'
]
)
|
Improve notification performance with some more goroutines | package runner
import (
"log"
"github.com/sivel/overseer/monitor"
"github.com/sivel/overseer/notifier"
"github.com/sivel/overseer/status"
)
type Runner struct {
StatusChan chan *status.Status
Monitors []monitor.Monitor
Notifiers []notifier.Notifier
}
func NewRunner(monitors []monitor.Monitor, notifiers []notifier.Notifier) *Runner {
runner := &Runner{
StatusChan: make(chan *status.Status),
Monitors: monitors,
Notifiers: notifiers,
}
return runner
}
func (r *Runner) Loop() {
if len(r.Monitors) == 0 {
log.Fatalf("No monitors are configured. Exiting...")
}
for _, monitor := range r.Monitors {
go monitor.Watch(r.StatusChan)
}
for {
stat := <-r.StatusChan
go func(stat *status.Status) {
if notifier.ShouldNotify(stat) {
for _, n := range r.Notifiers {
go func(stat *status.Status, n notifier.Notifier) {
if notifier.NotifierMatch(stat, n) {
n.Notify(stat)
}
}(stat, n)
}
}
}(stat)
}
}
| package runner
import (
"log"
"github.com/sivel/overseer/monitor"
"github.com/sivel/overseer/notifier"
"github.com/sivel/overseer/status"
)
type Runner struct {
StatusChan chan *status.Status
Monitors []monitor.Monitor
Notifiers []notifier.Notifier
}
func NewRunner(monitors []monitor.Monitor, notifiers []notifier.Notifier) *Runner {
runner := &Runner{
StatusChan: make(chan *status.Status),
Monitors: monitors,
Notifiers: notifiers,
}
return runner
}
func (r *Runner) Loop() {
if len(r.Monitors) == 0 {
log.Fatalf("No monitors are configured. Exiting...")
}
for _, monitor := range r.Monitors {
go monitor.Watch(r.StatusChan)
}
for {
stat := <-r.StatusChan
if !notifier.ShouldNotify(stat) {
continue
}
for _, n := range r.Notifiers {
if notifier.NotifierMatch(stat, n) {
n.Notify(stat)
}
}
}
}
|
Move archive description into page header | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
final class Archive extends AbstractSetup
{
public function run()
{
\add_action('jentil_after_title', [$this, 'renderDescription']);
}
/**
* @action jentil_after_title
*/
public function renderDescription()
{
$page = $this->app->utilities->page;
if (!$page->is('archive')) {
return;
}
if (!($description = $page->description())) {
return;
}
echo '<div class="archive-description entry-summary" itemprop="description">'.
$description.
'</div>';
}
}
| <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
final class Archive extends AbstractSetup
{
public function run()
{
\add_action('jentil_before_content', [$this, 'renderDescription']);
}
/**
* @action jentil_before_content
*/
public function renderDescription()
{
$page = $this->app->utilities->page;
if (!$page->is('archive')) {
return;
}
if (!($description = $page->description())) {
return;
}
echo '<div class="archive-description entry-summary" itemprop="description">'.
$description.
'</div>';
}
}
|
Rename variable to make more sense given expected value | package server
import (
"errors"
"fmt"
"log"
"os"
"strconv"
)
var apiHost, jsBundleURL, herokuAppName, twitterAPIToken string
var webPort int
func initEnv() (err error) {
twitterAPIToken = os.Getenv("TWITTER_TOKEN")
webPort, err = strconv.Atoi(os.Getenv("PORT"))
if err != nil || webPort == 0 {
log.Println("PORT not set, using default")
webPort = 8080
err = nil
}
jsBundleURL = os.Getenv("JS_BUNDLE")
if jsBundleURL == "" {
return errors.New("Could not determing JS bundle URL")
}
herokuAppName = os.Getenv("HEROKU_APP_NAME")
apiHost = os.Getenv("API_HOST")
if apiHost == "" {
if herokuAppName == "" {
return errors.New("Could not determine API URL")
}
apiHost = fmt.Sprintf("https://%s.herokuapp.com", herokuAppName)
log.Println("API_HOST not set, using default: " + apiHost)
}
return
}
func getServeAddress() string {
return fmt.Sprintf(":%d", webPort)
}
| package server
import (
"errors"
"fmt"
"log"
"os"
"strconv"
)
var apiHost, jsBundleURL, dynoID, twitterAPIToken string
var webPort int
func initEnv() (err error) {
twitterAPIToken = os.Getenv("TWITTER_TOKEN")
webPort, err = strconv.Atoi(os.Getenv("PORT"))
if err != nil || webPort == 0 {
log.Println("PORT not set, using default")
webPort = 8080
err = nil
}
jsBundleURL = os.Getenv("JS_BUNDLE")
if jsBundleURL == "" {
return errors.New("Could not determing JS bundle URL")
}
dynoID = os.Getenv("HEROKU_DYNO_ID")
apiHost = os.Getenv("API_HOST")
if apiHost == "" {
if dynoID == "" {
return errors.New("Could not determine API URL")
}
apiHost = fmt.Sprintf("https://%s.herokuapp.com", dynoID)
log.Println("API_HOST not set, using default: " + apiHost)
}
return
}
func getServeAddress() string {
return fmt.Sprintf(":%d", webPort)
}
|
Remove inlcudes for no longer needed libraries. | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
# "libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/bootstrap/dist/js/bootstrap.js",
"js/plugins.js",
# "libs/annotator.1.2.9/annotator.min.js",
# "libs/rangy/external/log4javascript_stub.js",
# "libs/rangy/src/core/core.js",
# "libs/rangy/src/core/dom.js",
# "libs/rangy/src/core//domrange.js",
# "libs/rangy/src/core/wrappedrange.js",
# "libs/rangy/src/core/wrappedselection.js",
# "libs/rangy/src/modules/rangy-classapplier.js",
# "libs/rangy/src/modules/rangy-highlighter.js",
filters='jsmin',
output="public/js/common.js"
)
assets = Environment()
assets.register("js_all", js)
assets.register("css_all", css)
| # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
"libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/bootstrap/dist/js/bootstrap.js",
"js/plugins.js",
"libs/annotator.1.2.9/annotator.min.js",
"libs/rangy/external/log4javascript_stub.js",
"libs/rangy/src/core/core.js",
"libs/rangy/src/core/dom.js",
"libs/rangy/src/core//domrange.js",
"libs/rangy/src/core/wrappedrange.js",
"libs/rangy/src/core/wrappedselection.js",
"libs/rangy/src/modules/rangy-classapplier.js",
"libs/rangy/src/modules/rangy-highlighter.js",
filters='jsmin',
output="public/js/common.js"
)
assets = Environment()
assets.register("js_all", js)
assets.register("css_all", css)
|
Add a new line before @param
Co-authored-by: Zach Ghera <7d293d7aa3d73ce243886706f2742c0d78eb864e@gmail.com> | /**
* Format a timestamp (in milliseconds) into a pretty string with just the time.
*
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "10:19 AM".
*/
export function timestampToTimeFormatted(msTimestamp, timezone = "America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
hour: 'numeric',
minute: '2-digit',
timeZone: timezone
};
let formatted = date.toLocaleTimeString('en-US', formatOptions);
return formatted;
}
/**
* Format a timestamp (in milliseconds) into a pretty string with just the date.
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "Monday, January 19, 1970".
*/
export function timestampToDateFormatted(msTimestamp, timezone="America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: timezone
};
let formatted = date.toLocaleDateString('en-US', formatOptions);
return formatted;
}
| /**
* Format a timestamp (in milliseconds) into a pretty string with just the time.
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "10:19 AM".
*/
export function timestampToTimeFormatted(msTimestamp, timezone = "America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
hour: 'numeric',
minute: '2-digit',
timeZone: timezone
};
let formatted = date.toLocaleTimeString('en-US', formatOptions);
return formatted;
}
/**
* Format a timestamp (in milliseconds) into a pretty string with just the date.
* @param {int} msTimestamp
* @param {string} timezone
* @returns {string} Time formatted into a string like "Monday, January 19, 1970".
*/
export function timestampToDateFormatted(msTimestamp, timezone="America/New_York") {
let date = new Date(msTimestamp);
let formatOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: timezone
};
let formatted = date.toLocaleDateString('en-US', formatOptions);
return formatted;
} |
Add a test mode, handle 429 errors, stop corrupting state file | #!/usr/bin/env python
import sys,requests,json
REDDIT=sys.argv[1]
CHANNEL=sys.argv[2]
FEED=sys.argv[3]
# Test mode:
if len(sys.argv) == 5:
print "running in test mode"
data = json.loads(open(sys.argv[4]).read())
writer=sys.stdout
else:
req = requests.get("http://www.reddit.com/r/%s/%s.json" %(REDDIT,FEED))
if req.status_code != 200:
print "Kabloom!"
print req.text
sys.exit(1)
data = req.json()
writer=open("/home/ircbot/irc/irc.mozilla.org/%s/in"%CHANNEL, "a")
STATEFILE="/home/ircbot/state/reddit-%s-%s-storyids"%(CHANNEL,REDDIT)
sf = open(STATEFILE)
seen = set(sf.read().split("\n"))
sf.close()
new=[]
for post in data["data"]["children"]:
post = post['data']
if not post["id"] in seen:
writer.write(post["title"]+"\n")
if post["domain"] == "self.%s" % REDDIT:
writer.write(post["url"]+"\n")
else:
writer.write(post["url"]+" "+post["permalink"]+"\n")
new.append(post["id"])
if len(new) != 0:
f = open(STATEFILE, "a")
for new in new:
f.write(new+"\n")
f.close()
| #!/usr/bin/env python
import sys,requests
REDDIT=sys.argv[1]
CHANNEL=sys.argv[2]
FEED=sys.argv[3]
STATEFILE="/home/ircbot/state/reddit-%s-%s-storyids"%(CHANNEL,REDDIT)
seen = set(open(STATEFILE).read().split("\n"))
data = requests.get("http://www.reddit.com/r/%s/%s.json" %(REDDIT,FEED)).json()
new=[]
writer=open("/home/ircbot/irc/irc.mozilla.org/%s/in"%CHANNEL, "a")
for post in data["data"]["children"]:
post = post['data']
if not post["id"] in seen:
writer.write(post["title"]+"\n")
if post["domain"] == "self.%s" % REDDIT:
writer.write(post["url"]+"\n")
else:
writer.write(post["url"]+" "+post["permalink"]+"\n")
new.append(post["id"])
if len(new) != 0:
f = open(STATEFILE, "a")
f.write("\n".join(new))
|
Read bank list from config file. | #!/usr/bin/python
import os
import sys
import api
import json
import getpass
sys.path.append("../")
import config
# Banks
banks = {}
for bank in config.banks:
exec "import %s" % (bank)
banks[bank] = eval(bank)
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "password": password}):
print "Login failed"
sys.exit(1)
todo = api.callapi("accountstodo")
for account in todo:
if account["bankname"] not in banks:
print "No scraper for %s!" % (account["bankname"])
continue
print "Scraping %s..." % (account["bankname"])
if os.getenv("DATAFILE"):
data = open(os.getenv("DATAFILE")).read()
else:
data = json.dumps(banks[account["bankname"]].downloadaccount(account),default=str)
api.callapi("newtransactions", {"data": data})
api.callapi("logout")
| #!/usr/bin/python
import os
import sys
import api
import json
import getpass
# Banks
banks = {}
import bankofamerica
banks["bankofamerica"] = bankofamerica
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "password": password}):
print "Login failed"
sys.exit(1)
todo = api.callapi("accountstodo")
for account in todo:
if account["bankname"] not in banks:
print "No scraper for %s!" % (account["bankname"])
continue
print "Scraping %s..." % (account["bankname"])
if os.getenv("DATAFILE"):
data = open(os.getenv("DATAFILE")).read()
else:
data = json.dumps(banks[account["bankname"]].downloadaccount(account),default=str)
api.callapi("newtransactions", {"data": data})
api.callapi("logout")
|
Use a networkFirst strategy for Picasa | /**
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(global) {
// Use a cache for the Picasa API response for the Google I/O 2014 album.
global.shed.router.get('/data/feed/api/user/(.*)',
global.shed.networkFirst, {origin: /https?:\/\/picasaweb.google.com/});
// Use a cache for the actual image files as well.
global.shed.router.get('/(.+)', global.shed.networkFirst,
{origin: /https?:\/\/lh\d*.googleusercontent.com/});
})(self);
| /**
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(global) {
// Use a cache for the Picasa API response for the Google I/O 2014 album.
global.shed.router.get('/data/feed/api/user/111395306401981598462/albumid/6029456067262589905(.*)',
global.shed.cacheFirst, {origin: /https?:\/\/picasaweb.google.com/});
// Use a cache for the actual image files as well.
global.shed.router.get('/(.+)', global.shed.cacheFirst, {origin: /https?:\/\/lh\d*.googleusercontent.com/});
})(self);
|
Correct input type for email
Correct input type for email | <div id="controls">
<form id="newuser" autocomplete="off">
<input id="newusername" type="text"
placeholder="<?php p($l->t('Username'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<input
type="password" id="newuserpassword"
placeholder="<?php p($l->t('Password'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<input id="newemail" type="email" style="display:none"
placeholder="<?php p($l->t('E-Mail'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<div class="groups"><div class="groupsListContainer multiselect button" data-placeholder="<?php p($l->t('Groups'))?>"><span class="title groupsList"></span><span class="icon-triangle-s"></span></div></div>
<input type="submit" class="button" value="<?php p($l->t('Create'))?>" />
</form>
<?php if((bool)$_['recoveryAdminEnabled']): ?>
<div class="recoveryPassword">
<input id="recoveryPassword"
type="password"
placeholder="<?php p($l->t('Admin Recovery Password'))?>"
title="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"
alt="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"/>
</div>
<?php endif; ?>
</div>
| <div id="controls">
<form id="newuser" autocomplete="off">
<input id="newusername" type="text"
placeholder="<?php p($l->t('Username'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<input
type="password" id="newuserpassword"
placeholder="<?php p($l->t('Password'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<input id="newemail" type="text" style="display:none"
placeholder="<?php p($l->t('E-Mail'))?>"
autocomplete="off" autocapitalize="none" autocorrect="off" />
<div class="groups"><div class="groupsListContainer multiselect button" data-placeholder="<?php p($l->t('Groups'))?>"><span class="title groupsList"></span><span class="icon-triangle-s"></span></div></div>
<input type="submit" class="button" value="<?php p($l->t('Create'))?>" />
</form>
<?php if((bool)$_['recoveryAdminEnabled']): ?>
<div class="recoveryPassword">
<input id="recoveryPassword"
type="password"
placeholder="<?php p($l->t('Admin Recovery Password'))?>"
title="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"
alt="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"/>
</div>
<?php endif; ?>
</div>
|
Add service identity package to quiet warnings | from setuptools import setup, find_packages
setup(
name="ducted",
version='1.2',
url='http://github.com/ducted/duct',
license='MIT',
description="A monitoring agent and event processor",
author='Colin Alston',
author_email='colin.alston@gmail.com',
packages=find_packages() + [
"twisted.plugins",
],
package_data={
'twisted.plugins': ['twisted/plugins/duct_plugin.py']
},
include_package_data=True,
install_requires=[
'zope.interface',
'Twisted',
'PyYaml',
'pyOpenSSL',
'protobuf',
'construct<2.6',
'pysnmp==4.2.5',
'cryptography',
'service_identity'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: System :: Monitoring',
],
)
| from setuptools import setup, find_packages
setup(
name="ducted",
version='1.2',
url='http://github.com/ducted/duct',
license='MIT',
description="A monitoring agent and event processor",
author='Colin Alston',
author_email='colin.alston@gmail.com',
packages=find_packages() + [
"twisted.plugins",
],
package_data={
'twisted.plugins': ['twisted/plugins/duct_plugin.py']
},
include_package_data=True,
install_requires=[
'zope.interface',
'Twisted',
'PyYaml',
'pyOpenSSL',
'protobuf',
'construct<2.6',
'pysnmp==4.2.5',
'cryptography',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: System :: Monitoring',
],
)
|
Kill animals if more than 5 collide at the same time | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.mobdensity;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.entity.CollideEntityEvent;
import java.util.List;
import java.util.stream.Collectors;
public class MobDensityListener {
@Listener
public void onEntityCollide(CollideEntityEvent event) {
List<Entity> entities = event.getEntities().stream().filter(e -> e instanceof Animal).collect(Collectors.toList());
if (entities.size() > 5) {
entities.forEach(e -> {
e.offer(Keys.FIRE_TICKS, 20 * 20);
});
}
}
}
| /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.mobdensity;
import com.skelril.nitro.probability.Probability;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.entity.CollideEntityEvent;
public class MobDensityListener {
@Listener
public void onEntityCollide(CollideEntityEvent event) {
event.getEntities().forEach(e -> {
if (e instanceof Animal && Probability.getChance(20) && event.getCause().containsType(e.getClass())) {
e.offer(Keys.FIRE_TICKS, 20 * 20);
}
});
}
}
|
Tidy up info a little for the PluginModule popup edit form
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40393 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER['SCRIPT_NAME'], basename(__FILE__)) !== false) {
header('location: index.php');
exit;
}
function module_users_own_rank_info()
{
return array(
'name' => tra('My Score'),
'description' => tra('Display the logged user\'s rank and score.'),
'prefs' => array( 'feature_score' ),
'params' => array()
);
}
function module_users_own_rank( $mod_reference, $module_params )
{
global $scorelib, $smarty, $user;
include_once('lib/score/scorelib.php');
$position = $scorelib->user_position($user);
$smarty->assign('position', $position);
$score = $scorelib->get_user_score($user);
$smarty->assign('score', $score);
$count = $scorelib->count_users(0);
$smarty->assign('count', $count);
$smarty->assign('user', $user);
}
| <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER['SCRIPT_NAME'], basename(__FILE__)) !== false) {
header('location: index.php');
exit;
}
function module_users_own_rank_info()
{
return array(
'name' => tra('My score'),
'description' => tra('Displays the logged user\'s rank and score.'),
'prefs' => array( 'feature_score' ),
'params' => array()
);
}
function module_users_own_rank( $mod_reference, $module_params )
{
global $scorelib, $smarty, $user;
include_once('lib/score/scorelib.php');
$position = $scorelib->user_position($user);
$smarty->assign('position', $position);
$score = $scorelib->get_user_score($user);
$smarty->assign('score', $score);
$count = $scorelib->count_users(0);
$smarty->assign('count', $count);
$smarty->assign('user', $user);
}
|
Upgrade Angular Validation Match to 1.7.1 | /*!
* angular-validation-match
* Checks if one input matches another
* @version v1.7.1
* @link https://github.com/TheSharpieOne/angular-validation-match
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(e,a,t){"use strict";function i(e){return{require:"?ngModel",restrict:"A",link:function(t,i,n,r){function c(){var e=o(t);return a.isObject(e)&&e.hasOwnProperty("$viewValue")&&(e=e.$viewValue),e}if(r){var o=e(n.match),u=e(n.matchCaseless),l=e(n.notMatch),s=e(n.matchIgnoreEmpty);t.$watch(c,function(){r.$$parseAndValidate()}),r.$validators.match=function(){var e,i=c(),n=l(t);return s(t)&&!r.$viewValue?!0:(e=u(t)?a.lowercase(r.$viewValue)===a.lowercase(i):r.$viewValue===i,e^=n,!!e)}}}}}i.$inject=["$parse"],a.module("validation.match",[]),a.module("validation.match").directive("match",i)}(window,window.angular); | /*!
* angular-validation-match
* Checks if one input matches another
* @version v1.7.0
* @link https://github.com/TheSharpieOne/angular-validation-match
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(e,a,t){"use strict";function i(e){return{require:"?ngModel",restrict:"A",link:function(t,i,n,r){function c(){var e=o(t);return a.isObject(e)&&e.hasOwnProperty("$viewValue")&&(e=e.$viewValue),e}if(r){var o=e(n.match),u=e(n.matchCaseless),l=e(n.notMatch);t.$watch(c,function(){r.$$parseAndValidate()}),r.$validators.match=function(){var e,i=c(),n=l(t);return e=u(t)?a.lowercase(r.$viewValue)===a.lowercase(i):r.$viewValue===i,e^=n,!!e}}}}}a.module("validation.match",[]),a.module("validation.match").directive("match",i),i.$inject=["$parse"]}(window,window.angular); |
Set the correct in-code policy for ec2 operations
In I8bd0fa342cdfee00acd3c7a33f7232fe0a87e23f we moved some of the policy
defaults into code. Some of the policy were accidentally changed.
Change-Id: Ib744317025d928c7397ab00dc706172592a9abaf
Closes-Bug: #1675377 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
ec2_credential_policies = [
policy.RuleDefault(
name=base.IDENTITY % 'ec2_get_credential',
check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_list_credentials',
check_str=base.RULE_ADMIN_OR_OWNER),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_create_credential',
check_str=base.RULE_ADMIN_OR_OWNER),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_delete_credential',
check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER),
]
def list_rules():
return ec2_credential_policies
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
ec2_credential_policies = [
policy.RuleDefault(
name=base.IDENTITY % 'ec2_get_credential',
check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_list_credentials',
check_str=base.RULE_ADMIN_REQUIRED),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_create_credential',
check_str=base.RULE_ADMIN_REQUIRED),
policy.RuleDefault(
name=base.IDENTITY % 'ec2_delete_credential',
check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER),
]
def list_rules():
return ec2_credential_policies
|
Fix typo in the image size fixer script | <?php
/**
* Fix missing image width/height
*/
if(php_sapi_name() !== 'cli') {
die('CLI only');
}
date_default_timezone_set('Europe/London');
require dirname(__FILE__) . '/../bootstrap.php';
$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Image', 'image');
$manager->filter("width = 0", array(), array(array("height = 0", array())));
$values = $manager->values();
if(!$values) {
echo "Nothing to do.\n";
return;
}
foreach($values as $record) {
echo "Doing ".$record->getUri()."... ";
if(!file_exists('../'.$record->getUri())) {
echo "NOT FOUND\n";
continue;
}
$sizeInfo = getimagesize('../'.$record->getUri());
$record->setWidth($sizeInfo['width']);
$record->setHeight($sizeInfo['height']);
$record->save();
echo "DONE\n";
}
echo "All done.\n";
| <?php
/**
* Fix missing image width/height
*/
if(php_sapi_name() !== 'cli') {
die('CLI only');
}
date_default_timezone_set('Europe/London');
require dirname(__FILE__) . '/../bootstrap.php';
$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Image', 'image');
$manager->filter("width = 0", array(), array(array("height = 0", array())));
$values = $manager->values();
if(!$values) {
echo "Nothing to do.\n";
return;
}
foreach($values as $record) {
echo "Doing ".$record->getUri()."... ";
if(!file_exists('../'.$record->getUri())) {
echo "NOT FOUND\n";
continue;
}
$sizeInfo = get_image_size('../'.$record->getUri());
$record->setWidth($sizeInfo['width']);
$record->setHeight($sizeInfo['height']);
$record->save();
echo "DONE\n";
}
echo "All done.\n";
|
Update position test to use test.V | package parse
import (
"bytes"
"io"
"testing"
"github.com/tdewolff/test"
)
func TestPosition(t *testing.T) {
var newlineTests = []struct {
pos int
s string
line int
col int
err error
}{
{0, "x", 1, 1, nil},
{1, "xx", 1, 2, nil},
{2, "x\nx", 2, 1, nil},
{2, "\n\nx", 3, 1, nil},
{3, "\nxxx", 2, 3, nil},
{2, "\r\nx", 2, 1, nil},
// edge cases
{0, "", 1, 1, io.EOF},
{0, "\n", 1, 1, nil},
{1, "\r\n", 1, 2, nil},
{-1, "x", 1, 2, io.EOF},
}
for _, nt := range newlineTests {
t.Run(nt.s, func(t *testing.T) {
r := bytes.NewBufferString(nt.s)
line, col, err := Pos(r, nt.pos)
test.Error(t, err, nt.err)
test.V(t, "line", line, nt.line)
test.V(t, "column", col, nt.col)
})
}
}
| package parse
import (
"bytes"
"io"
"testing"
"github.com/tdewolff/test"
)
func TestPosition(t *testing.T) {
var newlineTests = []struct {
pos int
s string
line int
col int
err error
}{
{0, "x", 1, 1, nil},
{1, "xx", 1, 2, nil},
{2, "x\nx", 2, 1, nil},
{2, "\n\nx", 3, 1, nil},
{3, "\nxxx", 2, 3, nil},
{2, "\r\nx", 2, 1, nil},
// edge cases
{0, "", 1, 1, io.EOF},
{0, "\n", 1, 1, nil},
{1, "\r\n", 1, 2, nil},
{-1, "x", 1, 2, io.EOF},
}
for _, nt := range newlineTests {
t.Run(nt.s, func(t *testing.T) {
r := bytes.NewBufferString(nt.s)
line, col, err := Pos(r, nt.pos)
test.Error(t, err, nt.err)
test.Int(t, line, nt.line, "line")
test.Int(t, col, nt.col, "col")
})
}
}
|
Return None explicitly instead of implicitly | """
Contains generic helper funcitons to aid in parsing.
"""
import itertools
def take_while(predicate, items):
return list(itertools.takewhile(predicate, items))
def drop_while(predicate, items):
return list(itertools.dropwhile(predicate, items))
def not_(func):
return lambda *args, **kwargs: not func(*args, **kwargs)
def first(predicate, iterable):
for item in iterable:
if predicate(item):
return item
return None
def rfirst(predicate, iterable):
return first(predicate, reversed(list(iterable)))
def catch(func, *args, **kwargs):
"""
Executes `func` with `args` and `kwargs` as arguments. If `func` throws an error, this function
returns the error, otherwise it returns `None`.
"""
try:
func(*args, **kwargs)
except Exception as error:
return error
return None
| """
Contains generic helper funcitons to aid in parsing.
"""
import itertools
def take_while(predicate, items):
return list(itertools.takewhile(predicate, items))
def drop_while(predicate, items):
return list(itertools.dropwhile(predicate, items))
def not_(func):
return lambda *args, **kwargs: not func(*args, **kwargs)
def first(predicate, iterable):
for item in iterable:
if predicate(item):
return item
return None
def rfirst(predicate, iterable):
return first(predicate, reversed(list(iterable)))
def catch(func, *args, **kwargs):
"""
Executes `func` with `args` and `kwargs` as arguments. If `func` throws an error, this function
returns the error, otherwise it returns `None`.
"""
try:
func(*args, **kwargs)
except Exception as error:
return error
|
Remove default output of all env vars | const _ = {
pick: require('lodash.pick'),
};
const express = require('express');
const fs = require('fs');
const path = require('path');
module.exports = () => {
const router = new express.Router();
const version = require('@maxdome/version')();
router.get('/version', (req, res) => {
res.send(version);
});
let env = {};
try {
const keys = fs
.readFileSync(path.join(process.cwd(), '.env.example'), 'utf-8')
.split('\n')
.map(line => {
const matches = line.match(/([A-Z_]*)=.*? #info/);
if (matches) {
return matches[1];
}
})
.filter(key => key);
env = _.pick(process.env, keys);
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
router.get('/env', (req, res) => {
res.send(env);
});
return router;
};
| const _ = {
pick: require('lodash.pick'),
};
const express = require('express');
const fs = require('fs');
const path = require('path');
module.exports = () => {
const router = new express.Router();
const version = require('@maxdome/version')();
router.get('/version', (req, res) => {
res.send(version);
});
let env = process.env;
try {
const keys = fs
.readFileSync(path.join(process.cwd(), '.env.example'), 'utf-8')
.split('\n')
.map(line => {
const matches = line.match(/([A-Z_]*)=.*? #info/);
if (matches) {
return matches[1];
}
})
.filter(key => key);
env = _.pick(env, keys);
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
router.get('/env', (req, res) => {
res.send(env);
});
return router;
};
|
fix(widget-message-meet): Fix proptype error with info list separator | import React, {PropTypes} from 'react';
import classNames from 'classnames';
import styles from './styles.css';
function ListSeparator(props) {
const mainStyles = [`separator`, styles.separator];
const textStyles = [`separator-text`, styles.separatorText];
const informativeClass = `informative`;
if (props.isInformative) {
mainStyles.push(informativeClass);
mainStyles.push(styles[informativeClass]);
textStyles.push(informativeClass);
textStyles.push(styles[informativeClass]);
}
return (
<div className={classNames(mainStyles)}>
<p className={classNames(textStyles)}>{props.primaryText}</p>
</div>
);
}
ListSeparator.propTypes = {
isInformative: PropTypes.bool,
primaryText: PropTypes.object
};
export default ListSeparator;
| import React, {PropTypes} from 'react';
import classNames from 'classnames';
import styles from './styles.css';
function ListSeparator(props) {
const mainStyles = [`separator`, styles.separator];
const textStyles = [`separator-text`, styles.separatorText];
const informativeClass = `informative`;
if (props.isInformative) {
mainStyles.push(informativeClass);
mainStyles.push(styles[informativeClass]);
textStyles.push(informativeClass);
textStyles.push(styles[informativeClass]);
}
return (
<div className={classNames(mainStyles)}>
<p className={classNames(textStyles)}>{props.primaryText}</p>
</div>
);
}
ListSeparator.propTypes = {
isInformative: PropTypes.boolean,
primaryText: PropTypes.object
};
export default ListSeparator;
|
Fix ConcurrentModificationException in tile chunk load hook | package codechicken.lib.world;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.ArrayList;
import java.util.List;
public class TileChunkLoadHook
{
private static boolean init;
public static void init() {
if(init) return;
init = true;
MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
}
@SubscribeEvent
public void onChunkLoad(ChunkEvent.Load event) {
List<TileEntity> list = new ArrayList<TileEntity>(event.getChunk().chunkTileEntityMap.values());
for(TileEntity t : list)
if(t instanceof IChunkLoadTile)
((IChunkLoadTile)t).onChunkLoad();
}
}
| package codechicken.lib.world;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.ArrayList;
import java.util.List;
public class TileChunkLoadHook
{
private static boolean init;
public static void init() {
if(init) return;
init = true;
MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
}
@SubscribeEvent
public void onChunkLoad(ChunkEvent.Load event) {
List<TileEntity> list = new ArrayList<TileEntity>(event.getChunk().chunkTileEntityMap.values());
for(TileEntity t : list)
if(t instanceof IChunkLoadTile)
((IChunkLoadTile)t).onChunkLoad();
}
}
|
Use PORT env for dev server | const path = require('path');
const port = process.env.PORT || 9000;
module.exports = {
devtool: 'inline-source-map',
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
exclude: /node_modules/,
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
output: {
library: 'Muxy',
libraryTarget: 'umd',
umdNamedDefine: true,
path: path.resolve(__dirname, 'dist'),
filename: 'muxy-extensions-sdk.js'
},
devServer: { port }
};
| const path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
exclude: /node_modules/,
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
output: {
library: 'Muxy',
libraryTarget: 'umd',
umdNamedDefine: true,
path: path.resolve(__dirname, 'dist'),
filename: 'muxy-extensions-sdk.js'
}
};
|
Add numeric name test case | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('helloWorld'))
def is_upper_camel_case_test_blank_name(self):
self.assertFalse(charformat.is_upper_camel_case(''))
def is_upper_camel_case_test_snake_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('Hello_World'))
def is_upper_camel_case_test_numeric_name(self):
self.assertFalse(charformat.is_upper_camel_case('1ello_world'))
if __name__ == '__main__':
unittest.main()
| import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('helloWorld'))
def is_upper_camel_case_test_blank_name(self):
self.assertFalse(charformat.is_upper_camel_case(''))
def is_upper_camel_case_test_snake_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('Hello_World'))
if __name__ == '__main__':
unittest.main()
|
Fix child not found error | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Task } = require('devtools/sham/task');
const { PROMISE } = require('devtools/client/shared/redux/middleware/promise');
const { connectToTab} = require('../client');
const constants = require('../constants');
const { getTabs } = require('../queries');
function newTabs(tabs) {
return {
type: constants.ADD_TABS,
value: tabs
};
}
function selectTab({ tabActor }) {
return (dispatch, getState) => {
const tabs = getTabs(getState());
const selectedTab = tabs[tabActor];
// set selected tab in the URL hash
let childId;
if (tabActor.includes("child")) {
childId = tabActor.match(/child\d+/)[0];
} else {
childId = tabActor.match(/tab\d+/)[0];
}
window.location.hash = `tab=${childId}`
return dispatch({
type: constants.SELECT_TAB,
tabActor: tabActor,
[PROMISE]: Task.spawn(function*() {
yield connectToTab(selectedTab);
return { selectedTab };
})
});
}
}
module.exports = {
newTabs,
selectTab
};
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Task } = require('devtools/sham/task');
const { PROMISE } = require('devtools/client/shared/redux/middleware/promise');
const { connectToTab} = require('../client');
const constants = require('../constants');
const { getTabs } = require('../queries');
function newTabs(tabs) {
return {
type: constants.ADD_TABS,
value: tabs
};
}
function selectTab({ tabActor }) {
return (dispatch, getState) => {
const tabs = getTabs(getState());
const selectedTab = tabs[tabActor];
// set selected tab in the URL hash
const childId = tabActor.match(/child\d+/)[0];
window.location.hash = `tab=${childId}`
return dispatch({
type: constants.SELECT_TAB,
tabActor: tabActor,
[PROMISE]: Task.spawn(function*() {
yield connectToTab(selectedTab);
return { selectedTab };
})
});
}
}
module.exports = {
newTabs,
selectTab
};
|
Refactor and fix string concat typo | <?php
/*
* Plugin Name: LuckyGrids
* Version: 0.1.0
* Plugin URI: http://luckygrids.io/wordpress
* Description: Embed LuckyGrids using a shortcode.
* Author: Ryan Burnette
* Author URI: http://ryanburnette.com
* Requires at least: 2.5
* Tested up to: 4.0.1
*/
function luckygrids_embed_code($id) {
return '<script src="//luckygrids.io/grids/'.$id.'.js" async="true"></script><div id="luckygrid'.$id.'"></div>';
}
function luckygrids_shortcode_atts($atts) {
$supported = array(
'id' => '0'
);
return shortcode_atts($supported, $atts);
}
function luckygrids_shortcode($atts) {
$atts = luckygrids_shortcode_atts($atts);
return luckygrids_embed_code($atts['id']);
}
add_shortcode('luckygrid', 'luckygrids_shortcode');
add_shortcode('luckygrids', 'luckygrids_shortcode');
| <?php
/*
* Plugin Name: LuckyGrids
* Version: 0.1.0
* Plugin URI: http://luckygrids.io/wordpress
* Description: Embed LuckyGrids using a shortcode.
* Author: Ryan Burnette
* Author URI: http://ryanburnette.com
* Requires at least: 2.5
* Tested up to: 4.1
*/
function luckygrids_embed_code($id) {
return '<script src="//luckygrids.io/grids/'+$id+'.js" async="true"></script><div id="luckygrid'+$id+'"></div>';
}
function luckygrids_shortcode($atts) {
$defaults = array();
$a = shortcode_atts($defaults, $atts);
$id = $a['id'];
return luckygrids_embed_code($id);
}
add_shortcode('luckygrid', 'luckygrids_shortcode');
add_shortcode('luckygrids', 'luckygrids_shortcode');
|
Allow users to define project assets | const path = require('path');
const android = require('./android');
const ios = require('./ios');
const findAssets = require('./findAssets');
const getRNPMConfig = (folder) =>
require(path.join(folder, './package.json')).rnpm || {};
/**
* Returns project config from the current working directory
* @return {Object}
*/
exports.getProjectConfig = function getProjectConfig() {
const folder = process.cwd();
const rnpm = getRNPMConfig(folder);
return Object.assign({}, rnpm, {
ios: ios.projectConfig(folder, rnpm.ios || {}),
android: android.projectConfig(folder, rnpm.android || {}),
assets: findAssets(folder, rnpm.assets),
});
};
/**
* Returns a dependency config from node_modules/<package_name>
* @param {String} packageName Dependency name
* @return {Object}
*/
exports.getDependencyConfig = function getDependencyConfig(packageName) {
const folder = path.join(process.cwd(), 'node_modules', packageName);
const rnpm = getRNPMConfig(folder);
return Object.assign({}, rnpm, {
ios: ios.dependencyConfig(folder, rnpm.ios || {}),
android: android.dependencyConfig(folder, rnpm.android || {}),
assets: findAssets(folder, rnpm.assets),
});
};
| const path = require('path');
const android = require('./android');
const ios = require('./ios');
const findAssets = require('./findAssets');
const getRNPMConfig = (folder) =>
require(path.join(folder, './package.json')).rnpm || {};
/**
* Returns project config from the current working directory
* @return {Object}
*/
exports.getProjectConfig = function getProjectConfig() {
const folder = process.cwd();
const rnpm = getRNPMConfig(folder);
return Object.assign({}, rnpm, {
ios: ios.projectConfig(folder, rnpm.ios || {}),
android: android.projectConfig(folder, rnpm.android || {}),
});
};
/**
* Returns a dependency config from node_modules/<package_name>
* @param {String} packageName Dependency name
* @return {Object}
*/
exports.getDependencyConfig = function getDependencyConfig(packageName) {
const folder = path.join(process.cwd(), 'node_modules', packageName);
const rnpm = getRNPMConfig(folder);
return Object.assign({}, rnpm, {
ios: ios.dependencyConfig(folder, rnpm.ios || {}),
android: android.dependencyConfig(folder, rnpm.android || {}),
assets: findAssets(folder, rnpm.assets),
});
};
|
Add some exception handling for dict | #!/usr/bin/env python
from nodes import Node
import json
class Dictionary(Node):
char = ".d"
args = 0
results = 1
def __init__(self, word_ids:Node.IntList):
if not hasattr(Dictionary, "word_list"):
Dictionary.word_list = init_words()
self.words = " ".join(Dictionary.word_list[i] for i in word_ids)
def func(self):
return self.words
def compress(inp):
words = init_words()
inp_words = [word.lower()for word in inp.split(" ")]
rtn = chr(len(inp_words))
for word in inp_words:
if word not in words:
rtn += "Word %s not in wordlist" % word
else:
rtn += chr(words.index(word))
return rtn
def init_words(dict_file = "dictionary.json"):
words_f = open(dict_file)
words = json.load(words_f)
words_f.close()
return words
| #!/usr/bin/env python
from nodes import Node
import json
class Dictionary(Node):
char = ".d"
args = 0
results = 1
def __init__(self, word_ids:Node.IntList):
if not hasattr(Dictionary, "word_list"):
Dictionary.word_list = init_words()
self.words = " ".join(Dictionary.word_list[i] for i in word_ids)
def func(self):
return self.words
def compress(inp):
words = init_words()
inp_words = [word.lower()for word in inp.split(" ")]
rtn = chr(len(inp_words))
for word in inp_words:
assert(word in words)
rtn += chr(words.index(word))
return rtn
def init_words(dict_file = "dictionary.json"):
words_f = open(dict_file)
words = json.load(words_f)
words_f.close()
return words
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.