text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add support for pulling hash tags
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'hashtags' : [hashtag['text'] for hashtag in data['entities']['hashtags'] ], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
Update Firefox profile: Disable WebRTC, DNS prefetch and IPv6, safebrowsing; Enable socks remote DNS
user_pref("network.proxy.backup.ftp", ""); user_pref("network.proxy.backup.ftp_port", 0); user_pref("network.proxy.backup.socks", ""); user_pref("network.proxy.backup.socks_port", 0); user_pref("network.proxy.backup.ssl", ""); user_pref("network.proxy.backup.ssl_port", 0); user_pref("network.proxy.ftp", "127.0.0.1"); user_pref("network.proxy.ftp_port", 3090); user_pref("network.proxy.http", "127.0.0.1"); user_pref("network.proxy.http_port", 3090); user_pref("network.proxy.share_proxy_settings", true); user_pref("network.proxy.socks", "127.0.0.1"); user_pref("network.proxy.socks_port", 3090); user_pref("network.proxy.socks_remote_dns", true); user_pref("network.proxy.ssl", "127.0.0.1"); user_pref("network.proxy.ssl_port", 3090); user_pref("network.proxy.type", 1); user_pref("media.peerconnection.enabled", false); user_pref("browser.safebrowsing.malware.enabled", false); user_pref("browser.safebrowsing.enabled", false); user_pref("network.dns.disablePrefetch", true); user_pref("network.dns.disableIPv6", true);
user_pref("network.proxy.backup.ftp", ""); user_pref("network.proxy.backup.ftp_port", 0); user_pref("network.proxy.backup.socks", ""); user_pref("network.proxy.backup.socks_port", 0); user_pref("network.proxy.backup.ssl", ""); user_pref("network.proxy.backup.ssl_port", 0); user_pref("network.proxy.ftp", "127.0.0.1"); user_pref("network.proxy.ftp_port", 3090); user_pref("network.proxy.http", "127.0.0.1"); user_pref("network.proxy.http_port", 3090); user_pref("network.proxy.share_proxy_settings", true); user_pref("network.proxy.socks", "127.0.0.1"); user_pref("network.proxy.socks_port", 3090); user_pref("network.proxy.ssl", "127.0.0.1"); user_pref("network.proxy.ssl_port", 3090); user_pref("network.proxy.type", 1);
Test of regex is the issue
'use strict' const express = require('express') const Slapp = require('slapp') const ConvoStore = require('slapp-convo-beepboop') const Context = require('slapp-context-beepboop') // use `PORT` env var on Beep Boop - default to 3000 locally var port = process.env.PORT || 3000 var slapp = Slapp({ // Beep Boop sets the SLACK_VERIFY_TOKEN env var verify_token: process.env.SLACK_VERIFY_TOKEN, convo_store: ConvoStore(), context: Context() }) //********************************************* // Setup different handlers for messages //********************************************* slapp.message('3020791579', (msg) => { msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', '')) }) // response to the user typing "help" slapp.message('^([0-9-]{9,12})$', (msg) => { msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', '')) }) // attach Slapp to express server var server = slapp.attachToExpress(express()) // start http server server.listen(port, (err) => { if (err) { return console.error(err) } console.log(`Listening on port ${port}`) })
'use strict' const express = require('express') const Slapp = require('slapp') const ConvoStore = require('slapp-convo-beepboop') const Context = require('slapp-context-beepboop') // use `PORT` env var on Beep Boop - default to 3000 locally var port = process.env.PORT || 3000 var slapp = Slapp({ // Beep Boop sets the SLACK_VERIFY_TOKEN env var verify_token: process.env.SLACK_VERIFY_TOKEN, convo_store: ConvoStore(), context: Context() }) //********************************************* // Setup different handlers for messages //********************************************* // response to the user typing "help" slapp.message('^([0-9-]{9,12})$', (msg) => { msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', '')) }) // attach Slapp to express server var server = slapp.attachToExpress(express()) // start http server server.listen(port, (err) => { if (err) { return console.error(err) } console.log(`Listening on port ${port}`) })
Add a space to let it shine.
<?php /** * _s Theme Customizer * * @package _s * @since _s 1.2 */ /** * Add postMessage support for site title and description for the Theme Customizer. * * @param WP_Customize_Manager $wp_customize Theme Customizer object. * * @since _s 1.2 */ function _s_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; } add_action( 'customize_register', '_s_customize_register' ); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. * * @since _s 1.2 */ function _s_customize_preview_js() { wp_enqueue_script( '_s_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20120827', true ); } add_action( 'customize_preview_init', '_s_customize_preview_js' );
<?php /** * _s Theme Customizer * * @package _s * @since _s 1.2 */ /** * Add postMessage support for site title and description for the Theme Customizer. * * @param WP_Customize_Manager $wp_customize Theme Customizer object. * * @since _s 1.2 */ function _s_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; } add_action( 'customize_register', '_s_customize_register' ); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. * * @since _s 1.2 */ function _s_customize_preview_js() { wp_enqueue_script( '_s_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20120827', true ); } add_action( 'customize_preview_init', '_s_customize_preview_js' );
Enable versioning using Git tags, rendering of README in markdown syntax and limit depenencies by version.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( # package data name='freesif', description='Get data from Sesam Interface Files', use_scm_version=True, packages=find_packages(exclude=['contrib', 'docs', 'tests*']), package_data=dict(), python_requires='~=3.7', setup_requires=['setuptools_scm'], install_requires=[ 'tables>=3.6,<4', 'numpy>=1.17,<2' ], zip_safe=True, # meta data long_description=read('README.md'), keywords='sesam structural hydrodynamic', url='https://github.com/agrav/freesif', author='Audun Gravdal Johansen', author_email='audun.gravdal.johansen@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', ], )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.txt'), encoding='utf-8') as f: long_description = f.read() setup( name='freesif', version='0.1', description='Get data from Sesam Interface Files', long_description=long_description, # url='https://github.com/agrav/freesif', author='Audun Gravdal Johansen', author_email='audun.gravdal.johansen@gmail.com', license='MIT', classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', # 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], keywords='sesam structural hydrodynamic', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), install_requires=['tables', 'numpy'], )
Improve non-empty check on array.
<?php namespace Halfpastfour\PHPChartJS\Renderer; /** * Class Json * * @package Halfpastfour\PHPChartJS\Renderer */ class Json extends Renderer { /** * Render the necessary JSON for the chart to function in the frontend. * * @param int|null $flags * * @return string */ public function render($flags = JSON_PRETTY_PRINT) { $config = [ 'type' => constant(get_class($this->chart) . "::TYPE"), 'data' => [], ]; $labels = $this->chart->labels()->getArrayCopy(); if ($labels) { $config['data']['labels'] = $labels; } $dataSets = $this->chart->dataSets()->getArrayCopy(); if ($dataSets) { $config['data']['datasets'] = $dataSets; } $options = $this->chart->options()->getArrayCopy(); if (! empty($options)) { $config['options'] = $options; } return json_encode($config, $flags); } }
<?php namespace Halfpastfour\PHPChartJS\Renderer; /** * Class Json * * @package Halfpastfour\PHPChartJS\Renderer */ class Json extends Renderer { /** * Render the necessary JSON for the chart to function in the frontend. * * @param int|null $flags * * @return string * @throws \ReflectionException */ public function render($flags = JSON_PRETTY_PRINT) { $config = [ 'type' => constant(get_class($this->chart) . "::TYPE"), 'data' => [], ]; $labels = $this->chart->labels()->getArrayCopy(); if ($labels) { $config['data']['labels'] = $labels; } $dataSets = $this->chart->dataSets()->getArrayCopy(); if ($dataSets) { $config['data']['datasets'] = $dataSets; } $options = $this->chart->options()->getArrayCopy(); if ($options) { $config['options'] = $options; } return json_encode($config, $flags); } }
Fix chaining grammar typoo - use '.should.be.a()' instead of (working, but less clear) '.should.a()'
/*jshint expr:true */ describe('DeviceModel', function() { describe('instantiation', function() { beforeEach(function() { this.model = new spiderOakApp.DeviceModel({ name: "Test device", url: "Test%20device/", icon: "mac" }); }); it('should have a name', function() { this.model.get("name").should.be.a("string"); this.model.get("name").should.equal("Test device"); }); it('should have a URL', function() { this.model.get("url").should.be.a("string"); this.model.get("url").should.equal("Test%20device/"); }); it('should have an icon', function() { this.model.get("icon").should.be.a("string"); this.model.get("icon").should.equal("mac"); }); }); });
/*jshint expr:true */ describe('DeviceModel', function() { describe('instantiation', function() { beforeEach(function() { this.model = new spiderOakApp.DeviceModel({ name: "Test device", url: "Test%20device/", icon: "mac" }); }); it('should have a name', function() { this.model.get("name").should.be.a("string"); this.model.get("name").should.equal("Test device"); }); it('should have a URL', function() { this.model.get("url").should.a("string"); this.model.get("url").should.equal("Test%20device/"); }); it('should have an icon', function() { this.model.get("icon").should.a("string"); this.model.get("icon").should.equal("mac"); }); }); });
Put in call to to UsersService to actually change password
from flask_login import current_user from app.brain.user_management.change_password_result import ChangePasswordResult from app.brain.utilities import hash_password from app.service import UsersService class AccountUpdater(object): @staticmethod def change_password(old_password, new_password, confirm_password): if new_password != confirm_password: return ChangePasswordResult.NEW_PASSWORDS_DO_NOT_MATCH elif not current_user.is_authenticated: # Some how the user isn't logged in --- this should never happen return ChangePasswordResult.CURRENT_PASSWORD_INCORRECT elif hash_password(old_password) != current_user.password: return ChangePasswordResult.CURRENT_PASSWORD_INCORRECT else: # If we get to here, we go ahead and change the password UsersService.change_password(current_user, hash_password(new_password))
from flask_login import current_user from app.brain.user_management.change_password_result import ChangePasswordResult from app.brain.utilities import hash_password class AccountUpdater(object): @staticmethod def change_password(old_password, new_password, confirm_password): if new_password != confirm_password: return ChangePasswordResult.NEW_PASSWORDS_DO_NOT_MATCH elif not current_user.is_authenticated: # Some how the user isn't logged in --- this should never happen return ChangePasswordResult.CURRENT_PASSWORD_INCORRECT elif hash_password(old_password) != current_user.password: return ChangePasswordResult.CURRENT_PASSWORD_INCORRECT else: # If we get to here, we go ahead and change the password # TODO: This logic needs to be updated pass
Use base is-nan and is-integer modules
'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/utils/is-nan' ); var isInteger = require( '@stdlib/math/base/utils/is-integer' ); var gamma = require( '@stdlib/math/base/special/gamma' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); var FACTORIALS = require( './factorials.json' ); // VARIABLES // var MAX_FACTORIAL = 170; // FIXME: make into constant // FACTORIAL // /** * FUNCTION: factorial( x ) * Computes the factorial of x. * * @param {Number} x - input value * @returns {Number} factorial */ function factorial( x ) { if ( isnan( x ) ) { return NaN; } if ( isInteger( x ) ) { if ( x < 0 ) { return NaN; } if ( x <= MAX_FACTORIAL ) { return FACTORIALS[ x ]; } return PINF; } return gamma( x + 1 ); } // end FUNCTION factorial() // EXPORTS // module.exports = factorial;
'use strict'; // MODULES // var gamma = require( '@stdlib/math/base/special/gamma' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); var FACTORIALS = require( './factorials.json' ); // VARIABLES // var MAX_FACTORIAL = 170; // FACTORIAL // /** * FUNCTION: factorial( x ) * Computes the factorial of x. * * @param {Number} x - input value * @returns {Number} factorial */ function factorial( x ) { // Check for `NaN`: if ( x !== x ) { return NaN; } // Check for `integer`: if ( x%1 === 0 ) { if ( x < 0 ) { return NaN; } if ( x <= MAX_FACTORIAL ) { return FACTORIALS[ x ]; } return PINF; } return gamma( x + 1 ); } // end FUNCTION factorial() // EXPORTS // module.exports = factorial;
Change autocorrelation to autocov. Variance infromation improves ABC results.
import numpy as np """Example implementation of the MA2 model """ # TODO: add tests def MA2(n_obs, t1, t2, n_sim=1, prng=None, latents=None): if latents is None: if prng is None: prng = np.random.RandomState() latents = prng.randn(n_sim, n_obs+2) # i.i.d. sequence ~ N(0,1) u = np.atleast_2d(latents) y = u[:,2:] + t1 * u[:,1:-1] + t2 * u[:,:-2] return y def autocov(lag, x): """Autocovariance assuming a (weak) univariate stationary process with realizations in rows """ mu = np.mean(x, axis=1, keepdims=True) C = np.mean(x[:,lag:] * x[:,:-lag], axis=1, keepdims=True) - mu**2 return C def distance(x, y): d = np.linalg.norm( np.array(x) - np.array(y), ord=2, axis=0) return d
import numpy as np """Example implementation of the MA2 model """ # TODO: add tests def MA2(n_obs, t1, t2, n_sim=1, prng=None, latents=None): if latents is None: if prng is None: prng = np.random.RandomState() latents = prng.randn(n_sim, n_obs+2) # i.i.d. sequence ~ N(0,1) u = np.atleast_2d(latents) y = u[:,2:] + t1 * u[:,1:-1] + t2 * u[:,:-2] return y def autocov(lag, x): """Normalized autocovariance (i.e. autocorrelation) assuming a (weak) stationary process. Assuming univariate stochastic process with realizations in rows """ mu = np.mean(x, axis=1, keepdims=True) var = np.var(x, axis=1, keepdims=True, ddof=1) # Autocovariance C = np.mean(x[:,lag:] * x[:,:-lag], axis=1, keepdims=True) - mu**2 # Normalize tau = C / var return tau def distance(x, y): d = np.linalg.norm( np.array(x) - np.array(y), ord=2, axis=0) return d
tests/thread_pthread_barrier: Remove f string in test This causes nightlies to fail as the HiL test runners don't have python3.6+
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect('Start {}'.format(i + 1)) for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect(f'Start {i + 1}') for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
Fix path resolving for absolute paths
/** * Ensures that the label package file actually exists * @param {String} path - path to the json file label package * @return {Bool || Error} this is a try-catch where the error */ "use strict"; const fs = require("fs"); const path = require("path"); const removeAllFromStr = require("../utils/removeAllFromStr"); const isJsonString = require("../utils/isJsonString"); // Not using arrows bc it will mess up "this" context module.exports = function (jsonPath) { // Declare function as asynchronous, and save the done callback let done = this.async(); try { if (jsonPath.indexOf(".json") < 0) { done("Not a JSON file"); return; } // Calculate the full path of the JSON file based upon the current working directory. Using // path.resolve allows for absolute paths to be used also. let fullPath = path.resolve(process.cwd(), jsonPath); fs.readFile(fullPath, (err, data) => { if (err){ done(err); return; } if (isJsonString(data)) { done(true); } done("Not a valid JSON file"); }); } catch (e){ done(e); return; } };
/** * Ensures that the label package file actually exists * @param {String} path - path to the json file label package * @return {Bool || Error} this is a try-catch where the error */ "use strict"; const fs = require("fs"); const removeAllFromStr = require("../utils/removeAllFromStr"); const isJsonString = require("../utils/isJsonString"); // Not using arrows bc it will mess up "this" context module.exports = function (path) { // Declare function as asynchronous, and save the done callback let done = this.async(); try { if (path.indexOf(".json") < 0) { done("Not a JSON file"); return; } let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path; let fullPath = process.cwd() + "/" + removeAllFromStr( packagePath, [ "`", '"', "'" ] ) fs.readFile(fullPath, (err, data) => { if (err){ done(err); return; } if (isJsonString(data)) { done(true); } done("Not a valid JSON file"); }); } catch (e){ done(e); return; } };
Change Mod Class and name
package li.cil.oc.example.architecture; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; /** * This mod demonstrates how to create tile entities that are treated as * components by OpenComputers, i.e. tile entities that provide methods which * can be called from a program running on a computer. * <p/> * The mod tries to keep everything else to a minimum, to focus on the mod- * specific parts. It is not intended for use or distribution, but you're free * to base a proper addon on this code. */ @Mod(modid = "OpenComputers|ExampleArchitecture", name = "OpenComputers Addon Example - Architecture", version = "1.0.0", dependencies = "required-after:OpenComputers@[1.4.0,)") public class ModExampleArchitecture { @Mod.Instance public static ModExampleArchitecture instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { li.cil.oc.api.Machine.add(PseudoArchitecture.class); } }
package li.cil.oc.example.architecture; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; /** * This mod demonstrates how to create tile entities that are treated as * components by OpenComputers, i.e. tile entities that provide methods which * can be called from a program running on a computer. * <p/> * The mod tries to keep everything else to a minimum, to focus on the mod- * specific parts. It is not intended for use or distribution, but you're free * to base a proper addon on this code. */ @Mod(modid = "OpenComputers|ExampleTileEntity", name = "OpenComputers Addon Example - TileEntity", version = "1.0.0", dependencies = "required-after:OpenComputers@[1.2.0,)") public class ModExampleTileEntity { @Mod.Instance public static ModExampleTileEntity instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { li.cil.oc.api.Machine.add(PseudoArchitecture.class); } }
Add support for variables in JSON subfields
import { GraphQLScalarType } from 'graphql'; import { Kind } from 'graphql/language'; function identity(value) { return value; } function parseLiteral(ast, variables) { switch (ast.kind) { case Kind.STRING: case Kind.BOOLEAN: return ast.value; case Kind.INT: case Kind.FLOAT: return parseFloat(ast.value); case Kind.OBJECT: { const value = Object.create(null); ast.fields.forEach(field => { value[field.name.value] = parseLiteral(field.value, variables); }); return value; } case Kind.LIST: return ast.values.map(n => parseLiteral(n, variables)); case Kind.NULL: return null; case Kind.VARIABLE: { const name = ast.name.value; return variables ? variables[name] : undefined; } default: return undefined; } } export default new GraphQLScalarType({ name: 'JSON', description: 'The `JSON` scalar type represents JSON values as specified by ' + '[ECMA-404](http://www.ecma-international.org/' + 'publications/files/ECMA-ST/ECMA-404.pdf).', serialize: identity, parseValue: identity, parseLiteral, });
import { GraphQLScalarType } from 'graphql'; import { Kind } from 'graphql/language'; function identity(value) { return value; } function parseLiteral(ast) { switch (ast.kind) { case Kind.STRING: case Kind.BOOLEAN: return ast.value; case Kind.INT: case Kind.FLOAT: return parseFloat(ast.value); case Kind.OBJECT: { const value = Object.create(null); ast.fields.forEach((field) => { value[field.name.value] = parseLiteral(field.value); }); return value; } case Kind.LIST: return ast.values.map(parseLiteral); case Kind.NULL: return null; default: return undefined; } } export default new GraphQLScalarType({ name: 'JSON', description: 'The `JSON` scalar type represents JSON values as specified by ' + '[ECMA-404](http://www.ecma-international.org/' + 'publications/files/ECMA-ST/ECMA-404.pdf).', serialize: identity, parseValue: identity, parseLiteral, });
Use facingMode: user when retrieving user video
import * as NotifyActions from './NotifyActions.js' import * as SocketActions from './SocketActions.js' import * as StreamActions from './StreamActions.js' import * as constants from '../constants.js' import Promise from 'bluebird' import socket from '../socket.js' import { callId, getUserMedia } from '../window.js' export const init = () => dispatch => { return dispatch({ type: constants.INIT, payload: Promise.all([ connect()(dispatch), getCameraStream()(dispatch) ]) .spread((socket, stream) => { dispatch(SocketActions.handshake({ socket, roomName: callId, stream })) }) }) } export const connect = () => dispatch => { return new Promise(resolve => { socket.once('connect', () => { resolve(socket) }) socket.on('connect', () => { dispatch(NotifyActions.warning('Connected to server socket')) }) socket.on('disconnect', () => { dispatch(NotifyActions.error('Server socket disconnected')) }) }) } export const getCameraStream = () => dispatch => { return getUserMedia({ video: { facingMode: 'user' }, audio: true }) .then(stream => { dispatch(StreamActions.addStream({ stream, userId: constants.ME })) return stream }) .catch(() => { dispatch(NotifyActions.alert('Could not get access to microphone & camera')) return null }) }
import * as NotifyActions from './NotifyActions.js' import * as SocketActions from './SocketActions.js' import * as StreamActions from './StreamActions.js' import * as constants from '../constants.js' import Promise from 'bluebird' import socket from '../socket.js' import { callId, getUserMedia } from '../window.js' export const init = () => dispatch => { return dispatch({ type: constants.INIT, payload: Promise.all([ connect()(dispatch), getCameraStream()(dispatch) ]) .spread((socket, stream) => { dispatch(SocketActions.handshake({ socket, roomName: callId, stream })) }) }) } export const connect = () => dispatch => { return new Promise(resolve => { socket.once('connect', () => { resolve(socket) }) socket.on('connect', () => { dispatch(NotifyActions.warning('Connected to server socket')) }) socket.on('disconnect', () => { dispatch(NotifyActions.error('Server socket disconnected')) }) }) } export const getCameraStream = () => dispatch => { return getUserMedia({ video: true, audio: true }) .then(stream => { dispatch(StreamActions.addStream({ stream, userId: constants.ME })) return stream }) .catch(() => { dispatch(NotifyActions.alert('Could not get access to microphone & camera')) return null }) }
Add link to component protocol
/* Fluux XMPP is a Go XMPP library, focusing on simplicity, simple automation, and IoT. The goal is to make simple to write simple adhoc XMPP clients: - For automation (like for example monitoring of an XMPP service), - For building connected "things" by plugging them on an XMPP server, - For writing simple chatbots to control a service or a thing. Fluux XMPP can be used to build XMPP clients or XMPP components. Clients Fluux XMPP can be use to create fully interactive XMPP clients (for example console-based), but it is more commonly used to build automated clients (connected devices, automation scripts, chatbots, etc.). Components XMPP components can typically be used to extends the features of an XMPP server, in a portable way, using component protocol over persistent TCP connections. Component protocol is defined in XEP-114 (https://xmpp.org/extensions/xep-0114.html). Compliance Fluux XMPP has been primarily tested with ejabberd (https://www.ejabberd.im) but it should work with any XMPP compliant server. */ package xmpp
/* Fluux XMPP is a Go XMPP library, focusing on simplicity, simple automation, and IoT. The goal is to make simple to write simple adhoc XMPP clients: - For automation (like for example monitoring of an XMPP service), - For building connected "things" by plugging them on an XMPP server, - For writing simple chatbots to control a service or a thing. Fluux XMPP can be used to build XMPP clients or XMPP components. Clients Fluux XMPP can be use to create fully interactive XMPP clients (for example console-based), but it is more commonly used to build automated clients (connected devices, automation scripts, chatbots, etc.). Components XMPP components can typically be used to extends the features of an XMPP server, in a portable way, using component protocol over persistent TCP connections. Compliance Fluux XMPP has been primarily tested with ejabberd (https://www.ejabberd.im) but it should work with any XMPP compliant server. */ package xmpp
Disable animations in bridgeless mode Summary: Bridgeless mode requires all native modules to be turbomodules. The iOS animated module was converted to TM, but reverted due to perf issues. RSNara is looking into it, but it may be an involved fix. As a short term workaround, to unblock release mode testing of bridgeless mode, use `AnimatedMock`. Changelog: [Internal] Disable animations in bridgeless mode Reviewed By: RSNara Differential Revision: D19729827 fbshipit-source-id: e6c4d89258ec23da252c047b4c67c171f7f21c25
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; import Platform from '../../Utilities/Platform'; const View = require('../../Components/View/View'); const React = require('react'); import type {AnimatedComponentType} from './createAnimatedComponent'; const AnimatedMock = require('./AnimatedMock'); const AnimatedImplementation = require('./AnimatedImplementation'); //TODO(T57411659): Remove the bridgeless check when Animated perf regressions are fixed. const Animated = ((Platform.isTesting || global.RN$Bridgeless ? AnimatedMock : AnimatedImplementation): typeof AnimatedMock); module.exports = { get FlatList(): any { return require('./components/AnimatedFlatList'); }, get Image(): any { return require('./components/AnimatedImage'); }, get ScrollView(): any { return require('./components/AnimatedScrollView'); }, get SectionList(): any { return require('./components/AnimatedSectionList'); }, get Text(): any { return require('./components/AnimatedText'); }, get View(): AnimatedComponentType< React.ElementConfig<typeof View>, React.ElementRef<typeof View>, > { return require('./components/AnimatedView'); }, ...Animated, };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; import Platform from '../../Utilities/Platform'; const View = require('../../Components/View/View'); const React = require('react'); import type {AnimatedComponentType} from './createAnimatedComponent'; const AnimatedMock = require('./AnimatedMock'); const AnimatedImplementation = require('./AnimatedImplementation'); const Animated = ((Platform.isTesting ? AnimatedMock : AnimatedImplementation): typeof AnimatedMock); module.exports = { get FlatList(): any { return require('./components/AnimatedFlatList'); }, get Image(): any { return require('./components/AnimatedImage'); }, get ScrollView(): any { return require('./components/AnimatedScrollView'); }, get SectionList(): any { return require('./components/AnimatedSectionList'); }, get Text(): any { return require('./components/AnimatedText'); }, get View(): AnimatedComponentType< React.ElementConfig<typeof View>, React.ElementRef<typeof View>, > { return require('./components/AnimatedView'); }, ...Animated, };
Allow email verification middleware to work with API routes Currently if you apply the email verification middleware to an API route (XHR) you get strange/broken behaviour because of the redirect. So, when the request expects JSON, just return a 403. This solves my issues.
<?php namespace Illuminate\Auth\Middleware; use Closure; use Illuminate\Support\Facades\Redirect; use Illuminate\Contracts\Auth\MustVerifyEmail; class EnsureEmailIsVerified { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle($request, Closure $next) { if (! $request->user() || ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail())) { if ($request->expectsJson()) { abort(403, 'Your email address is not verified.'); } else { return Redirect::route('verification.notice'); } } return $next($request); } }
<?php namespace Illuminate\Auth\Middleware; use Closure; use Illuminate\Support\Facades\Redirect; use Illuminate\Contracts\Auth\MustVerifyEmail; class EnsureEmailIsVerified { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return \Illuminate\Http\Response */ public function handle($request, Closure $next) { if (! $request->user() || ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail())) { return Redirect::route('verification.notice'); } return $next($request); } }
Fix fluid in tank rendering
package xyz.brassgoggledcoders.steamagerevolution.modules.storage.renderers; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import xyz.brassgoggledcoders.steamagerevolution.modules.storage.tileentities.TileEntityBasicFluidTank; import xyz.brassgoggledcoders.steamagerevolution.utils.RenderUtil; public class TileEntityBasicFluidTankRenderer extends TileEntitySpecialRenderer<TileEntityBasicFluidTank> { protected static Minecraft mc = Minecraft.getMinecraft(); @Override public void render(TileEntityBasicFluidTank tile, double x, double y, double z, float partialTicks, int destroyStage, float alpha) { FluidTank tank = tile.tank; FluidStack liquid = tank.getFluid(); if(liquid != null) { float height = ((float) liquid.amount) / (float) tank.getCapacity(); float d = RenderUtil.FLUID_OFFSET; RenderUtil.renderFluidCuboid(liquid, tile.getPos(), x, y, z, d, d, d, 1d - d, height - d, 1d - d); } } }
package xyz.brassgoggledcoders.steamagerevolution.modules.storage.renderers; import javax.annotation.Nonnull; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import xyz.brassgoggledcoders.steamagerevolution.modules.storage.tileentities.TileEntityBasicFluidTank; import xyz.brassgoggledcoders.steamagerevolution.utils.RenderUtil; public class TileEntityBasicFluidTankRenderer extends TileEntitySpecialRenderer<TileEntityBasicFluidTank> { protected static Minecraft mc = Minecraft.getMinecraft(); @Override public void renderTileEntityFast(@Nonnull TileEntityBasicFluidTank tile, double x, double y, double z, float partialTicks, int destroyStage, float partial, net.minecraft.client.renderer.BufferBuilder buffer) { FluidTank tank = tile.tank; FluidStack liquid = tank.getFluid(); if(liquid != null) { float height = ((float) liquid.amount) / (float) tank.getCapacity(); float d = RenderUtil.FLUID_OFFSET; RenderUtil.renderFluidCuboid(liquid, tile.getPos(), x, y, z, d, d, d, 1d - d, height - d, 1d - d); } } }
Add a user agent identifier to the integration test client
<?php namespace Aws\Test\Integ; trait IntegUtils { private static function getSdk(array $args = []) { return new \Aws\Sdk($args + [ 'region' => 'us-east-1', 'profile' => 'integ', 'version' => 'latest', 'ua_append' => 'PHPUnit/Integration' ]); } public static function log($message) { fwrite(STDERR, date('c') . ': ' . $message . "\n"); } /** * Get the resource prefix to add to created resources * * @return string */ public static function getResourcePrefix() { if (!isset($_SERVER['PREFIX']) || $_SERVER['PREFIX'] == 'hostname') { $_SERVER['PREFIX'] = crc32(gethostname()) . rand(0, 10000); } return $_SERVER['PREFIX']; } }
<?php namespace Aws\Test\Integ; trait IntegUtils { private static function getSdk(array $args = []) { return new \Aws\Sdk($args + [ 'region' => 'us-east-1', 'profile' => 'integ', 'version' => 'latest', 'user-agent' => 'PHPUnit/Integration' ]); } public static function log($message) { fwrite(STDERR, date('c') . ': ' . $message . "\n"); } /** * Get the resource prefix to add to created resources * * @return string */ public static function getResourcePrefix() { if (!isset($_SERVER['PREFIX']) || $_SERVER['PREFIX'] == 'hostname') { $_SERVER['PREFIX'] = crc32(gethostname()) . rand(0, 10000); } return $_SERVER['PREFIX']; } }
Remove escape from double quotes
package org.udg.pds.simpleapp_javaee.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider public class LoggingFilter implements ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String method = requestContext.getMethod(); logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType()); // String json = IOUtils.toString(requestContext.getEntityStream()); Object entity = responseContext.getEntity(); if (entity != null) { String response = new ObjectMapper().writeValueAsString(entity).replace("\\\"", "\""); logger.info("Response: " + response); } } }
package org.udg.pds.simpleapp_javaee.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider public class LoggingFilter implements ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String method = requestContext.getMethod(); logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType()); // String json = IOUtils.toString(requestContext.getEntityStream()); Object entity = responseContext.getEntity(); if (entity != null) { logger.info("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity)); } } }
Remove commented line we definitely will never need
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
import sys import json import requests from string import Template import dateutil.parser def posts_at_url(url): current_page = 1 max_page = sys.maxint while current_page <= max_page: resp = requests.get(url, params={'json':1,'page':current_page}) results = json.loads(resp.content) current_page += 1 max_page = results['pages'] for p in results['posts']: yield p def documents(name, url, **kwargs): for post in posts_at_url(url): yield process_post(post) def process_post(post): del post['comments'] # del post['content'] post['_id'] = post['slug'] # remove fields we're not interested in post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']] author_template = Template("$first_name $last_name") post['author'] = [author['title'] for author in post['taxonomy_author']] dt = dateutil.parser.parse(post['date']) dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ') post['date'] = dt_string return post
Enable muting for internal MIT users. (imported from commit 82dc8c620c5f9af5b7a366bd16aee9125b9ba634)
var feature_flags = (function () { var exports = {}; exports.mark_read_at_bottom = true; exports.summarize_read_while_narrowed = true; exports.twenty_four_hour_time = _.contains([], page_params.email); exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain); exports.email_forwarding = true; exports.mandatory_topics = _.contains([ 'customer7.invalid' ], page_params.domain ); exports.collapsible = page_params.staging; exports.propagate_topic_edits = page_params.staging || _.contains(['customer7.invalid'], page_params.domain); exports.fade_users_when_composing = page_params.staging; exports.alert_words = _.contains(['reddit.com', 'mit.edu', 'zulip.com'], page_params.domain); var zulip_mit_emails = []; var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email); exports.muting = page_params.staging || is_zulip_mit_user; exports.left_side_userlist = page_params.staging || _.contains(['customer7.invalid'], page_params.domain); return exports; }());
var feature_flags = (function () { var exports = {}; exports.mark_read_at_bottom = true; exports.summarize_read_while_narrowed = true; exports.twenty_four_hour_time = _.contains([], page_params.email); exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain); exports.email_forwarding = true; exports.mandatory_topics = _.contains([ 'customer7.invalid' ], page_params.domain ); exports.collapsible = page_params.staging; exports.propagate_topic_edits = page_params.staging || _.contains(['customer7.invalid'], page_params.domain); exports.fade_users_when_composing = page_params.staging; exports.alert_words = _.contains(['reddit.com', 'mit.edu', 'zulip.com'], page_params.domain); exports.muting = page_params.staging; exports.left_side_userlist = page_params.staging || _.contains(['customer7.invalid'], page_params.domain); return exports; }());
Set default API endpoint in config
/* Name: planetos - index.js Source & docs: https://github.com/fvdm/nodejs-planetos Feedback: https://github.com/fvdm/nodejs-planetos/issues License: Unlicense (public domain) */ var httpreq = require ('httpreq'); var config = {}; /** * Get dataset endpoints * * @callback callback * @param dataset {number} - Dataset ID * @param [params] {object} - Additional parameters * @param callback {function} - `function (err, data) {}` * @returns {void} */ function getEndpoints (dataset, params, callback) { } /** * Module setup * * @callback callback * @param conf {object} * @param conf.apikey {string} - Account API key * @param [conf.timeout] {number=5000} - Request timeout in ms * @param [conf.endpoint] {string} - Route API calls to another server * @param callback {function} - `function (err, data) {}` * @returns {void} */ module.exports = function (conf) { config.apikey = conf.apikey || null; config.timeout = conf.timeout || 5000; config.endpoint = conf.endpoint || 'http://api.planetos.com/v1'; return { endpoints: getEndpoints }; };
/* Name: planetos - index.js Source & docs: https://github.com/fvdm/nodejs-planetos Feedback: https://github.com/fvdm/nodejs-planetos/issues License: Unlicense (public domain) */ var httpreq = require ('httpreq'); var config = {}; /** * Get dataset endpoints * * @callback callback * @param dataset {number} - Dataset ID * @param [params] {object} - Additional parameters * @param callback {function} - `function (err, data) {}` * @returns {void} */ function getEndpoints (dataset, params, callback) { } /** * Module setup * * @callback callback * @param conf {object} * @param conf.apikey {string} - Account API key * @param [conf.timeout] {number=5000} - Request timeout in ms * @param [conf.endpoint] {string} - Route API calls to another server * @param callback {function} - `function (err, data) {}` * @returns {void} */ module.exports = function (conf) { config.apikey = conf.apikey || null; config.timeout = conf.timeout || 5000; config.endpoint = conf.endpoint || null; return { endpoints: getEndpoints }; };
Add tinymce provider to maintenance provider list fixes build when using maintenance. fixes #316
<?php class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract { public function __construct() { $providers = array(); $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_JsClassKwf(); $providers[] = new Kwf_Assets_Provider_IniNoFiles(); $providers[] = new Kwf_Assets_Provider_ExtTrl(); $providers[] = new Kwf_Assets_Provider_DefaultAssets(); $providers[] = new Kwf_Assets_Provider_ErrorHandler(); $providers[] = new Kwf_Assets_TinyMce_Provider(); parent::__construct($providers); } }
<?php class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract { public function __construct() { $providers = array(); $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_JsClassKwf(); $providers[] = new Kwf_Assets_Provider_IniNoFiles(); $providers[] = new Kwf_Assets_Provider_ExtTrl(); $providers[] = new Kwf_Assets_Provider_DefaultAssets(); $providers[] = new Kwf_Assets_Provider_ErrorHandler(); parent::__construct($providers); } }
Add iOS specific check for NFC capabilities.
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.ios.activation; import org.openecard.mobile.activation.NFCCapabilities; import org.openecard.mobile.activation.NfcCapabilityResult; import org.robovm.apple.corenfc.NFCReaderSession; /** * * @author Neil Crossley */ public class IOSNFCCapabilities implements NFCCapabilities { @Override public boolean isAvailable() { return NFCReaderSession.isReadingAvailable(); } @Override public boolean isEnabled() { return true; } @Override public NfcCapabilityResult checkExtendedLength() { return NfcCapabilityResult.QUERY_NOT_ALLOWED; } }
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.ios.activation; import org.openecard.mobile.activation.NFCCapabilities; import org.openecard.mobile.activation.NfcCapabilityResult; /** * * @author Neil Crossley */ public class IOSNFCCapabilities implements NFCCapabilities { @Override public boolean isAvailable() { return true; } @Override public boolean isEnabled() { return true; } @Override public NfcCapabilityResult checkExtendedLength() { return NfcCapabilityResult.QUERY_NOT_ALLOWED; } }
Increase the amount of output in build scan performance tests.
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() { for (int i = 0; i < 100; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() { for (int i = 0; i < 100; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() { for (int i = 0; i < 10; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() { for (int i = 0; i < 10; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
Remove sleep time as it appeared to hang forever
import sys import time import asyncio import logging def pg_lsn_to_int(pos): # http://www.postgresql.org/docs/9.4/static/datatype-pg-lsn.html # see http://eulerto.blogspot.com.es/2011/11/understanding-wal-nomenclature.html logfile, offset = pos.split('/') return 0xFF000000 * int(logfile, 16) + int(offset, 16) def exception_handler(loop, context): loop.default_exception_handler(context) logging.error('Unexpected exception, exiting...') sys.exit(1) def run_asyncio(*callback_and_args): loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) if callback_and_args: loop.call_soon(*callback_and_args) loop.run_forever() logging.info('Exiting after being asked to stop nicely') return 0
import sys import time import asyncio import logging def pg_lsn_to_int(pos): # http://www.postgresql.org/docs/9.4/static/datatype-pg-lsn.html # see http://eulerto.blogspot.com.es/2011/11/understanding-wal-nomenclature.html logfile, offset = pos.split('/') return 0xFF000000 * int(logfile, 16) + int(offset, 16) def exception_handler(loop, context): sleep_time = 10 try: loop.default_exception_handler(context) logging.error('Unexpected exception, exiting...') # TODO: can we do some kind of backoff? finally: time.sleep(sleep_time) sys.exit(1) def run_asyncio(*callback_and_args): loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) if callback_and_args: loop.call_soon(*callback_and_args) loop.run_forever() logging.info('Exiting after being asked to stop nicely') return 0
Update get_lca_matrix test for develop
# coding: utf-8 from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
# coding: utf-8 from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all()
Add clean task to gulp config
/// <binding AfterBuild='nuget-pack' /> "use strict"; var gulp = require('gulp'), path = require('path'), exec = require('child_process').exec, fs = require('fs'); var solutionFolder = path.resolve(__dirname, '..'); var projectFolder = path.join(solutionFolder, 'MAB.DotIgnore'); var distFolder = path.join(solutionFolder, 'dist'); if (!fs.existsSync(distFolder)) { fs.mkdirSync(distFolder); } gulp.task('nuget-clean', function (callback) { exec('del *.nupkg', { cwd: distFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); }); gulp.task('nuget-pack', ['nuget-clean'], function (callback) { exec('nuget pack MAB.DotIgnore.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); });
/// <binding AfterBuild='nuget-pack' /> "use strict"; var gulp = require('gulp'), path = require('path'), exec = require('child_process').exec, fs = require('fs'); var solutionFolder = path.resolve(__dirname, '..'); var projectFolder = path.join(solutionFolder, 'MAB.DotIgnore'); var distFolder = path.join(solutionFolder, 'dist'); if (!fs.existsSync(distFolder)) { fs.mkdirSync(distFolder); } gulp.task('nuget-pack', function (callback) { exec('nuget pack MAB.DotIgnore.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); });
Make it compile with recent version of twilio
from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, current_app, request from twilio.twiml.voice_response import VoiceResponse from twilio.request_validator import RequestValidator from config import * def twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) url = list(urlparse(request.url)) url[1] = url[1].encode("idna").decode("utf-8") url = urlunparse(url) signature = request.headers.get("X-TWILIO-SIGNATURE", "") request_valid = validator.validate(url, request.form, signature) if request_valid or current_app.debug: resp = VoiceResponse() f(resp, *args, **kwargs) return str(resp) else: return abort(403) return decorated_function
from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, current_app, request from twilio.twiml import Response from twilio.util import RequestValidator from config import * def twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) url = list(urlparse(request.url)) url[1] = url[1].encode("idna").decode("utf-8") url = urlunparse(url) signature = request.headers.get("X-TWILIO-SIGNATURE", "") request_valid = validator.validate(url, request.form, signature) if request_valid or current_app.debug: resp = Response() f(resp, *args, **kwargs) return str(resp) else: return abort(403) return decorated_function
Add shebang to cli_tets.py module
#!/usr/bin/env python3 # # Copyright (c) 2021, Nicola Coretti # All rights reserved. import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.called) self.assertEqual(exit_mock.call_args, (call(expected_exit_code))) def test_table_subcommand_with_no_additional_arguments(self): expected_exit_code = -1 argv = ['table'] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.called) self.assertEqual(exit_mock.call_args, (call(expected_exit_code))) if __name__ == '__main__': unittest.main()
import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.called) self.assertEqual(exit_mock.call_args, (call(expected_exit_code))) def test_table_subcommand_with_no_additional_arguments(self): expected_exit_code = -1 argv = ['table'] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.called) self.assertEqual(exit_mock.call_args, (call(expected_exit_code))) if __name__ == '__main__': unittest.main()
Replace `fmt` with `log` in clean.
package clean import ( "os" "path/filepath" "strings" "github.com/littledot/mockhiato/lib" "github.com/littledot/mockhiato/lib/plugin/github.com/stretchr/testify" log "github.com/sirupsen/logrus" ) // Run executes the command. func Run(config lib.Config) { projectPath, err := filepath.Abs(config.ProjectPath) if err != nil { panic(err) } formatter := testify.NewTestifyFormatter(config) err = filepath.Walk(projectPath, func(filePath string, info os.FileInfo, err error) error { if err != nil { // Something wrong? Skip return nil } if !strings.HasSuffix(filePath, ".go") { // Not Go source? Skip return nil } file, err := os.Open(filePath) if err != nil { return nil } defer file.Close() if formatter.IsMockFile(file) { // Formatter says its a mock? Remove log.Infof("Remove %s", filePath) if err := os.Remove(filePath); err != nil { panic(err) } } return nil }) if err != nil { panic(err) } }
package clean import ( "fmt" "os" "path/filepath" "strings" "github.com/littledot/mockhiato/lib" "github.com/littledot/mockhiato/lib/plugin/github.com/stretchr/testify" ) // Run executes the command. func Run(config lib.Config) { projectPath, err := filepath.Abs(config.ProjectPath) if err != nil { panic(err) } formatter := testify.NewTestifyFormatter(config) err = filepath.Walk(projectPath, func(filePath string, info os.FileInfo, err error) error { if err != nil { // Something wrong? Skip return nil } if !strings.HasSuffix(filePath, ".go") { // Not Go source? Skip return nil } file, err := os.Open(filePath) if err != nil { return nil } defer file.Close() if formatter.IsMockFile(file) { // Formatter says its a mock? Remove fmt.Println("Removing", filePath) if err := os.Remove(filePath); err != nil { panic(err) } } return nil }) if err != nil { panic(err) } }
Delete a tree redo completed
package GeeksforGeeksPractice; public class _0003DeleteATree { public static void main(String args[]){ TreeNode tn=new TreeNode(1); tn.left=new TreeNode(2); tn.right=new TreeNode(3); tn.left.right=new TreeNode(4); tn.left.left=new TreeNode(5); tn.left.left.left=new TreeNode(6); tn.left.left.left.left=new TreeNode(7); preOrder(tn);System.out.println(); deleteTree(tn); preOrder(tn);System.out.println(); //-1/-1/-1/-1/-1/-1/-1/ } private static void preOrder(TreeNode tn) { if(tn!=null) { System.out.print(tn.val+"/"); preOrder(tn.left); preOrder(tn.right); } } private static void deleteTree(TreeNode tn) { if(tn!=null) { deleteTree(tn.left); deleteTree(tn.right); //make tn as null,but to check output make value as -1 tn.val=-1; } } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
package GeeksforGeeksPractice; public class _0003DeleteATree { public static void main(String args[]){ TreeNode tn=new TreeNode(1); tn.left=new TreeNode(2); tn.right=new TreeNode(3); tn.left.right=new TreeNode(4); tn.left.left=new TreeNode(5); tn.left.left.left=new TreeNode(6); tn.left.left.left.left=new TreeNode(7); preOrder(tn);System.out.println(); deleteTree(tn); preOrder(tn);System.out.println(); //-1/-1/-1/-1/-1/-1/-1/ } private static void preOrder(TreeNode tn) { if(tn!=null) { System.out.print(tn.val+"/"); preOrder(tn.left); preOrder(tn.right); } } private static void deleteTree(TreeNode tn) { } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
Fix bug with registering non-school teams
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): if 'is_school' in data and data['is_school']: error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
Set type for subject ID
import click from panoptes_client.panoptes import Panoptes panoptes = Panoptes('https://panoptes.zooniverse.org/api') @click.group() def cli(): pass @cli.command() @click.option('--id', help='Project ID', required=False, type=int) @click.option('--display-name') @click.argument('slug', required=False) def project(id, display_name, slug): projects = panoptes.get_projects(id, slug=slug, display_name=display_name) for proj_data in projects['projects']: click.echo('Project name: %s' % proj_data['display_name']) click.echo('\tClassification count: %s' % proj_data['classifications_count']) click.echo('\tSubject count: %s' % proj_data['subjects_count']) click.echo('') @cli.command() @click.argument('subject_id', required=True, type=int) def subject(subject_id): subject = panoptes.get_subject(subject_id)['subjects'][0] project = panoptes.get_project(subject['links']['project']) click.echo('Project: %s' % project['display_name']) click.echo('Locations:') for location in subject['locations']: for mimetype, uri in location.items(): click.echo('\t%s: %s' % (mimetype, uri))
import click from panoptes_client.panoptes import Panoptes panoptes = Panoptes('https://panoptes.zooniverse.org/api') @click.group() def cli(): pass @cli.command() @click.option('--id', help='Project ID', required=False, type=int) @click.option('--display-name') @click.argument('slug', required=False) def project(id, display_name, slug): projects = panoptes.get_projects(id, slug=slug, display_name=display_name) for proj_data in projects['projects']: click.echo('Project name: %s' % proj_data['display_name']) click.echo('\tClassification count: %s' % proj_data['classifications_count']) click.echo('\tSubject count: %s' % proj_data['subjects_count']) click.echo('') @cli.command() @click.argument('subject_id', required=True) def subject(subject_id): subject = panoptes.get_subject(subject_id)['subjects'][0] project = panoptes.get_project(subject['links']['project']) click.echo('Project: %s' % project['display_name']) click.echo('Locations:') for location in subject['locations']: for mimetype, uri in location.items(): click.echo('\t%s: %s' % (mimetype, uri))
Read names line-by-line from a plain text file.
#! /usr/bin/env python """ Example usage: snbuild data/models.yaml data/scraped.yaml \ > standard_names/data/standard_names.yaml """ import os from . import (from_model_file, FORMATTERS, Collection) from .io import from_list_file def main(): """ Build a list of CSDMS standard names for YAML description files. """ import argparse parser = argparse.ArgumentParser( 'Scan a model description file for CSDMS standard names') parser.add_argument('file', nargs='+', type=argparse.FileType('r'), help='YAML file describing model exchange items') args = parser.parse_args() names = Collection() for model_file in args.file: names |= from_list_file(model_file) formatter = FORMATTERS['yaml'] print '%YAML 1.2' print '---' print os.linesep.join([ formatter(names.names(), sorted=True, heading='names'), '---', formatter(names.objects(), sorted=True, heading='objects'), '---', formatter(names.quantities(), sorted=True, heading='quantities'), '---', formatter(names.operators(), sorted=True, heading='operators'), '...', ]) if __name__ == '__main__': main()
#! /usr/bin/env python """ Example usage: snbuild data/models.yaml data/scraped.yaml \ > standard_names/data/standard_names.yaml """ import os from . import (from_model_file, FORMATTERS, Collection) def main(): """ Build a list of CSDMS standard names for YAML description files. """ import argparse parser = argparse.ArgumentParser( 'Scan a model description file for CSDMS standard names') parser.add_argument('file', nargs='+', type=argparse.FileType('r'), help='YAML file describing model exchange items') args = parser.parse_args() names = Collection() for model_file in args.file: names |= from_model_file(model_file) formatter = FORMATTERS['yaml'] print '%YAML 1.2' print '---' print os.linesep.join([ formatter(names.names(), sorted=True, heading='names'), '---', formatter(names.objects(), sorted=True, heading='objects'), '---', formatter(names.quantities(), sorted=True, heading='quantities'), '---', formatter(names.unique_operators(), sorted=True, heading='operators'), '...', ]) if __name__ == '__main__': main()
Mark usage of temporary files in `cmd` The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ivan Sobolev # Copyright (c) 2016 Ivan Sobolev # # License: MIT # """This module exports the Bemlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Bemlint(NodeLinter): """Provides an interface to bemlint.""" name = 'bemlint' cmd = 'bemlint ${temp_file} ${args}' config_file = ('--config', '.bemlint.json') regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) multiline = False line_col_base = (1, 1) error_stream = util.STREAM_BOTH tempfile_suffix = 'bem' defaults = { 'selector': 'text.html', '--format': 'compact', } # the following attributes are marked useless for SL4 version_args = '--version' version_re = r'v(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.4.5'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ivan Sobolev # Copyright (c) 2016 Ivan Sobolev # # License: MIT # """This module exports the Bemlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Bemlint(NodeLinter): """Provides an interface to bemlint.""" name = 'bemlint' cmd = 'bemlint @ ${args}' config_file = ('--config', '.bemlint.json') regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) multiline = False line_col_base = (1, 1) error_stream = util.STREAM_BOTH tempfile_suffix = 'bem' defaults = { 'selector': 'text.html', '--format': 'compact', } # the following attributes are marked useless for SL4 version_args = '--version' version_re = r'v(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.4.5'
Add Checkbox into IconCheckbox storybook subcomponents
import React from 'react'; import Checkbox from '@ichef/gypcrete/src/Checkbox'; import IconCheckbox from '@ichef/gypcrete/src/IconCheckbox'; import FlexRow from 'utils/FlexRow'; export default { title: '@ichef/gypcrete|IconCheckbox', component: IconCheckbox, subcomponents: { Checkbox, }, }; export function BasicUsage() { return ( <FlexRow> <IconCheckbox /> <IconCheckbox indeterminate /> </FlexRow> ); } export function WithStatus() { return ( <FlexRow> <IconCheckbox defaultChecked status="loading" /> <IconCheckbox status="success" statusOptions={{ autohide: false }} /> <IconCheckbox status="error" errorMsg="Cannot add printer." /> </FlexRow> ); }
import React from 'react'; import IconCheckbox from '@ichef/gypcrete/src/IconCheckbox'; import FlexRow from 'utils/FlexRow'; export default { title: '@ichef/gypcrete|IconCheckbox', component: IconCheckbox }; export function BasicUsage() { return ( <FlexRow> <IconCheckbox /> <IconCheckbox indeterminate /> </FlexRow> ); } export function WithStatus() { return ( <FlexRow> <IconCheckbox defaultChecked status="loading" /> <IconCheckbox status="success" statusOptions={{ autohide: false }} /> <IconCheckbox status="error" errorMsg="Cannot add printer." /> </FlexRow> ); }
Bump version (a little late)
from __future__ import unicode_literals from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2.0.post1' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name return "" # Return empty string if file is empty def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return "{0} {1}".format(get_first_name(gender), get_last_name())
from __future__ import unicode_literals from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name return "" # Return empty string if file is empty def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return "{0} {1}".format(get_first_name(gender), get_last_name())
Fix imports for Django >= 1.6
from django.conf import settings try: from django.conf.urls.defaults import patterns, include except ImportError: # Django >= 1.6 from django.conf.urls import patterns, include import goog.urls from goog import utils class GoogDevelopmentMiddleware(object): def devmode_enabled(self, request): """Returns True iff the devmode is enabled.""" return utils.is_devmode() def process_request(self, request): # This urlconf patching is inspired by debug_toolbar. # https://github.com/robhudson/django-debug-toolbar if self.devmode_enabled(request): original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if original_urlconf != 'goog.urls': goog.urls.urlpatterns += patterns( '', ('', include(original_urlconf)), ) request.urlconf = 'goog.urls'
from django.conf import settings from django.conf.urls.defaults import patterns, include import goog.urls from goog import utils class GoogDevelopmentMiddleware(object): def devmode_enabled(self, request): """Returns True iff the devmode is enabled.""" return utils.is_devmode() def process_request(self, request): # This urlconf patching is inspired by debug_toolbar. # https://github.com/robhudson/django-debug-toolbar if self.devmode_enabled(request): original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if original_urlconf != 'goog.urls': goog.urls.urlpatterns += patterns( '', ('', include(original_urlconf)), ) request.urlconf = 'goog.urls'
Add date tooltip to timestamps
/* Copyright 2015, 2016 OpenMarket Ltd 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. */ 'use strict'; var React = require('react'); var DateUtils = require('matrix-react-sdk/lib/DateUtils'); module.exports = React.createClass({ displayName: 'MessageTimestamp', render: function() { var date = new Date(this.props.ts); return ( <span className="mx_MessageTimestamp" title={ DateUtils.formatDate(date) }> { DateUtils.formatTime(date) } </span> ); }, });
/* Copyright 2015, 2016 OpenMarket Ltd 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. */ 'use strict'; var React = require('react'); var DateUtils = require('matrix-react-sdk/lib/DateUtils'); module.exports = React.createClass({ displayName: 'MessageTimestamp', render: function() { var date = new Date(this.props.ts); return ( <span className="mx_MessageTimestamp"> { DateUtils.formatTime(date) } </span> ); }, });
Use this folder for PLUGIN_FOLDER
<?php $_tests_dir = getenv( 'WP_TESTS_DIR' ); if ( ! $_tests_dir ) { $_tests_dir = '/tmp/wordpress-tests-lib'; } define('PLUGIN_NAME','your-plugin-name-here.php'); define('PLUGIN_FOLDER',basename(dirname( __DIR__ ))); define('PLUGIN_PATH',PLUGIN_FOLDER.'/'.PLUGIN_NAME); // Activates this plugin in WordPress so it can be tested. $GLOBALS['wp_tests_options'] = array( 'active_plugins' => array( PLUGIN_PATH ), ); require_once $_tests_dir . '/includes/functions.php'; function _manually_load_plugin() { require dirname( __DIR__ ) . '/'.PLUGIN_NAME; } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); require $_tests_dir . '/includes/bootstrap.php';
<?php $_tests_dir = getenv( 'WP_TESTS_DIR' ); if ( ! $_tests_dir ) { $_tests_dir = '/tmp/wordpress-tests-lib'; } define('PLUGIN_FOLDER','your-plugin-folder-name-here') define('PLUGIN_NAME','your-plugin-name-here.php'); define('PLUGIN_PATH',PLUGIN_FOLDER.'/'.PLUGIN_NAME); // Activates this plugin in WordPress so it can be tested. $GLOBALS['wp_tests_options'] = array( 'active_plugins' => array( PLUGIN_PATH ), ); require_once $_tests_dir . '/includes/functions.php'; function _manually_load_plugin() { require dirname( __DIR__ ) . '/'.PLUGIN_NAME; } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); require $_tests_dir . '/includes/bootstrap.php';
Use jQuery chaining, you dolt.
$(document).ready(function() { var id = location.pathname.split('/').slice(-1)[0]; if (id) { $.get('get/' + id, function(entry) { $('#paste').show().text(entry.content); $('#content').val(entry.content); }, 'json'); } $('#entry form').bind('submit', function() { var entry = { content: $('#content').val() }; $.post("post", JSON.stringify(entry), function(id) { location = id; }, 'text'); return false; }); });
$(document).ready(function() { var id = location.pathname.split('/').slice(-1)[0]; if (id) { $('#paste').show(); $.get('get/' + id, function(entry) { $('#paste').text(entry.content); $('#content').val(entry.content); }, 'json'); } $('#entry form').bind('submit', function() { var entry = { content: $('#content').val() }; $.post("post", JSON.stringify(entry), function(id) { location = id; }, 'text'); return false; }); });
Disable file logging by default
//Winston Logger Module const winston = require('winston'); let logLevel = "info"; //default if (process.env.NODE_ENV === "production") { logLevel = "error"; //logs error } else if (process.env.NODE_ENV === "staging") { logLevel = "info"; //logs info and error } const logger = new winston.Logger({ transports: [ new winston.transports.Console({ //write prettified logs to console colorize: true, timestamp: true, level: logLevel }), /* new winston.transports.File({ //write logs to a file as well level: logLevel, name: 'policy_logs', filename: 'policy_logs.log' }) */ ], exitOnError: false }); module.exports = { //required functions to implement //normal message. log to file and to the console as an "info" message info: function (msg) { logger.info(msg); }, //error message. log to file and to the console as an "error" message error: function (msg) { logger.error(msg); } }
//Winston Logger Module const winston = require('winston'); let logLevel = "info"; //default if (process.env.NODE_ENV === "production") { logLevel = "error"; //logs error } else if (process.env.NODE_ENV === "staging") { logLevel = "info"; //logs info and error } const logger = new winston.Logger({ transports: [ new winston.transports.Console({ //write prettified logs to console colorize: true, timestamp: true, level: logLevel }), new winston.transports.File({ //write logs to a file as well level: logLevel, name: 'policy_logs', filename: 'policy_logs.log' }) ], exitOnError: false }); module.exports = { //required functions to implement //normal message. log to file and to the console as an "info" message info: function (msg) { logger.info(msg); }, //error message. log to file and to the console as an "error" message error: function (msg) { logger.error(msg); } }
Improve StringIterator to allow for more general usage
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # 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. """Iterate over string""" from __future__ import absolute_import import StringIO import d1_common.const class StringIterator(object): """Generator that returns the bytes of a string in chunks""" def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE): self._string = string self._chunk_size = chunk_size def __iter__(self): f = StringIO.StringIO(self._string) while True: chunk_str = f.read(self._chunk_size) if not chunk_str: break yield chunk_str def __len__(self): return len(self._string) @property def size(self): return len(self._string)
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # 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. """Iterate over string""" from __future__ import absolute_import import StringIO import d1_common.const class StringIterator(object): """Generator that returns the bytes of a string in chunks""" def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE): self._string = string self._chunk_size = chunk_size def __iter__(self): f = StringIO.StringIO(self._string) while True: chunk_str = f.read(self._chunk_size) if not chunk_str: break yield chunk_str
db: Change sort test to use time in millis.
package db import ( "testing" "time" "github.com/octavore/ketchup/proto/ketchup/models" ) func TestSort(t *testing.T) { now := time.Now() nowUnix := now.UnixNano() / 1e6 nowPlus1 := now.Add(time.Minute).UnixNano() / 1e6 nowPlus2 := now.Add(time.Minute*2).UnixNano() / 1e6 pages := []*models.Page{ {Timestamps: &models.Timestamp{UpdatedAt: &nowUnix}}, {Timestamps: &models.Timestamp{UpdatedAt: &nowPlus2}}, {Timestamps: &models.Timestamp{UpdatedAt: &nowPlus1}}, } SortPagesByUpdatedAt(pages, true) expected := []int64{nowUnix, nowPlus1, nowPlus2} for i, n := range expected { ps := pages[i].GetTimestamps().GetUpdatedAt() if ps != n { t.Fatalf("expected %v but got %v at %v", n, ps, i) } } SortPagesByUpdatedAt(pages, false) expected = []int64{nowPlus2, nowPlus1, nowUnix} for i, n := range expected { ps := pages[i].GetTimestamps().GetUpdatedAt() if ps != n { t.Fatalf("expected %v but got %v at %v", n, ps, i) } } }
package db import ( "testing" "time" "github.com/octavore/ketchup/proto/ketchup/models" ) func TestSort(t *testing.T) { now := time.Now() nowUnix := now.Unix() nowPlus1 := now.Add(time.Minute).Unix() nowPlus2 := now.Add(time.Minute * 2).Unix() pages := []*models.Page{ {Timestamps: &models.Timestamp{UpdatedAt: &nowUnix}}, {Timestamps: &models.Timestamp{UpdatedAt: &nowPlus2}}, {Timestamps: &models.Timestamp{UpdatedAt: &nowPlus1}}, } SortPagesByUpdatedAt(pages, true) expected := []int64{nowUnix, nowPlus1, nowPlus2} for i, n := range expected { ps := pages[i].GetTimestamps().GetUpdatedAt() if ps != n { t.Fatalf("expected %v but got %v at %v", n, ps, i) } } SortPagesByUpdatedAt(pages, false) expected = []int64{nowPlus2, nowPlus1, nowUnix} for i, n := range expected { ps := pages[i].GetTimestamps().GetUpdatedAt() if ps != n { t.Fatalf("expected %v but got %v at %v", n, ps, i) } } }
Allow for Missing Buildpack Filename Previously we assumed that all buildpacks would have an associated filename. It is possible to create a buildpack without a filename, therefore this commit removes our assumption.
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.operations.buildpacks; import org.cloudfoundry.Nullable; import org.immutables.value.Value; /** * A Cloud Foundry Buildpack */ @Value.Immutable abstract class _Buildpack { /** * The enabled flag */ abstract Boolean getEnabled(); /** * The filename */ @Nullable abstract String getFilename(); /** * The id */ abstract String getId(); /** * The locked flag */ abstract Boolean getLocked(); /** * The name */ abstract String getName(); /** * The position */ abstract Integer getPosition(); }
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.operations.buildpacks; import org.immutables.value.Value; /** * A Cloud Foundry Buildpack */ @Value.Immutable abstract class _Buildpack { /** * The enabled flag */ abstract Boolean getEnabled(); /** * The filename */ abstract String getFilename(); /** * The id */ abstract String getId(); /** * The locked flag */ abstract Boolean getLocked(); /** * The name */ abstract String getName(); /** * The position */ abstract Integer getPosition(); }
Set install_requires: django >= 1.3, < 1.9
from setuptools import setup, find_packages from djcelery_ses import __version__ setup( name='django-celery-ses', version=__version__, description="django-celery-ses", author='tzangms', author_email='tzangms@streetvoice.com', url='http://github.com/StreetVoice/django-celery-ses', license='MIT', test_suite='runtests.runtests', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires = [ "django >= 1.3, < 1.9", "django-celery >= 3", ], classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", ], keywords='django,celery,mail', )
from setuptools import setup, find_packages from djcelery_ses import __version__ setup( name='django-celery-ses', version=__version__, description="django-celery-ses", author='tzangms', author_email='tzangms@streetvoice.com', url='http://github.com/StreetVoice/django-celery-ses', license='MIT', test_suite='runtests.runtests', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires = [ "django >= 1.3", "django-celery >= 3", ], classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", ], keywords='django,celery,mail', )
:bug: Fix invoking possibly null function in destroy
'use strict'; var InstallFlow = require('../elements/install-flow.js'); var Installation = class { constructor(variant, title) { this.flow = new InstallFlow(variant); this.func = null; this.onAccountCreated = null; this.onFlowSkipped = null; this.title = title || 'Welcome to Kite'; } accountCreated(func) { this.onAccountCreated = func; } flowSkipped(func) { this.onFlowSkipped = func; } destroy() { if (this.flow.accountCreated) { if (typeof (this.onAccountCreated) === 'function') { this.onAccountCreated(); } } else { if (typeof this.onFlowSkipped === 'function') { this.onFlowSkipped(); } } this.flow.destroy(); } getTitle() { return this.title; } get element() { return this.flow.element; } }; module.exports = Installation;
'use strict'; var InstallFlow = require('../elements/install-flow.js'); var Installation = class { constructor(variant, title) { this.flow = new InstallFlow(variant); this.func = null; this.onAccountCreated = null; this.onFlowSkipped = null; this.title = title || 'Welcome to Kite'; } accountCreated(func) { this.onAccountCreated = func; } flowSkipped(func) { this.onFlowSkipped = func; } destroy() { if (this.flow.accountCreated) { if (typeof (this.onAccountCreated) === 'function') { this.onAccountCreated(); } } else { if (typeof (this.onFlowSkipped()) === 'function') { this.onFlowSkipped(); } } this.flow.destroy(); } getTitle() { return this.title; } get element() { return this.flow.element; } }; module.exports = Installation;
Use classes to create constraints.
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
Use correct uri for AppolloClient
import React from 'react' import PropTypes from 'prop-types' import { Provider } from 'react-redux' import { BrowserRouter } from 'react-router-dom' import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; import BaseDataView from './BaseDataView' function getCookieValue(a) { var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)'); return b ? b.pop() : ''; } const client = new ApolloClient({ uri: process.env.REACT_APP_FLASK_API_URL + 'graphql', headers: { 'Authorization': 'Bearer ' + getCookieValue('token') } // options: { mode: 'no-cors' } }); window.apiUrl = process.env.REACT_APP_FLASK_API_URL; const Root = ({ store }) => ( <ApolloProvider client={client}> <Provider store={store}> <BrowserRouter> <BaseDataView /> </BrowserRouter> </Provider> </ApolloProvider> ) Root.propTypes = { store: PropTypes.object.isRequired } export default Root
import React from 'react' import PropTypes from 'prop-types' import { Provider } from 'react-redux' import { BrowserRouter } from 'react-router-dom' import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; import BaseDataView from './BaseDataView' function getCookieValue(a) { var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)'); return b ? b.pop() : ''; } const client = new ApolloClient({ uri: process.env.REACT_APP_GRAPHQL_API_URL + 'graphql', headers: { 'Authorization': 'Bearer ' + getCookieValue('token') } // options: { mode: 'no-cors' } }); window.apiUrl = process.env.REACT_APP_FLASK_API_URL; const Root = ({ store }) => ( <ApolloProvider client={client}> <Provider store={store}> <BrowserRouter> <BaseDataView /> </BrowserRouter> </Provider> </ApolloProvider> ) Root.propTypes = { store: PropTypes.object.isRequired } export default Root
Add error checking on invalid json
<?php namespace Busuu\IosReceiptsApi; use Exception; use GuzzleHttp\Client; class AppleClient { /** @var Client $client */ private $client; /** @var string */ private $password; public function __construct($password) { $this->client = new Client(); $this->password = $password; } /** * Fetch the receipt from apple * * @param $receiptData * @param $endpoint * * @return array * @throws Exception */ public function fetchReceipt($receiptData, $endpoint) { $data = [ 'password' => $this->password, 'receipt-data' => $receiptData ]; $response = $this->client->post($endpoint, [ 'body' => json_encode($data), 'timeout' => 10 ]); $jsonResponse = json_decode($response->getBody(), true); if (null !== $jsonResponse) { return $jsonResponse; } throw new Exception(sprintf('Invalid Response from Apple Server: %s', $response)); } }
<?php namespace Busuu\IosReceiptsApi; use GuzzleHttp\Client; class AppleClient { /** @var Client $client */ private $client; /** @var string */ private $password; public function __construct($password) { $this->client = new Client(); $this->password = $password; } /** * Fetch the receipt from apple * * @param $receiptData * @param $endpoint * @return array */ public function fetchReceipt($receiptData, $endpoint) { try { $data = [ 'password' => $this->password, 'receipt-data' => $receiptData ]; $response = $this->client->post($endpoint, ['body' => json_encode($data)]); return json_decode($response->getBody(), true); } catch (\Exception $e) { throw new \InvalidArgumentException( sprintf('Error in the communication with Apple - %s', $e->getMessage()) ); } } }
Add volume and volumeshift commands to help command
module.exports = { help: (message, config) => { const p = config.prefix; message.channel.send( `\`\`\`diff ++ MUSIC COMMANDS ++ ${p}play URL - Plays a song at a YouTube URL. ${p}stop - Interrupts the current song. ${p}queue - Says the current queue. ${p}pleasestop - Clears the queue and interrupts the current song. ${p}clearqueue - Clears the queue. ${p}volume - Displays the volume. ${p}volumeshift - Shifts the volume by a given percentage. ++ TESTING COMMANDS ++ ${p}ping - Says "pong." ${p}echo text - Repeats whatever text is given. ++ RANDOMNESS COMMANDS ++ ${p}coin - Says heads or tails. ${p}dice n - Says a random number between 1 and n. 6 is the default. ${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user. ++ MISC. commands ++ ${p}effify text - Effifies some text. \`\`\``); }, };
module.exports = { help: (message, config) => { const p = config.prefix; message.channel.send( `\`\`\`diff ++ MUSIC COMMANDS ++ ${p}play URL - Plays a song at a YouTube URL. ${p}stop - Interrupts the current song. ${p}queue - Says the current queue. ${p}pleasestop - Clears the queue and interrupts the current song. ${p}clearqueue - Clears the queue. ++ TESTING COMMANDS ++ ${p}ping - Says "pong." ${p}echo text - Repeats whatever text is given. ++ RANDOMNESS COMMANDS ++ ${p}coin - Says heads or tails. ${p}dice n - Says a random number between 1 and n. 6 is the default. ${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user. ++ MISC. commands ++ ${p}effify text - Effifies some text. \`\`\``); }, };
Fix linting error for unused session variable
import Promise from 'bluebird' import BaseWorker from '../../base' import rota from '../../rota.json' import redis from 'redis' Promise.promisifyAll(redis.RedisClient.prototype) export class AlertWorker extends BaseWorker { constructor (rsmq) { super('alert', rsmq) this.rsmq = rsmq this.redisClient = redis.createClient({ host: 'redis' }) } async process ({ body, meta }, next) { const { type, channel } = meta const attempts = await this.redisClient.getAsync(this.storageKey('attempt', meta)) if (attempts >= 3) { if (meta.index >= rota.length) return next() meta.index = meta.index + 1 } meta.person = rota[meta.index] await this.store(this.storageKey('alert', meta), { meta, body }) const rendered = await this.render(`${__dirname}/${type}.ejs`, { meta, body }) const message = JSON.stringify({ meta, body: JSON.parse(rendered) }) await this.rsmq.sendMessageAsync({ qname: channel, message, delay: 0 }) next() } } export default AlertWorker
import Promise from 'bluebird' import BaseWorker from '../../base' import rota from '../../rota.json' import redis from 'redis' Promise.promisifyAll(redis.RedisClient.prototype) export class AlertWorker extends BaseWorker { constructor (rsmq) { super('alert', rsmq) this.rsmq = rsmq this.redisClient = redis.createClient({ host: 'redis' }) } async process ({ body, meta }, next) { const { session, type, channel } = meta const attempts = await this.redisClient.getAsync(this.storageKey('attempt', meta)) if (attempts >= 3) { if (meta.index >= rota.length) return next() meta.index = meta.index + 1 } meta.person = rota[meta.index] await this.store(this.storageKey('alert', meta), { meta, body }) const rendered = await this.render(`${__dirname}/${type}.ejs`, { meta, body }) const message = JSON.stringify({ meta, body: JSON.parse(rendered) }) await this.rsmq.sendMessageAsync({ qname: channel, message, delay: 0 }) next() } } export default AlertWorker
Fix issue in trait conflict
<?php namespace Rougin\Wildfire\Traits; use Rougin\Describe\Describe; use Rougin\Describe\Driver\CodeIgniterDriver; /** * Describe Trait * * @package Wildfire * @author Rougin Royce Gutib <rougingutib@gmail.com> */ trait DescribeTrait { /** * Gets the Describe class based on the given database. * * @param CI_DB $database * @return \Rougin\Describe\Describe */ protected function getDescribe($database) { $config = [ 'default' => [ 'dbdriver' => $database->dbdriver, 'hostname' => $database->hostname, 'username' => $database->username, 'password' => $database->password, 'database' => $database->database ], ]; if (empty($config['default']['hostname'])) { $config['default']['hostname'] = $database->dsn; } $driver = new CodeIgniterDriver($config); return new Describe($driver); } }
<?php namespace Rougin\Wildfire\Traits; use Rougin\Describe\Describe; use Rougin\Describe\Driver\CodeIgniterDriver; /** * Describe Trait * * @package Wildfire * @author Rougin Royce Gutib <rougingutib@gmail.com> */ trait DescribeTrait { /** * @var \Rougin\Describe\Describe */ protected $describe; /** * Gets the Describe class based on the given database. * * @param CI_DB $database * @return \Rougin\Describe\Describe */ protected function getDescribe($database) { $config = [ 'default' => [ 'dbdriver' => $database->dbdriver, 'hostname' => $database->hostname, 'username' => $database->username, 'password' => $database->password, 'database' => $database->database ], ]; if (empty($config['default']['hostname'])) { $config['default']['hostname'] = $database->dsn; } $driver = new CodeIgniterDriver($config); return new Describe($driver); } }
Bump version due to PyPI submit error caused by server outage.
from setuptools import setup setup(name='pagerduty_events_api', version='0.2.1', description='Python wrapper for Pagerduty Events API', url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api', download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.2.1', author='Balazs Szerencsi', author_email='balazs.szerencsi@icloud.com', license='MIT', packages=['pagerduty_events_api'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'ddt'], install_requires=['requests'], keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
from setuptools import setup setup(name='pagerduty_events_api', version='0.2.0', description='Python wrapper for Pagerduty Events API', url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api', download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.2.0', author='Balazs Szerencsi', author_email='balazs.szerencsi@icloud.com', license='MIT', packages=['pagerduty_events_api'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'ddt'], install_requires=['requests'], keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
Write series summary in correct field.
package org.atlasapi.output.annotation; import org.atlasapi.content.Content; import org.atlasapi.content.Episode; import org.atlasapi.output.FieldWriter; import org.atlasapi.output.OutputContext; import org.atlasapi.output.writers.SeriesSummaryWriter; import java.io.IOException; import static com.google.common.base.Preconditions.checkNotNull; public class SeriesSummaryAnnotation extends OutputAnnotation<Content> { public static final String SERIES_FIELD = "series"; private final SeriesSummaryWriter summaryWriter; public SeriesSummaryAnnotation(SeriesSummaryWriter summaryWriter) { this.summaryWriter = checkNotNull(summaryWriter); } @Override public void write(Content entity, FieldWriter writer, OutputContext ctxt) throws IOException { if (entity instanceof Episode) { Episode episode = (Episode) entity; if(episode.getSeriesRef() == null) { writer.writeField(SERIES_FIELD, null); } else { writer.writeObject(summaryWriter, episode, ctxt); } } } }
package org.atlasapi.output.annotation; import org.atlasapi.content.Content; import org.atlasapi.content.Episode; import org.atlasapi.output.FieldWriter; import org.atlasapi.output.OutputContext; import org.atlasapi.output.writers.SeriesSummaryWriter; import java.io.IOException; import static com.google.common.base.Preconditions.checkNotNull; public class SeriesSummaryAnnotation extends OutputAnnotation<Content> { public static final String SERIES_FIELD = "series"; private final SeriesSummaryWriter summaryWriter; public SeriesSummaryAnnotation(SeriesSummaryWriter summaryWriter) { this.summaryWriter = checkNotNull(summaryWriter); } @Override public void write(Content entity, FieldWriter writer, OutputContext ctxt) throws IOException { if (entity instanceof Episode) { Episode episode = (Episode) entity; if(episode.getSeriesRef() == null) { writer.writeField(SERIES_FIELD, null); } else { summaryWriter.write(episode, writer, ctxt); } } } }
Change default height to better fit in a tonic view port 450 seems to work better than 500px.
// tonic-d3 - index.js // wrapper for d3 to make is easier to embed d3 charts in tonic // based off of https://tonicdev.com/tonic/d3-graph function wrap(d3Fn, options) { var d3Location = 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'; options = options || {}; options.width = options.width || 500; options.height = options.height || 450; var style = options.style || ''; return function(d3Args) { return '<center>' + '<style>' + style + '</style>' + '<svg width = ' + options.width + ' height = ' + options.height + ' ></svg>' + '<script src="' + d3Location + '"></script>' + '<script>(' + d3Fn.toString() + ')(' + JSON.stringify(d3Args)+ ', d3.select("svg"), d3)</script>' + '</center>'; }; } module.exports = wrap;
// tonic-d3 - index.js // wrapper for d3 to make is easier to embed d3 charts in tonic // based off of https://tonicdev.com/tonic/d3-graph function wrap(d3Fn, options) { var d3Location = 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'; options = options || {}; options.width = options.width || 500; options.height = options.height || 500; var style = options.style || ''; return function(d3Args) { return '<center>' + '<style>' + style + '</style>' + '<svg width = ' + options.width + ' height = ' + options.height + ' ></svg>' + '<script src="' + d3Location + '"></script>' + '<script>(' + d3Fn.toString() + ')(' + JSON.stringify(d3Args)+ ', d3.select("svg"), d3)</script>' + '</center>'; }; } module.exports = wrap;
Remove topicId function, define at creation
var amqp = require('amqplib'), Q = require('q'), utils = require('../utils'); /* Connect to message queue */ function connect(waitForConnection) { var deferred = Q.defer(); waitForConnection.then(function (connection) { var waitForChannel = connection.createConfirmChannel(); waitForChannel.then(function (ch) { channel = ch; var waitForExchange = channel.assertExchange('radiodan', 'topic'); waitForExchange.then(function () { deferred.resolve(channel); }, utils.failedPromiseHandler); }, utils.failedPromiseHandler); }, utils.failedPromiseHandler); return deferred.promise; } /* Send a command to Rabbit MQ */ function sendCommand(command, radioId, connectionPromise, done) { command = JSON.stringify(command); connectionPromise.then(function (channel) { channel.publish('radiodan', radioId, new Buffer(command), {}, done); console.log('published to %s', topicForId(radioId), command); }); } function create(id, queueHost) { queueHost = queueHost || 'localhost'; var connectionPromise = connect(amqp.connect('amqp://' + queueHost)), instance = {}; instance.id = 'radio.' + id + '.command'; instance.sendCommand = function(command, done) { return sendCommand(command, instance.id, connectionPromise, done); }; return instance; } module.exports = {create: create};
var amqp = require('amqplib'), Q = require('q'), utils = require('../utils'); /* Connect to message queue */ function connect(waitForConnection) { var deferred = Q.defer(); waitForConnection.then(function (connection) { var waitForChannel = connection.createConfirmChannel(); waitForChannel.then(function (ch) { channel = ch; var waitForExchange = channel.assertExchange('radiodan', 'topic'); waitForExchange.then(function () { deferred.resolve(channel); }, utils.failedPromiseHandler); }, utils.failedPromiseHandler); }, utils.failedPromiseHandler); return deferred.promise; } /* Send a command to Rabbit MQ */ function sendCommand(command, radioId, connectionPromise, done) { command = JSON.stringify(command); connectionPromise.then(function (channel) { channel.publish('radiodan', radioId, new Buffer(command), {}, done); console.log('published to %s', topicForId(radioId), command); }); } /* Return a topic key for a given radio id */ function topicForId(id) { return 'radio.' + id + '.command'; } function create(id, queueHost) { queueHost = queueHost || 'localhost'; var connectionPromise = connect(amqp.connect('amqp://' + queueHost)), instance = {}; instance.id = topicForId(id); instance.sendCommand = function(command, done) { return sendCommand(command, instance.id, connectionPromise, done); }; return instance; } module.exports = {create: create};
Add attachment support to email sender CLI
from typing import Tuple from opwen_email_server import azure_constants as constants from opwen_email_server import config from opwen_email_server.services.queue import AzureQueue from opwen_email_server.services.sendgrid import SendgridEmailSender QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_KEY, name=constants.QUEUE_EMAIL_SEND) EMAIL = SendgridEmailSender(key=config.EMAIL_SENDER_KEY) def send(email: dict) -> Tuple[str, int]: success = EMAIL.send_email(email) if not success: return 'error', 500 return 'sent', 200 if __name__ == '__main__': from argparse import ArgumentParser from argparse import FileType from base64 import b64encode from json import loads from os.path import basename from uuid import uuid4 parser = ArgumentParser() parser.add_argument('email') parser.add_argument('--attachment', type=FileType('rb')) args = parser.parse_args() email = loads(args.email) email.setdefault('_uid', str(uuid4())) if args.attachment: email.setdefault('attachments', []).append({ 'filename': basename(args.attachment.name), 'content': b64encode(args.attachment.read()).decode('ascii') }) args.attachment.close() send(email)
from typing import Tuple from opwen_email_server import azure_constants as constants from opwen_email_server import config from opwen_email_server.services.queue import AzureQueue from opwen_email_server.services.sendgrid import SendgridEmailSender QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_KEY, name=constants.QUEUE_EMAIL_SEND) EMAIL = SendgridEmailSender(key=config.EMAIL_SENDER_KEY) def send(email: dict) -> Tuple[str, int]: success = EMAIL.send_email(email) if not success: return 'error', 500 return 'sent', 200 if __name__ == '__main__': from argparse import ArgumentParser from json import loads from uuid import uuid4 parser = ArgumentParser() parser.add_argument('email') args = parser.parse_args() email = loads(args.email) email.setdefault('_uid', str(uuid4())) send(email)
Update bitso to newest api and add xrp coin
const Lang = imports.lang; const Local = imports.misc.extensionUtils.getCurrentExtension(); const BaseProvider = Local.imports.BaseProvider; const Api = new Lang.Class({ Name: 'Bitso.Api', Extends: BaseProvider.Api, apiName: "Bitso", currencies: ['MXN'], coins: ['BTC','mBTC','ETH', 'XRP'], /* quote https://bitso.com/api_info#rate-limits * * > Rate limits are are based on one minute windows. If you do more than 30 * > requests in a minute, you get locked out for one minute. */ interval: 30, attributes: { last: function (options) { const renderCurrency = BaseProvider.CurrencyRenderer(options); const renderChange = BaseProvider.ChangeRenderer(); return { text: (data) => renderCurrency(data.payload.last), change: (data) => renderChange(data.payload.last) }; } }, getLabel: function(options) { return "Bitso " + options.currency + "/" + options.coin; }, getUrl: function(options) { const coin = BaseProvider.baseCoin(options.coin); return "https://api.bitso.com/v3/ticker?book=" + coin.toLowerCase() + "_" + options.currency.toLowerCase(); } });
const Lang = imports.lang; const Local = imports.misc.extensionUtils.getCurrentExtension(); const BaseProvider = Local.imports.BaseProvider; const Api = new Lang.Class({ Name: 'Bitso.Api', Extends: BaseProvider.Api, apiName: "Bitso", currencies: ['MXN'], coins: ['BTC','mBTC','ETH'], /* quote https://bitso.com/api_info#rate-limits * * > Rate limits are are based on one minute windows. If you do more than 30 * > requests in a minute, you get locked out for one minute. */ interval: 30, attributes: { last: function (options) { const renderCurrency = BaseProvider.CurrencyRenderer(options); const renderChange = BaseProvider.ChangeRenderer(); return { text: (data) => renderCurrency(data.last), change: (data) => renderChange(data.last) }; } }, getLabel: function(options) { return "Bitso " + options.currency + "/" + options.coin; }, getUrl: function(options) { const coin = BaseProvider.baseCoin(options.coin); return "https://api.bitso.com/v2/ticker?book=" + coin + "_" + options.currency; } });
[bug-fix] Fix missing path to take redux action
import twreporterRedux from '@twreporter/redux' // lodash import get from 'lodash/get' const _ = { get } const { fetchAuthorCollectionIfNeeded, fetchAuthorDetails } = twreporterRedux.actions /** * loadData function is used for server side rendering. * It depends on redux store to load data and dispatch loaded results. * The loaded data is needed by `author/:authorId` page. * * @param {Object} match - `match` object of `react-router` * @param {Object} match.params - key/value pairs parsed from the URL corresponding to the dynamic segments of the path * @param {string} match.params.authorId - dynamic path segment * @param {Object} store - redux store instance * @returns {Promise} which resolves when loading finishes */ export default function loadData({ match, store }) { const authorId = _.get(match, 'params.authorId', '') return Promise.all([ store.dispatch(fetchAuthorCollectionIfNeeded(authorId)), store.dispatch(fetchAuthorDetails(authorId)) ]) .catch(error => { console.error(error) // eslint-disable-line no-console }) }
import twreporterRedux from '@twreporter/redux' // lodash import get from 'lodash/get' const _ = { get } const { fetchAuthorCollectionIfNeeded, fetchAuthorDetails } = twreporterRedux /** * loadData function is used for server side rendering. * It depends on redux store to load data and dispatch loaded results. * The loaded data is needed by `author/:authorId` page. * * @param {Object} match - `match` object of `react-router` * @param {Object} match.params - key/value pairs parsed from the URL corresponding to the dynamic segments of the path * @param {string} match.params.authorId - dynamic path segment * @param {Object} store - redux store instance * @returns {Promise} which resolves when loading finishes */ export default function loadData({ match, store }) { const authorId = _.get(match, 'params.authorId', '') return Promise.all([ store.dispatch(fetchAuthorCollectionIfNeeded(authorId)), store.dispatch(fetchAuthorDetails(authorId)) ]) .catch(error => { console.error(error) // eslint-disable-line no-console }) }
report.clipped_list: Add option to limit the number of lookups
import itertools def plural(s, number): return s.format(number=number, s="s" if number % 100 != 1 else "") def plural_w(s, number, capitalize=False): numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven", "nine", "ten") number_str = numbers[number] if number < len(numbers) else str(number) if capitalize: number_str = number_str.capitalize() return s.format(number=number_str, s="s" if number % 100 != 1 else "") def clip_string(s, limit=1000, sep=None): if len(s) < limit: return s s = s[:limit - 3] if sep is None: return s sep_pos = s.rfind(sep) if sep_pos == -1: return s return s[:sep_pos + len(sep)] + "..." def clipped_list(s, limit=1000, less_lookups=False): if less_lookups: s = ", ".join(itertools.islice(s, (limit + 2) // 3)) else: s = ", ".join(s) return clip_string(s, limit, ", ")
def plural(s, number): return s.format(number=number, s="s" if number % 100 != 1 else "") def plural_w(s, number, capitalize=False): numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven", "nine", "ten") number_str = numbers[number] if number < len(numbers) else str(number) if capitalize: number_str = number_str.capitalize() return s.format(number=number_str, s="s" if number % 100 != 1 else "") def clip_string(s, limit=1000, sep=None): if len(s) < limit: return s s = s[:limit - 3] if sep is None: return s sep_pos = s.rfind(sep) if sep_pos == -1: return s return s[:sep_pos + len(sep)] + "..." def clipped_list(s, limit=1000): return clip_string(", ".join(s), limit, ", ")
Add basic service-worker response and asset
<?php class CM_Http_Response_Resource_Javascript_ServiceWorker extends CM_Http_Response_Resource_Javascript_Abstract { public function __construct(CM_Http_Request_Abstract $request, CM_Service_Manager $serviceManager) { $path = $request->getPath(); $path = str_replace('-', '/', $path); $request->setPath($path); parent::__construct($request, $serviceManager); } protected function _process() { $debug = $this->getEnvironment()->isDebug(); $this->_setAsset(new CM_Asset_Javascript_ServiceWorker($this->getSite(), $debug)); } public static function match(CM_Http_Request_Abstract $request) { return 0 === stripos($request->getPath(), '/serviceworker-'); } }
<?php class CM_Http_Response_Resource_Javascript_ServiceWorker extends CM_Http_Response_Resource_Javascript_Abstract { public function __construct(CM_Http_Request_Abstract $request, CM_Service_Manager $serviceManager) { $path = $request->getPath(); $path = str_replace('-', '/', $path); $request->setPath($path); parent::__construct($request, $serviceManager); } protected function _process() { $debug = $this->getEnvironment()->isDebug(); $this->_setAsset(new CM_Asset_Javascript_ServiceWorker($this->getSite(), $debug)); } public static function match(CM_Http_Request_Abstract $request) { return 0 === stripos($request->getPath(), '/serviceworker-'); } }
Fix csv saving for arbitrary parameter sets
"""Various utility functions, mostly dealing with input/output""" import os import numpy as np def load_snapshots(directory_name, stack_coords=False): """Loads files by traversing a directory and reading in a filename sorted order""" data = [] for root, dirs, files in os.walk(directory_name): for file_name in sorted(files, key=lambda x: int(x.split(".")[-2])): #This needs fixing, but I'll leave it like this until we unify our formats if file_name.endswith("csv"): bodies = np.loadtxt(os.path.join(root, file_name), delimiter=",", unpack=stack_coords) data.append(bodies) return np.array(data) def save_snapshot(snapshot, file_name): np.savetxt(file_name, snapshot, delimiter=",") def construct_snapshot_name(directory, num): return os.path.join(directory, "nbody_snapshot." + str(num) + ".csv")
"""Various utility functions, mostly dealing with input/output""" import os import numpy as np def load_snapshots(directory_name, stack_coords=False): """Loads files by traversing a directory and reading in a filename sorted order""" data = [] for root, dirs, files in os.walk(directory_name): for file_name in sorted(files, key=lambda x: int(x.split(".")[-2])): #This needs fixing, but I'll leave it like this until we unify our formats if file_name.endswith("csv"): bodies = np.loadtxt(os.path.join(root, file_name), delimiter=",", skiprows=1, unpack=stack_coords) data.append(bodies) return np.array(data) def save_snapshot(snapshot, file_name): f = open(file_name, 'w') f.write("x,y,z\n") for i in range(snapshot.shape[0]): f.write("%e,%e,%e\n" % (snapshot[i, 0], snapshot[i, 1], snapshot[i, 2])) f.close() def construct_snapshot_name(directory, num): return os.path.join(directory, "nbody_snapshot." + str(num) + ".csv")
Use Eloquent ORM and Facades
<?php require_once __DIR__.'/../vendor/autoload.php'; Dotenv::load(__DIR__.'/../'); /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | Here we will load the environment and create the application instance | that serves as the central piece of this framework. We'll use this | application as an "IoC" container and router for this framework. | */ $app = new Laravel\Lumen\Application( realpath(__DIR__.'/../') ); $app->withFacades(); $app->withEloquent(); /* |-------------------------------------------------------------------------- | Register Container Bindings |-------------------------------------------------------------------------- | | Now we will register a few bindings in the service container. We will | register the exception handler and the console kernel. You may add | your own bindings here if you like or you can make another file. | */ $app->singleton( 'Illuminate\Contracts\Debug\ExceptionHandler', 'App\Exceptions\Handler' ); $app->singleton( 'Illuminate\Contracts\Console\Kernel', 'App\Console\Kernel' ); /* |-------------------------------------------------------------------------- | Load The Application Routes |-------------------------------------------------------------------------- | | Next we will include the routes file so that they can all be added to | the application. This will provide all of the URLs the application | can respond to, as well as the controllers that may handle them. | */ require __DIR__.'/../app/Http/routes.php'; return $app;
<?php require_once __DIR__.'/../vendor/autoload.php'; Dotenv::load(__DIR__.'/../'); /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | Here we will load the environment and create the application instance | that serves as the central piece of this framework. We'll use this | application as an "IoC" container and router for this framework. | */ $app = new Laravel\Lumen\Application( realpath(__DIR__.'/../') ); // $app->withFacades(); // $app->withEloquent(); /* |-------------------------------------------------------------------------- | Register Container Bindings |-------------------------------------------------------------------------- | | Now we will register a few bindings in the service container. We will | register the exception handler and the console kernel. You may add | your own bindings here if you like or you can make another file. | */ $app->singleton( 'Illuminate\Contracts\Debug\ExceptionHandler', 'App\Exceptions\Handler' ); $app->singleton( 'Illuminate\Contracts\Console\Kernel', 'App\Console\Kernel' ); /* |-------------------------------------------------------------------------- | Load The Application Routes |-------------------------------------------------------------------------- | | Next we will include the routes file so that they can all be added to | the application. This will provide all of the URLs the application | can respond to, as well as the controllers that may handle them. | */ require __DIR__.'/../app/Http/routes.php'; return $app;
Trim whitespace from either side of name / email.
<?php add_action( 'wp_ajax_form_to_disk', 'form_to_disk' ); add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' ); $f2d_option = get_option( 'f2d_options', '' ); function form_to_disk() { global $f2d_option; date_default_timezone_set('America/Los_Angeles'); if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) { $protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] ); $form_data = trim( $_POST[ 'firstName' ] ) . ','; $form_data .= trim( $_POST[ 'lastName' ] ) . ','; $form_data .= trim( $_POST[ 'email' ] ); $entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' ) or die( 'Unable to process that request' ); $txt = date( 'Ymd' ); $txt .= ','; $txt .= $form_data; fwrite( $entries, $txt . PHP_EOL ); fclose( $entries ); die(); } }
<?php add_action( 'wp_ajax_form_to_disk', 'form_to_disk' ); add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' ); $f2d_option = get_option( 'f2d_options', '' ); function form_to_disk() { global $f2d_option; date_default_timezone_set('America/Los_Angeles'); if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) { $protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] ); $form_data = $_POST[ 'firstName' ] . ','; $form_data .= $_POST[ 'lastName' ] . ','; $form_data .= $_POST[ 'email' ]; $entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' ) or die( 'Unable to process that request' ); $txt = date( 'Ymd' ); $txt .= ','; $txt .= $form_data; fwrite( $entries, $txt . PHP_EOL ); fclose( $entries ); die(); } }
Add source map for SASS
'use strict' import { defaults } from 'lodash' import { extractStyles, styleLoader } from './helpers' export default function ({ isClient }) { let babelOptions = JSON.stringify(defaults(this.options.build.babel, { presets: ['vue-app'], babelrc: false, cacheDirectory: !!this.dev })) // https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations let config = { postcss: this.options.build.postcss, loaders: { 'js': 'babel-loader?' + babelOptions, 'css': styleLoader.call(this, 'css'), 'less': styleLoader.call(this, 'less', 'less-loader'), 'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&?sourceMap'), 'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'), 'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'), 'styl': styleLoader.call(this, 'stylus', 'stylus-loader') }, preserveWhitespace: false, extractCSS: extractStyles.call(this) } // Return the config return config }
'use strict' import { defaults } from 'lodash' import { extractStyles, styleLoader } from './helpers' export default function ({ isClient }) { let babelOptions = JSON.stringify(defaults(this.options.build.babel, { presets: ['vue-app'], babelrc: false, cacheDirectory: !!this.dev })) // https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations let config = { postcss: this.options.build.postcss, loaders: { 'js': 'babel-loader?' + babelOptions, 'css': styleLoader.call(this, 'css'), 'less': styleLoader.call(this, 'less', 'less-loader'), 'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax'), 'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'), 'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'), 'styl': styleLoader.call(this, 'stylus', 'stylus-loader') }, preserveWhitespace: false, extractCSS: extractStyles.call(this) } // Return the config return config }
Fix one of the Linking code examples Close #1996
import { Linking, StyleSheet, Text } from 'react-native'; import React, { PureComponent } from 'react'; import Example from '../../shared/example'; const url = 'https://mathiasbynens.github.io/rel-noopener/malicious.html'; export default class LinkingPage extends PureComponent { handlePress() { Linking.canOpenURL(url).then((supported) => { return Linking.openURL(url); }); } render() { return ( <Example title="Linking"> <Text onPress={this.handlePress} style={styles.text}> Linking.openURL </Text> <Text accessibilityRole="link" href="https://mathiasbynens.github.io/rel-noopener/malicious.html" hrefAttrs={{ target: '_blank' }} style={styles.text} > target="_blank" </Text> </Example> ); } } const styles = StyleSheet.create({ text: { borderRadius: 5, borderStyle: 'solid', borderWidth: 1, marginVertical: 10, padding: 10 } });
import { Linking, StyleSheet, Text } from 'react-native'; import React, { PureComponent } from 'react'; import Example from '../../shared/example'; const url = 'https://mathiasbynens.github.io/rel-noopener/malicious.html'; export default class LinkingPage extends PureComponent { handlePress() { Linking.canOpenURL(url).then((supported) => { return Linking.openURL(url); }); } render() { return ( <Example title="Linking"> <Text onPress={this.handlePress} style={styles.text}> Linking.openURL </Text> <Text accessibilityRole="link" href="https://mathiasbynens.github.io/rel-noopener/malicious.html" style={styles.text} target="_blank" > target="_blank" </Text> </Example> ); } } const styles = StyleSheet.create({ text: { borderRadius: 5, borderStyle: 'solid', borderWidth: 1, marginVertical: 10, padding: 10 } });
Use separate instances of analysis and trading for each thread
#!/usr/bin/python # -*- coding: utf-8 -*- from google.cloud import error_reporting from google.cloud import logging from analysis import Analysis from trading import Trading from twitter import Twitter # Analyzes Trump tweets, makes stock trades, and sends tweet alerts. def twitter_callback(text, link): # Initialize these here to create separate httplib2 instances per thread. analysis = Analysis() trading = Trading() companies = analysis.find_companies(text) logger.log_text("Using companies: %s" % companies, severity="DEBUG") if companies: trading.make_trades(companies) twitter.tweet(companies, link) if __name__ == "__main__": logger = logging.Client(use_gax=False).logger("main") error_client = error_reporting.Client() # Restart in a loop if there are any errors so we stay up. while True: logger.log_text("Starting new session.", severity="INFO") twitter = Twitter(twitter_callback) try: twitter.start_streaming() except Exception as exception: error_client.report_exception() logger.log_text("Exception on main thread: %s" % exception, severity="ERROR") finally: logger.log_text("Ending session.", severity="INFO")
#!/usr/bin/python # -*- coding: utf-8 -*- from google.cloud import error_reporting from google.cloud import logging from analysis import Analysis from trading import Trading from twitter import Twitter # Analyzes Trump tweets, makes stock trades, and sends tweet alerts. def twitter_callback(text, link): companies = analysis.find_companies(text) logger.log_text("Using companies: %s" % companies, severity="DEBUG") if companies: trading.make_trades(companies) twitter.tweet(companies, link) if __name__ == "__main__": logger = logging.Client(use_gax=False).logger("main") error_client = error_reporting.Client() # Restart in a loop if there are any errors so we stay up. while True: logger.log_text("Starting new session.", severity="INFO") analysis = Analysis() trading = Trading() twitter = Twitter(twitter_callback) try: twitter.start_streaming() except Exception as exception: error_client.report_exception() logger.log_text("Exception on main thread: %s" % exception, severity="ERROR") finally: logger.log_text("Ending session.", severity="INFO")
Allow passing handler in to the operation
"use strict"; const Joi = require('joi'); const securitySchema = require('./securitySchema'); const parameterSchema = require('./parameterSchema'); module.exports = Joi.object({ 'tags': Joi.array() .items(Joi.string().required()), 'summary': Joi.string() .max(120) .required(), 'description': Joi.string() .required(), 'consumes': Joi.array() .items(Joi.string().required()), 'produces': Joi.array() .items(Joi.string().required()), 'parameters': Joi.array() .items(parameterSchema), 'schemes': Joi.array() .items(Joi.string() .allow('http', 'https', 'ws', 'wss')), 'deprecated': Joi.boolean(), 'security': securitySchema, 'handler': Joi.func() });
"use strict"; const Joi = require('joi'); const securitySchema = require('./securitySchema'); const parameterSchema = require('./parameterSchema'); module.exports = Joi.object({ 'tags': Joi.array() .items(Joi.string().required()), 'summary': Joi.string() .max(120) .required(), 'description': Joi.string() .required(), 'consumes': Joi.array() .items(Joi.string().required()), 'produces': Joi.array() .items(Joi.string().required()), 'parameters': Joi.array() .items(parameterSchema), 'schemes': Joi.array() .items(Joi.string() .allow('http', 'https', 'ws', 'wss')), 'deprecated': Joi.boolean(), 'security': securitySchema });
Set VM policy for Strict Mode
package com.wkovacs64.mtorch; import android.app.Application; import android.os.Build; import android.os.StrictMode; import timber.log.Timber; public final class CustomApplication extends Application { @Override public void onCreate() { if (BuildConfig.DEBUG) { // Initialize Timber logging library Timber.plant(new Timber.DebugTree()); // Enable StrictMode for debug builds enabledStrictMode(); } super.onCreate(); } private void enabledStrictMode() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .penaltyDialog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); } } }
package com.wkovacs64.mtorch; import android.app.Application; import android.os.Build; import android.os.StrictMode; import timber.log.Timber; public final class CustomApplication extends Application { @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { // Initialize Timber logging library Timber.plant(new Timber.DebugTree()); // Enable StrictMode for debug builds enabledStrictMode(); } } private void enabledStrictMode() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .penaltyDialog() .build()); } } }
Remove request tokens from service responses
const { authenticate } = require('@feathersjs/authentication'); const { discard } = require('feathers-hooks-common'); const globalHooks = require('../../../hooks'); const { canRead } = require('../utils/filePermissionHelper'); const restrictToCurrentUser = (hook) => { const { params: { account: { userId } }, result: { data: files } } = hook; const permissionPromises = files.map((f) => canRead(userId, f) .then(() => f) .catch(() => undefined)); return Promise.all(permissionPromises) .then((allowedFiles) => { hook.result.data = allowedFiles; return hook; }); }; exports.before = { all: [authenticate('jwt')], find: [globalHooks.hasPermission('FILESTORAGE_VIEW')], get: [globalHooks.hasPermission('FILESTORAGE_VIEW')], create: [globalHooks.hasPermission('FILESTORAGE_CREATE')], update: [globalHooks.hasPermission('FILESTORAGE_EDIT')], patch: [globalHooks.hasPermission('FILESTORAGE_EDIT')], remove: [globalHooks.hasPermission('FILESTORAGE_REMOVE')], }; exports.after = { all: [discard('securityCheck.requestToken', 'thumbnailRequestToken')], find: [restrictToCurrentUser], get: [], create: [], update: [], patch: [], remove: [], };
const { authenticate } = require('@feathersjs/authentication'); const globalHooks = require('../../../hooks'); const { canRead } = require('../utils/filePermissionHelper'); const restrictToCurrentUser = (hook) => { const { params: { account: { userId } }, result: { data: files } } = hook; const permissionPromises = files.map((f) => canRead(userId, f) .then(() => f) .catch(() => undefined)); return Promise.all(permissionPromises) .then((allowedFiles) => { hook.result.data = allowedFiles; return hook; }); }; exports.before = { all: [authenticate('jwt')], find: [globalHooks.hasPermission('FILESTORAGE_VIEW')], get: [globalHooks.hasPermission('FILESTORAGE_VIEW')], create: [globalHooks.hasPermission('FILESTORAGE_CREATE')], update: [globalHooks.hasPermission('FILESTORAGE_EDIT')], patch: [globalHooks.hasPermission('FILESTORAGE_EDIT')], remove: [globalHooks.hasPermission('FILESTORAGE_REMOVE')], }; exports.after = { all: [], find: [restrictToCurrentUser], get: [], create: [], update: [], patch: [], remove: [], };
Use the get_secret function to grab the database configuration. git-svn-id: d73fdb991549f9d1a0affa567d55bb0fdbd453f3@8412 f04a3889-0f81-4131-97fb-bc517d1f583d
from .base import * # Debug Settings DEBUG = False TEMPLATE_DEBUG = False # Media Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Staticfile Setttings STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_final') # TMP Dir for Choropleth Screenshots IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp') # Enable Pipeline PIPELINE_ENABLED = True # Database Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': get_secret('DB_NAME'), 'USER': get_secret('DB_USER'), 'PASSWORD': get_secret('DB_PASSWORD'), 'HOST': get_secret('DB_HOST'), 'PORT': get_secret('DB_PORT') } } # Email Settings EMAIL_HOST = '' EMAIL_PORT = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = '' EMAIL_USE_SSL = ''
from .base import * # Debug Settings DEBUG = False TEMPLATE_DEBUG = False # Media Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Staticfile Setttings STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_final') # TMP Dir for Choropleth Screenshots IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp') # Enable Pipeline PIPELINE_ENABLED = True # Database Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Email Settings EMAIL_HOST = '' EMAIL_PORT = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = '' EMAIL_USE_SSL = ''
Add consumerKey and consumerSecret to prompt.
var _ = require('lodash'); var optimist = require('optimist'); var prompt = require('prompt'); var schema = { properties: { consumerKey: { required: true }, consumerSecret: { required: true }, friendId: { required: true } } }; prompt.override = optimist.argv; prompt.start(); prompt.get(schema, function(err, input) { var file = require(__dirname + '\\friend.json'); var some = _.first(file.results, 20); _.each(some, function(tx) { console.log('----------------------------------') console.log('Who Paid: ' + tx.sender.name); console.log('Who Owes: ' + tx.receiver.name); console.log('Amount: ' + tx.amount); console.log('Description: ' + tx.message); console.log('Date: ' + tx.happenedAt.iso.substring(0, tx.happenedAt.iso.indexOf('T'))); console.log(tx.receiver.name + ' owes ' + tx.sender.name + ' $' + tx.amount + ' for ' + tx.message + ' on ' + tx.happenedAt.iso.substring(0, tx.happenedAt.iso.indexOf('T'))); }); });
var _ = require('lodash'); var optimist = require('optimist'); var prompt = require('prompt'); var schema = { properties: { file: { required: true, default: 'file.json' }, friendId: { required: true } } }; prompt.override = optimist.argv; prompt.start(); prompt.get(schema, function(err, input) { var file = require(__dirname + '\\friend.json'); var some = _.first(file.results, 20); _.each(some, function(tx) { console.log('----------------------------------') console.log('Who Paid: ' + tx.sender.name); console.log('Who Owes: ' + tx.receiver.name); console.log('Amount: ' + tx.amount); console.log('Description: ' + tx.message); console.log('Date: ' + tx.happenedAt.iso.substring(0, tx.happenedAt.iso.indexOf('T'))); console.log(tx.receiver.name + ' owes ' + tx.sender.name + ' $' + tx.amount + ' for ' + tx.message + ' on ' + tx.happenedAt.iso.substring(0, tx.happenedAt.iso.indexOf('T'))); }); });
Move from dkvolume to go-plugins-helpers/volume
package main import ( "flag" "fmt" "os" "path/filepath" "strings" "github.com/docker/go-plugins-helpers/volume" ) const glusterfsId = "_glusterfs" var ( defaultDir = filepath.Join(volume.DefaultDockerRootDirectory, glusterfsId) serversList = flag.String("servers", "", "List of glusterfs servers") restAddress = flag.String("rest", "", "URL to glusterfsrest api") gfsBase = flag.String("gfs-base", "/mnt/gfs", "Base directory where volumes are created in the cluster") root = flag.String("root", defaultDir, "GlusterFS volumes root directory") ) func main() { var Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() if len(*serversList) == 0 { Usage() os.Exit(1) } servers := strings.Split(*serversList, ":") d := newGlusterfsDriver(*root, *restAddress, *gfsBase, servers) h := volume.NewHandler(d) fmt.Println(h.ServeUnix("root", "glusterfs")) }
package main import ( "flag" "fmt" "os" "path/filepath" "strings" "github.com/calavera/dkvolume" ) const glusterfsId = "_glusterfs" var ( defaultDir = filepath.Join(dkvolume.DefaultDockerRootDirectory, glusterfsId) serversList = flag.String("servers", "", "List of glusterfs servers") restAddress = flag.String("rest", "", "URL to glusterfsrest api") gfsBase = flag.String("gfs-base", "/mnt/gfs", "Base directory where volumes are created in the cluster") root = flag.String("root", defaultDir, "GlusterFS volumes root directory") ) func main() { var Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() if len(*serversList) == 0 { Usage() os.Exit(1) } servers := strings.Split(*serversList, ":") d := newGlusterfsDriver(*root, *restAddress, *gfsBase, servers) h := dkvolume.NewHandler(d) fmt.Println(h.ServeUnix("root", "glusterfs")) }
Handle encoding better across python versions
#!/usr/bin/env python from codecs import open from setuptools import setup import maxmindupdater with open('README.rst', encoding='utf8') as readme_file: readme = readme_file.read() setup( name=maxmindupdater.__name__, version=maxmindupdater.__version__, description=maxmindupdater.__doc__, long_description=readme, author='Yola', author_email='engineers@yola.com', license='MIT (Expat)', url=maxmindupdater.__url__, packages=['maxmindupdater'], test_suite='nose.collector', entry_points={ 'console_scripts': ['maxmind-updater=maxmindupdater.__main__:main'], }, install_requires=[ 'requests >= 2.0.0, < 3.0.0', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], )
#!/usr/bin/env python from setuptools import setup import maxmindupdater with open('README.rst') as readme_file: readme = readme_file.read().decode('utf8') setup( name=maxmindupdater.__name__, version=maxmindupdater.__version__, description=maxmindupdater.__doc__, long_description=readme, author='Yola', author_email='engineers@yola.com', license='MIT (Expat)', url=maxmindupdater.__url__, packages=['maxmindupdater'], test_suite='nose.collector', entry_points={ 'console_scripts': ['maxmind-updater=maxmindupdater.__main__:main'], }, install_requires=[ 'requests >= 2.0.0, < 3.0.0', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], )
Add cache resource provider to toolbox
<?php namespace Ob_Ivan\DropboxProxy; use Ob_Ivan\DropboxProxy\ResourceProvider\CacheResourceProvider; use Ob_Ivan\DropboxProxy\ResourceProvider\DropboxResourceProvider; use Ob_Ivan\ResourceContainer\ResourceContainer; class ToolboxFactory { /** * TODO: Replace $storagePath argument with a substitution array. * * @param string $configPath * @param string $storagePath null * @return ResourceContainer **/ public static function getToolbox($configPath, $storagePath = null) { $config = json_decode(file_get_contents($configPath), true); $container = new ResourceContainer(); $container->importProvider(new CacheResourceProvider()); $container->importProvider(new DropboxResourceProvider()); $container->importValues($config); if ($storagePath) { $container['filesystem.storage'] = $storagePath; } return $container; } }
<?php namespace Ob_Ivan\DropboxProxy; use Ob_Ivan\DropboxProxy\ResourceProvider\DropboxResourceProvider; use Ob_Ivan\ResourceContainer\ResourceContainer; class ToolboxFactory { /** * TODO: Replace $storagePath argument with a substitution array. * * @param string $configPath * @param string $storagePath null * @return ResourceContainer **/ public static function getToolbox($configPath, $storagePath = null) { $config = json_decode(file_get_contents($configPath), true); $container = new ResourceContainer(); $container->importProvider(new DropboxResourceProvider()); $container->importValues($config); if ($storagePath) { $container['filesystem.storage'] = $storagePath; } return $container; } }
Include recommended on eslint config
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parserOptions: { parser: 'babel-eslint' }, env: { browser: true, }, extends: [ // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules. 'plugin:vue/essential', // https://github.com/standard/standard/blob/master/docs/RULES-en.md 'standard' ], // required to lint *.vue files plugins: [ 'eslint:recommended', 'vue' ], // add your custom rules here rules: { // allow async-await 'generator-star-spacing': 'off', // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off' } }
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parserOptions: { parser: 'babel-eslint' }, env: { browser: true, }, extends: [ // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules. 'plugin:vue/essential', // https://github.com/standard/standard/blob/master/docs/RULES-en.md 'standard' ], // required to lint *.vue files plugins: [ 'vue' ], // add your custom rules here rules: { // allow async-await 'generator-star-spacing': 'off', // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off' } }
Test that an empty name field doesn't raise errors
from django.test import TestCase from store.forms import ReviewForm from store.models import Review from .factories import * class ReviewFormTest(TestCase): def test_form_validation_for_blank_items(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': '', 'product':p1.id}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['text'],["Please fill in the review"]) self.assertEqual(form.errors['rating'],["Please leave a rating"]) def test_form_save_handles_saving_product_reviews(self): prod = ProductFactory.create() form = ReviewForm( data={'name':'Kevin', 'text': 'Review', 'rating': 3, 'product':prod.id}) new_review = form.save() self.assertEqual(new_review, Review.objects.first()) self.assertEqual(new_review.name, 'Kevin') self.assertEqual(new_review.product, prod) def test_empty_name_field_doesnt_raise_errors(self): prod = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': 'Review', 'rating': 3, 'product':prod.id}) self.assertTrue(form.is_valid())
from django.test import TestCase from store.forms import ReviewForm from store.models import Review from .factories import * class ReviewFormTest(TestCase): def test_form_validation_for_blank_items(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': '', 'product':p1.id}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['text'],["Please fill in the review"]) self.assertEqual(form.errors['rating'],["Please leave a rating"]) def test_form_save_handles_saving_to_a_list(self): prod = ProductFactory.create() form = ReviewForm( data={'name':'Kevin', 'text': 'Review', 'rating': 3, 'product':prod.id}) new_review = form.save() self.assertEqual(new_review, Review.objects.first()) self.assertEqual(new_review.name, 'Kevin') self.assertEqual(new_review.product, prod)
Fix [] on Travis Building
<?php /** * This file ensure * a maximum compatibility * for user that do not * make use of composer */ use Phpfastcache\core\InstanceManager; if(!defined('PHPFASTCACHE_LOADED_VIA_COMPOSER')) { require_once 'required_files.php'; } /** * phpFastCache() Full alias * @param string $storage * @param array $config * @return mixed */ if(!function_exists("phpFastCache")) { function phpFastCache($storage = 'auto', $config = array()) { return InstanceManager::getInstance($storage, $config); } } /** * __c() Short alias * @param string $storage * @param array $config * @return mixed */ if(!function_exists("__c")) { function __c ( $storage = 'auto' , $config = array() ) { return InstanceManager::getInstance ( $storage , $config ); } }
<?php /** * This file ensure * a maximum compatibility * for user that do not * make use of composer */ use Phpfastcache\core\InstanceManager; if(!defined('PHPFASTCACHE_LOADED_VIA_COMPOSER')) { require_once 'required_files.php'; } /** * phpFastCache() Full alias * @param string $storage * @param array $config * @return mixed */ if(!function_exists("phpFastCache")) { function phpFastCache($storage = 'auto', $config = []) { trigger_error(__FUNCTION__ . '() is deprecated use instanceManager::getInstance() instead.', E_USER_DEPRECATED); return InstanceManager::getInstance($storage, $config); } } /** * __c() Short alias * @param string $storage * @param array $config * @return mixed */ if(!function_exists("__c")) { function __c ( $storage = 'auto' , $config = [ ] ) { trigger_error ( __FUNCTION__ . '() is deprecated use instanceManager::getInstance() instead.' , E_USER_DEPRECATED ); return InstanceManager::getInstance ( $storage , $config ); } }
Check for autoloader file before trying to include it
<?php /** * A (quick and dirty) scanner to scanning all (linked) pages of an https-enabled website for Mixed Content * @author Bramus! <bramus@bram.us> * @version 1.0 * * NO NEED TO TOUCH THIS FILE ... PLEASE REFER TO THE README.MD FILE ;-) */ // Error settings error_reporting(E_ERROR); ini_set('display_errors', 'on'); // Check if we're at the CLI if (php_sapi_name() != 'cli') exit('Please run this file on the command line. E.g. `php bin/scanner.php $url`' . PHP_EOL); // Require autoloader if (!file_exists(__DIR__ . '/../vendor/autoload.php')) exit('Make sure you run `composer install` first, before running this scanner'); require __DIR__ . '/../vendor/autoload.php'; // Check arguments (simple) if ($argc != 2 || !parse_url($argv[1])) exit('Please use a valid URL you wish to scan as a parameter to this script. Eg. `php bin/scanner.php https://www.bram.us/`' . PHP_EOL); // Get ignorepatterns $ignorePatterns = include __DIR__ . '/../conf/ignorePatterns.php'; // Go for it! $scanner = new \Bramus\MCS\Scanner($argv[1], (array) $ignorePatterns); $scanner->scan();
<?php /** * A (quick and dirty) scanner to scanning all (linked) pages of an https-enabled website for Mixed Content * @author Bramus! <bramus@bram.us> * @version 1.0 * * NO NEED TO TOUCH THIS FILE ... PLEASE REFER TO THE README.MD FILE ;-) */ // Error settings error_reporting(E_ERROR); ini_set('display_errors', 'on'); // Check if we're at the CLI if (php_sapi_name() != 'cli') exit('Please run this file on the command line. E.g. `php bin/scanner.php $url`' . PHP_EOL); // Check arguments (simple) if ($argc != 2 || !parse_url($argv[1])) exit('Please use a valid URL you wish to scan as a parameter to this script. Eg. `php bin/scanner.php https://www.bram.us/`' . PHP_EOL); // Require needed Scanner class require __DIR__ . '/../vendor/autoload.php'; // Get ignorepatterns $ignorePatterns = include __DIR__ . '/../conf/ignorePatterns.php'; // Go for it! $scanner = new \Bramus\MCS\Scanner($argv[1], (array) $ignorePatterns); $scanner->scan();
Use staticfiles instead of staticmedia
from django import forms from django.utils import simplejson as json from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( settings.STATICFILES_URL + 'js/jquery.js', settings.STATICFILES_URL + 'js/jquery.tmpl.js', settings.STATICFILES_URL + 'js/json-table.js', settings.STATICFILES_URL + 'js/json-table-templates.js', )
from django import forms from django.utils import simplejson as json import staticmedia class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( staticmedia.url('js/jquery.js'), staticmedia.url('js/jquery.tmpl.js'), staticmedia.url('js/json-table.js'), staticmedia.url('js/json-table-templates.js'), )
Fix return type of TO_DAYS function. Should be int.
<?php namespace Vectorface\MySQLite\MySQL; /** * Provides Date and Time MySQL compatibility functions for SQLite. * * http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html */ trait DateTime { /** * NOW - Return the current date and time * * @return string The current timestamp, in MySQL's date format. */ public static function mysql_now() { return date("Y-m-d H:i:s"); } /** * TO_DAYS - Return the date argument converted to days * * @param string $date A date to be converted to days. * @return int The date converted to a number of days since year 0. */ public static function mysql_to_days($date) { return 719527 + intval(ceil(strtotime($date) / (60 * 60 * 24))); } /** * UNIX_TIMESTAMP - Return a UNIX timestamp * * @param string $date The date to be converted to a unix timestamp. Defaults to the current date/time. * @return int The number of seconds since the unix epoch. */ public static function mysql_unix_timestamp($date = null) { if (!isset($date)) { return time(); } return strtotime($date); } }
<?php namespace Vectorface\MySQLite\MySQL; /** * Provides Date and Time MySQL compatibility functions for SQLite. * * http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html */ trait DateTime { /** * NOW - Return the current date and time * * @return string The current timestamp, in MySQL's date format. */ public static function mysql_now() { return date("Y-m-d H:i:s"); } /** * TO_DAYS - Return the date argument converted to days * * @param string $date A date to be converted to days. * @return int The date converted to a number of days since year 0. */ public static function mysql_to_days($date) { return 719527 + ceil(strtotime($date) / (60 * 60 * 24)); } /** * UNIX_TIMESTAMP - Return a UNIX timestamp * * @param string $date The date to be converted to a unix timestamp. Defaults to the current date/time. * @return int The number of seconds since the unix epoch. */ public static function mysql_unix_timestamp($date = null) { if (!isset($date)) { return time(); } return strtotime($date); } }
Use a default game status rather than null (fixes a potential error when loading starts).
import Immutable, { Record } from 'immutable' import { PSI_GAME_LAUNCH, PSI_GAME_STATUS, } from '../actions' export const GameStatus = new Record({ state: 'unknown', extra: null, }) export const GameClient = new Record({ gameId: null, status: new GameStatus(), }) const handlers = { [PSI_GAME_LAUNCH](state, action) { if (action.error) { return new GameClient() } return new GameClient({ gameId: action.payload }) }, [PSI_GAME_STATUS](state, action) { return state.set('status', new GameStatus({ state: action.payload.state, extra: action.payload.extra ? Immutable.fromJS(action.payload.extra) : null, })) }, } export default function gameClientReducer(state = new GameClient(), action) { return handlers.hasOwnProperty(action.type) ? handlers[action.type](state, action) : state }
import Immutable, { Record } from 'immutable' import { PSI_GAME_LAUNCH, PSI_GAME_STATUS, } from '../actions' export const GameStatus = new Record({ state: 'unknown', extra: null, }) export const GameClient = new Record({ gameId: null, status: null, }) const handlers = { [PSI_GAME_LAUNCH](state, action) { if (action.error) { return new GameClient() } return new GameClient({ gameId: action.payload }) }, [PSI_GAME_STATUS](state, action) { return state.set('status', new GameStatus({ state: action.payload.state, extra: action.payload.extra ? Immutable.fromJS(action.payload.extra) : null, })) }, } export default function gameClientReducer(state = new GameClient(), action) { return handlers.hasOwnProperty(action.type) ? handlers[action.type](state, action) : state }
firefox: Disable a few unused features
user_pref("accessibility.typeaheadfind.flashBar", 0); user_pref("accessibility.typeaheadfind.prefillwithselection", true); user_pref("browser.backspace_action", 2); user_pref("browser.bookmarks.restore_default_bookmarks", false); user_pref("browser.newtab.url", "about:blank"); user_pref("browser.readinglist.enabled", false); user_pref("browser.search.suggest.enabled", false); user_pref("browser.selfsupport.url", ""); user_pref("browser.showQuitWarning", true); user_pref("browser.startup.homepage", "about:blank"); user_pref("browser.tabs.animate", false); user_pref("browser.tabs.closeWindowWithLastTab", false); user_pref("browser.tabs.warnOnClose", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("loop.enabled", false); user_pref("network.cookie.cookieBehavior", 3); user_pref("network.cookie.lifetimePolicy", 2); user_pref("network.http.referer.spoofSource", true); user_pref("network.http.referer.trimmingPolicy", 2); user_pref("network.http.referer.XOriginPolicy", 2); user_pref("readinglist.scheduler.enabled", false); user_pref("toolkit.telemetry.enabled", false);
user_pref("accessibility.typeaheadfind.flashBar", 0); user_pref("accessibility.typeaheadfind.prefillwithselection", true); user_pref("browser.backspace_action", 2); user_pref("browser.bookmarks.restore_default_bookmarks", false); user_pref("browser.newtab.url", "about:blank"); user_pref("browser.search.suggest.enabled", false); user_pref("browser.selfsupport.url", ""); user_pref("browser.showQuitWarning", true); user_pref("browser.startup.homepage", "about:blank"); user_pref("browser.tabs.animate", false); user_pref("browser.tabs.closeWindowWithLastTab", false); user_pref("browser.tabs.warnOnClose", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("network.cookie.cookieBehavior", 3); user_pref("network.cookie.lifetimePolicy", 2); user_pref("network.http.referer.spoofSource", true); user_pref("network.http.referer.trimmingPolicy", 2); user_pref("network.http.referer.XOriginPolicy", 2); user_pref("toolkit.telemetry.enabled", false);
Remove reference to ampClientIDOptIn in setupAnalytics utility.
/** * Internal dependencies */ import { wpApiFetch } from './wp-api-fetch'; const defaultSettings = { accountID: 100, propertyID: 200, profileID: 300, internalWebPropertyID: 400, useSnippet: true, }; /** * Activate and set up the Analytics module. * @param {Object} settingsOverrides Optional settings to override the defaults. */ export async function setupAnalytics( settingsOverrides = {} ) { const settings = { ...defaultSettings, ...settingsOverrides, }; // Activate the module. await wpApiFetch( { method: 'post', path: 'google-site-kit/v1/modules/analytics', data: { active: true }, } ); // Set dummy connection data. await wpApiFetch( { method: 'post', path: 'google-site-kit/v1/modules/analytics/data/settings', data: { data: settings, }, parse: false, } ); }
/** * Internal dependencies */ import { wpApiFetch } from './wp-api-fetch'; const defaultSettings = { accountID: 100, propertyID: 200, profileID: 300, internalWebPropertyID: 400, useSnippet: true, // ampClientIDOptIn: (bool) }; /** * Activate and set up the Analytics module. * @param {Object} settingsOverrides Optional settings to override the defaults. */ export async function setupAnalytics( settingsOverrides = {} ) { const settings = { ...defaultSettings, ...settingsOverrides, }; // Activate the module. await wpApiFetch( { method: 'post', path: 'google-site-kit/v1/modules/analytics', data: { active: true }, } ); // Set dummy connection data. await wpApiFetch( { method: 'post', path: 'google-site-kit/v1/modules/analytics/data/settings', data: { data: settings, }, parse: false, } ); }
Refactor Command action to dragonglue.command
from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function) from dragonglue.command import send_command, Command grammar = Grammar("launch") applications = { 'sublime': 'w-s', 'pycharm': 'w-d', 'chrome': 'w-f', 'logs': 'w-j', 'SQL': 'w-k', 'IPython': 'w-l', 'shell': 'w-semicolon', 'terminal': 'w-a', # 'spotify': 'spotify /home/dan/bin/spotify', } # aliases applications['charm'] = applications['pycharm'] applications['termie'] = applications['terminal'] launch_rule = MappingRule( name="launch", mapping={ 'Do run': Key('w-x'), 'get <application>': Key('%(application)s'), # 're-browse': Key('w-F'), 'voice sync': Command('subl --command voice_sync'), '(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'), }, extras=[ Choice('application', applications) ] ) grammar.add_rule(launch_rule) grammar.load() def unload(): global grammar if grammar: grammar.unload() grammar = None
from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function) from dragonglue.command import send_command grammar = Grammar("launch") applications = { 'sublime': 'w-s', 'pycharm': 'w-d', 'chrome': 'w-f', 'logs': 'w-j', 'SQL': 'w-k', 'IPython': 'w-l', 'shell': 'w-semicolon', 'terminal': 'w-a', # 'spotify': 'spotify /home/dan/bin/spotify', } # aliases applications['charm'] = applications['pycharm'] applications['termie'] = applications['terminal'] def Command(cmd): def ex(application=''): # print 'execute', cmd + application send_command(cmd + application) return Function(ex) launch_rule = MappingRule( name="launch", mapping={ 'Do run': Key('w-x'), 'get <application>': Key('%(application)s'), # 're-browse': Key('w-F'), 'voice sync': Command('subl --command voice_sync'), '(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'), }, extras=[ Choice('application', applications) ] ) grammar.add_rule(launch_rule) grammar.load() def unload(): global grammar if grammar: grammar.unload() grammar = None
Change extra from 3 to 0.
# coding: utf-8 import re from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cmsplugin_bootstrap_carousel.models import * from django.utils.translation import ugettext as _ from django.contrib import admin from django.forms import ModelForm, ValidationError class CarouselForm(ModelForm): class Meta: model = Carousel def clean_domid(self): data = self.cleaned_data['domid'] if not re.match(r'^[a-zA-Z_]\w*$', data): raise ValidationError(_("The name must be a single word beginning with a letter")) return data class CarouselItemInline(admin.StackedInline): model = CarouselItem extra = 0 class CarouselPlugin(CMSPluginBase): model = Carousel form = CarouselForm name = _("Carousel") render_template = "cmsplugin_bootstrap_carousel/carousel.html" inlines = [ CarouselItemInline, ] def render(self, context, instance, placeholder): context.update({'instance' : instance}) return context plugin_pool.register_plugin(CarouselPlugin)
# coding: utf-8 import re from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cmsplugin_bootstrap_carousel.models import * from django.utils.translation import ugettext as _ from django.contrib import admin from django.forms import ModelForm, ValidationError class CarouselForm(ModelForm): class Meta: model = Carousel def clean_domid(self): data = self.cleaned_data['domid'] if not re.match(r'^[a-zA-Z_]\w*$', data): raise ValidationError(_("The name must be a single word beginning with a letter")) return data class CarouselItemInline(admin.StackedInline): model = CarouselItem class CarouselPlugin(CMSPluginBase): model = Carousel form = CarouselForm name = _("Carousel") render_template = "cmsplugin_bootstrap_carousel/carousel.html" inlines = [ CarouselItemInline, ] def render(self, context, instance, placeholder): context.update({'instance' : instance}) return context plugin_pool.register_plugin(CarouselPlugin)
Check if language is valid
const r = require('../../../db.js'); const i18n = require('i18n'); module.exports.info = { aliases: [ 'locale', 'lang', 'i18n' 'langue', 'langage' ] }; module.exports.command = (message) => { if (message.input && Object.keys(i18n.getCatalog()).includes(message.input)) { r.table('i18n') .insert({ id: message.inbox, lang: message.input }, { conflict: 'update' }) .run(r.conn, (err) => { if (err) { message.channel.createMessage(message.__('err_generic')); } else { message.setLocale(message.input); message.channel.createMessage(message.__('locale_set', { locale: message.input })); } }); } else { message.channel.createMessage(message.__('locale_incorrect', { locales: Object.keys(i18n.getCatalog()).join(', ') })); } };
const r = require('../../../db.js'); const i18n = require('i18n'); module.exports.info = { aliases: [ 'locale', 'lang' ] }; module.exports.command = (message) => { if (message.input) { r.table('i18n') .insert({ id: message.inbox, lang: message.input }, { conflict: 'update' }) .run(r.conn, (err) => { if (err) { message.channel.createMessage(message.__('err_generic')); } else { message.setLocale(message.input); message.channel.createMessage(message.__('locale_set', { locale: message.input })); } }); } else { message.channel.createMessage(message.__('locale_incorrect', { locales: Object.keys(i18n.getCatalog()).join(', ') })); } };
Fix println to use console.log
var lists = require('./list'); if (typeof cljs == 'undefined') cljs = {}; if (typeof cljs.core == 'undefined') cljs.core = {}; cljs.core.list = function () { return lists.create(arguments); } cljs.core.first = function (list) { return list.first(); } cljs.core.next = function (list) { return list.next(); } cljs.core.cons = function (first, next) { return lists.list(first, next); } cljs.core.println = function () { var result = ''; for (var k = 0; k < arguments.length; k++) result += arguments[k].toString(); console.log(result); } cljs.core.to_HY_object = function (value) { if (value == null) return []; return value.asObject(); }
var lists = require('./list'); if (typeof cljs == 'undefined') cljs = {}; if (typeof cljs.core == 'undefined') cljs.core = {}; cljs.core.list = function () { return lists.create(arguments); } cljs.core.first = function (list) { return list.first(); } cljs.core.next = function (list) { return list.next(); } cljs.core.cons = function (first, next) { return lists.list(first, next); } cljs.core.println = function () { var result = ''; for (var k = 0; k < arguments.length; k++) result += arguments[k].toString(); } cljs.core.to_HY_object = function (value) { if (value == null) return []; return value.asObject(); }
Resolve the value of self later
// @flow /* Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
// @flow /* Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { if (!self) { self = this; } return function() { var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
Fix window is not defined error
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import Container from '../components/Container'; import Header from '../components/Header'; import Footer from '../components/Footer'; import './index.css'; const propTypes = { children: PropTypes.func }; const path = typeof window != 'undefined' ? window.location.pathname : ''; const TemplateWrapper = ({ children }) => <div> <Helmet title="Colson Donohue" meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' } ]} /> <Header path={path} /> <Container> {children()} </Container> <Footer /> </div>; TemplateWrapper.propTypes = propTypes; export default TemplateWrapper;
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import Container from '../components/Container'; import Header from '../components/Header'; import Footer from '../components/Footer'; import './index.css'; const propTypes = { children: PropTypes.func }; const TemplateWrapper = ({ children }) => <div> <Helmet title="Colson Donohue" meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' } ]} /> <Header path={window.location.pathname} /> <Container> {children()} </Container> <Footer /> </div>; TemplateWrapper.propTypes = propTypes; export default TemplateWrapper;
Load Plugin for CakePHP greater or equal 3.7.0 Solution found at: https://github.com/cakephp/cakephp/issues/12682
<?php use Cake\Core\Plugin; $findRoot = function ($root) { do { $lastRoot = $root; $root = dirname($root); if (is_dir($root . '/vendor/cakephp/cakephp')) { return $root; } } while ($root !== $lastRoot); throw new \Exception('Cannot find the root of the application, unable to run tests'); }; $root = $findRoot(__FILE__); unset($findRoot); chdir($root); //if (file_exists($root . '/config/bootstrap.php')) { // require $root . '/config/bootstrap.php'; // return; //} require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php'; $loader = require $root . '/vendor/autoload.php'; $loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src'); $loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests'); $loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src'); $config = [ 'path' => dirname(__FILE__, 2) . DS, ]; if (\version_compare(\Cake\Core\Configure::version(), '3.7.0', 'lt')) { Plugin::load('Burzum/FileStorage', $config); } else { $plugin = new \Burzum\FileStorage\Plugin($config); Plugin::getCollection()->add($plugin); }
<?php use Cake\Core\Plugin; $findRoot = function ($root) { do { $lastRoot = $root; $root = dirname($root); if (is_dir($root . '/vendor/cakephp/cakephp')) { return $root; } } while ($root !== $lastRoot); throw new \Exception('Cannot find the root of the application, unable to run tests'); }; $root = $findRoot(__FILE__); unset($findRoot); chdir($root); //if (file_exists($root . '/config/bootstrap.php')) { // require $root . '/config/bootstrap.php'; // return; //} require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php'; $loader = require $root . '/vendor/autoload.php'; $loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src'); $loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests'); $loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src'); if (\version_compare(\Cake\Core\Configure::version(), '3.7.0', 'lt')) { Plugin::load('Burzum/FileStorage', [ 'path' => dirname(__FILE__, 2) . DS, ]); }
Make the printer data widget use the python script
command: '/usr/bin/env python stolaf-base/snmpGet.py', refreshFrequency: 300000, lastUpdateTime: undefined, style: [ "bottom: 0", "left: 75%", "width: 25%", "text-align: center", "border: 0", "height: 3%", "vertical-align: middle", "color: rgba(255, 255, 255, 0.25)", "font-weight: 300", ].join('\n'), render: function(argument) { return 'Printers: <span class="last-updated"></span>'; }, update: function(output, domEl) { if (!window.sto) return ''; if (!window.sto.libs.csv) return ''; if (!window.sto.libs.moment) return ''; var csv = window.sto.libs.csv; var moment = window.sto.libs.moment; window.sto.data.printers = csv.parse(output, {header: true, cast: ['String', 'String', 'String', 'String']});; this.lastUpdateTime = new Date(); domEl.querySelector('.last-updated').textContent = moment(this.lastUpdateTime).calendar(); },
command: '/bin/bash stolaf-base/snmpGet.sh', refreshFrequency: 600000, lastUpdateTime: undefined, style: [ "bottom: 0", "left: 75%", "width: 25%", "text-align: center", "border: 0", "height: 3%", "vertical-align: middle", "color: rgba(255, 255, 255, 0.25)", "font-weight: 300", ].join('\n'), render: function(argument) { return 'Printers: <span class="last-updated"></span>'; }, update: function(output, domEl) { if (!window.sto) return ''; if (!window.sto.libs.csv) return ''; if (!window.sto.libs.moment) return ''; var csv = window.sto.libs.csv; var moment = window.sto.libs.moment; window.sto.data.printers = csv.parse(output, {header: true, cast: ['String', 'String', 'String', 'String']});; this.lastUpdateTime = new Date(); domEl.querySelector('.last-updated').textContent = moment(this.lastUpdateTime).calendar(); },
Remove un-needed dynamic dependency to zlib Discovered in issue #25
#!/usr/bin/python2.7 from distutils.core import setup, Extension from sys import platform from setup_config import NASSL_SETUP, NASSL_EXT_SETUP from buildAll_config import OPENSSL_DIR, ZLIB_DIR from buildAll_unix import OPENSSL_INSTALL_DIR extra_compile_args = ['-Wall', '-Wno-deprecated-declarations'] if platform == 'darwin': # Workaround for Clang 3.4 # add as the element of an array rather than a string, py 2.7.5 extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future'] # Add arguments specific to Unix builds unix_ext_args = NASSL_EXT_SETUP.copy() unix_ext_args.update({ 'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'], 'extra_compile_args' : extra_compile_args, 'library_dirs' : [OPENSSL_DIR, ZLIB_DIR], 'libraries' : ['ssl', 'crypto']}) unix_setup = NASSL_SETUP.copy() unix_setup.update({ 'ext_modules' : [Extension(**unix_ext_args)] }) setup(**unix_setup)
#!/usr/bin/python2.7 from distutils.core import setup, Extension from sys import platform from setup_config import NASSL_SETUP, NASSL_EXT_SETUP from buildAll_config import OPENSSL_DIR, ZLIB_DIR from buildAll_unix import OPENSSL_INSTALL_DIR extra_compile_args = ['-Wall', '-Wno-deprecated-declarations'] if platform == 'darwin': # Workaround for Clang 3.4 # add as the element of an array rather than a string, py 2.7.5 extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future'] # Add arguments specific to Unix builds unix_ext_args = NASSL_EXT_SETUP.copy() unix_ext_args.update({ 'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'], 'extra_compile_args' : extra_compile_args, 'library_dirs' : [OPENSSL_DIR, ZLIB_DIR], 'libraries' : ['ssl', 'z', 'crypto']}) unix_setup = NASSL_SETUP.copy() unix_setup.update({ 'ext_modules' : [Extension(**unix_ext_args)] }) setup(**unix_setup)
Test with content changing button
(function (window, $, undefined) { 'use strict'; var Example; Example = function Example(cockpit) { console.log('Loading example plugin in the browser.'); // Instance variables this.cockpit = cockpit; // Add required UI elements $('#menu').prepend('<div id="example" class="hidden">[example]</div>'); cockpitEventEmitter.on('cockpit.pluginsLoaded', function() { var item = { label: ko.observable("Example menu") }; item.callback = function () { alert('example menu item from heads up menu'); item.label( item.label() +" Foo Bar"); }; cockpitEventEmitter.emit('headsUpMenu.register', item); cockpitEventEmitter.emit('headsUpMenu.register', { type: "custom", content: '<button class="btn btn-large btn-info btn-block" data-bind="click: callback">Custom button</button>', callback: function () { alert('Message from custom Button'); } }); }); }; window.Cockpit.plugins.push(Example); }(window, jQuery));
(function (window, $, undefined) { 'use strict'; var Example; Example = function Example(cockpit) { console.log('Loading example plugin in the browser.'); // Instance variables this.cockpit = cockpit; // Add required UI elements $('#menu').prepend('<div id="example" class="hidden">[example]</div>'); cockpitEventEmitter.on('cockpit.pluginsLoaded', function() { cockpitEventEmitter.emit('headsUpMenu.register', { label: "Example menu", // no type == explicit buttons callback: function () { alert('example menu item from heads up menu'); } }); cockpitEventEmitter.emit('headsUpMenu.register', { label: "Example menu button", type: "button", callback: function () { alert('example menu item from heads up menu 2'); } }); cockpitEventEmitter.emit('headsUpMenu.register', { type: "custom", content: '<button class="btn btn-large btn-info btn-block" data-bind="click: callback">Custom button</button>', callback: function () { alert('Message from custom Button'); } }); }); }; window.Cockpit.plugins.push(Example); }(window, jQuery));
Use assert instead of require for fixture tests
package main import ( "fmt" "io/ioutil" "testing" rss "github.com/jteeuwen/go-pkg-rss" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var items []*rss.Item var fixtures = []string{ "aws-ec2-us-east-1", "crossfitwc", "github-status", "heroku-status", "weather.gov-KPHL", } func Test_formatContent(t *testing.T) { for _, fixture := range fixtures { feed := rss.New(1, true, nil, testItemHandler) items = []*rss.Item{} xml, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.xml", fixture)) require.NoError(t, err) b, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.out", fixture)) require.NoError(t, err) expected := string(b) err = feed.FetchBytes("http://example.com", xml, charsetReader) require.NoError(t, err) require.NotEmpty(t, items) item := items[0] c, err := extractContent(item) require.NoError(t, err) assert.Equal(t, expected, formatContent(c), fixture) } } func testItemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) { items = newitems }
package main import ( "fmt" "io/ioutil" "testing" rss "github.com/jteeuwen/go-pkg-rss" "github.com/stretchr/testify/require" ) var items []*rss.Item var fixtures = []string{ "aws-ec2-us-east-1", "crossfitwc", "github-status", "heroku-status", "weather.gov-KPHL", } func Test_formatContent(t *testing.T) { for _, fixture := range fixtures { feed := rss.New(1, true, nil, testItemHandler) items = []*rss.Item{} xml, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.xml", fixture)) require.NoError(t, err) b, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.out", fixture)) require.NoError(t, err) expected := string(b) err = feed.FetchBytes("http://example.com", xml, charsetReader) require.NoError(t, err) require.NotEmpty(t, items) item := items[0] c, err := extractContent(item) require.NoError(t, err) require.Equal(t, expected, formatContent(c)) } } func testItemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) { items = newitems }
Remove unused inventory id constant
package org.achacha.test; /** * Well known constants populated into the database */ public class TestDataConstants { // login public static final long JUNIT_USER_LOGINID = 2; public static final String JUNIT_USER_EMAIL = "junit"; public static final String JUNIT_USER_PASSWORD = "test"; public static final long JUNIT_ADMIN_LOGINID = 3; public static final String JUNIT_ADMIN_EMAIL = "junitadmin"; public static final String JUNIT_ADMIN_PASSWORD = "test"; public static final long JUNIT_SU_LOGINID = 4; public static final String JUNIT_SU_EMAIL = "junitsu"; public static final String JUNIT_SU_PASSWORD = "test"; // player for JUNIT_USER_LOGINID public static final long JUNIT_PLAYER__ID = 1; }
package org.achacha.test; /** * Well known constants populated into the database */ public class TestDataConstants { // login public static final long JUNIT_USER_LOGINID = 2; public static final String JUNIT_USER_EMAIL = "junit"; public static final String JUNIT_USER_PASSWORD = "test"; public static final long JUNIT_ADMIN_LOGINID = 3; public static final String JUNIT_ADMIN_EMAIL = "junitadmin"; public static final String JUNIT_ADMIN_PASSWORD = "test"; public static final long JUNIT_SU_LOGINID = 4; public static final String JUNIT_SU_EMAIL = "junitsu"; public static final String JUNIT_SU_PASSWORD = "test"; // player for JUNIT_USER_LOGINID public static final long JUNIT_PLAYER__ID = 1; public static final long JUNIT_INVENTORY_ID = 1; // TODO: This will go away, data is to be generated dynamically and looked up by player id }