text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
__author__ = 'Chris Krycho' __copyright__ = '2013 Chris Krycho' from logging import error from os import path, walk from sys import exit try: from markdown import Markdown from mixins import DictAsMember except ImportError as import_error: error(import_error) exit() def convert_source(config): ''' Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to file names slugs (without the original file extension). ''' md = Markdown(extensions=config.markdown_extensions, output_format='html5') converted = {} for root, dirs, file_names in walk(config.site.content.source): for file_name in file_names: file_path = path.join(root, file_name) plain_slug, extension = path.splitext(file_name) with open(file_path) as file: md_text = file.read() content = md.convert(md_text) converted[plain_slug] = {'content': content, 'meta': md.Meta} md.reset() return DictAsMember(converted)
__author__ = 'Chris Krycho' __copyright__ = '2013 Chris Krycho' from logging import error from os import path, walk from sys import exit try: from markdown import Markdown from mixins import DictAsMember except ImportError as import_error: error(import_error) exit() def convert_source(config): ''' Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to file names slugs (without the original file extension). ''' md = Markdown(extensions=config.markdown_extensions, output_format='html5') converted = {} for root, dirs, file_names in walk(config.site.content.source): for file_name in file_names: file_path = path.join(root, file_name) plain_slug, extension = path.splitext(file_name) with open(file_path) as file: md_text = file.read() content = md.convert(md_text) converted[plain_slug] = {'content': content, 'meta': md.Meta} return DictAsMember(converted)
Refactor to use gdx GL instead of GL20
package stray.util.render; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; public class StencilMaskUtil { /** * call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered */ public static void prepareMask() { Gdx.gl.glDepthFunc(GL20.GL_LESS); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl.glDepthMask(true); Gdx.gl.glColorMask(false, false, false, false); } /** * call this AFTER batch.begin() and BEFORE drawing sprites */ public static void useMask() { Gdx.gl.glDepthMask(false); Gdx.gl.glColorMask(true, true, true, true); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl.glDepthFunc(GL20.GL_EQUAL); } /** * call this AFTER batch.flush/end */ public static void resetMask(){ Gdx.gl.glDisable(GL20.GL_DEPTH_TEST); } }
package stray.util.render; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; public class StencilMaskUtil { /** * call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered */ public static void prepareMask() { Gdx.gl20.glDepthFunc(GL20.GL_LESS); Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl20.glDepthMask(true); Gdx.gl20.glColorMask(false, false, false, false); } /** * call this AFTER batch.begin() and BEFORE drawing sprites */ public static void useMask() { Gdx.gl20.glDepthMask(false); Gdx.gl20.glColorMask(true, true, true, true); Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl20.glDepthFunc(GL20.GL_EQUAL); } /** * call this AFTER batch.flush/end */ public static void resetMask(){ Gdx.gl20.glDisable(GL20.GL_DEPTH_TEST); } }
Update an example test that uses deferred asserts
""" This test demonstrates the use of deferred asserts. Deferred asserts won't raise exceptions from failures until either process_deferred_asserts() is called, or the test reaches the tearDown() step. Requires version 2.1.6 or newer for the deferred_assert_exact_text() method. """ import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.deferred_assert_exact_text("Brand Identity", "#ctitle") self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
""" This test demonstrates the use of deferred asserts. Deferred asserts won't raise exceptions from failures until either process_deferred_asserts() is called, or the test reaches the tearDown() step. """ import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.process_deferred_asserts()
Fix another bug in the authentication
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main(Course.GetAllCoursesIds()) else: return renderer.index(True)
import web from modules.base import renderer from modules.login import loginInstance from modules.courses import Course #Index page class IndexPage: #Simply display the page def GET(self): if loginInstance.isLoggedIn(): userInput = web.input(); if "logoff" in userInput: loginInstance.disconnect(); return renderer.index(False) else: courses = Course.GetAllCoursesIds() return renderer.main(courses) else: return renderer.index(False) #Try to log in def POST(self): userInput = web.input(); if "login" in userInput and "password" in userInput and loginInstance.connect(userInput.login,userInput.password): return renderer.main() else: return renderer.index(True)
Solve Code Fights create die problem
#!/usr/local/bin/python # Code Fights Create Die Problem import random def createDie(seed, n): class Die(object): def __new__(self, seed, n): random.seed(seed) return int(random.random() * n) + 1 class Game(object): die = Die(seed, n) return Game.die def main(): tests = [ [37237, 5, 3], [36706, 12, 9], [21498, 10, 10], [2998, 6, 3], [5509, 10, 4] ] for t in tests: res = createDie(t[0], t[1]) ans = t[2] if ans == res: print("PASSED: createDie({}, {}) returned {}" .format(t[0], t[1], res)) else: print("FAILED: createDie({}, {}) returned {}, answer: {}" .format(t[0], t[1], res, ans)) if __name__ == '__main__': main()
#!/usr/local/bin/python # Code Fights Create Die Problem import random def createDie(seed, n): class Die(object): pass class Game(object): die = Die(seed, n) return Game.die def main(): tests = [ [37237, 5, 3], [36706, 12, 9], [21498, 10, 10], [2998, 6, 3], [5509, 10, 4] ] for t in tests: res = createDie(t[0], t[1]) ans = t[2] if ans == res: print("PASSED: createDie({}, {}) returned {}" .format(t[0], t[1], res)) else: print("FAILED: createDie({}, {}) returned {}, answer: {}" .format(t[0], t[1], res, ans)) if __name__ == '__main__': main()
Add litcoffee to Markdown extensions
from base_renderer import * import re import markdown @renderer class MarkdownRenderer(MarkupRenderer): FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$') def load_settings(self, renderer_options, global_setting): super(MarkdownRenderer, self).load_settings(renderer_options, global_setting) if 'extensions' in renderer_options: self.extensions = renderer_options['extensions'] else: # Fallback to the default GFM style self.extensions = ['tables', 'strikeout', 'fenced_code', 'codehilite'] if global_setting.mathjax_enabled: if 'mathjax' not in self.extensions: self.extensions.append('mathjax') @classmethod def is_enabled(cls, filename, syntax): if syntax == "text.html.markdown": return True return cls.FILENAME_PATTERN_RE.search(filename) is not None def render(self, text, **kwargs): return markdown.markdown(text, output_format='html5', extensions=self.extensions )
from base_renderer import * import re import markdown @renderer class MarkdownRenderer(MarkupRenderer): FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$') def load_settings(self, renderer_options, global_setting): super(MarkdownRenderer, self).load_settings(renderer_options, global_setting) if 'extensions' in renderer_options: self.extensions = renderer_options['extensions'] else: # Fallback to the default GFM style self.extensions = ['tables', 'strikeout', 'fenced_code', 'codehilite'] if global_setting.mathjax_enabled: if 'mathjax' not in self.extensions: self.extensions.append('mathjax') @classmethod def is_enabled(cls, filename, syntax): if syntax == "text.html.markdown": return True return cls.FILENAME_PATTERN_RE.search(filename) is not None def render(self, text, **kwargs): return markdown.markdown(text, output_format='html5', extensions=self.extensions )
Correct the unit test in V5_5_0 This file seems like copying from v5_4_0. Update it. Change-Id: I6125f66880feec7419ca6338ce23f05a01a2c3b3
# Copyright (c) 2015 Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara.plugins.cdh.v5_5_0 import plugin_utils as pu from sahara.tests.unit.plugins.cdh import base_plugin_utils_test class TestPluginUtilsV550(base_plugin_utils_test.TestPluginUtilsHigherThanV5): def setUp(self): super(TestPluginUtilsV550, self).setUp() self.plug_utils = pu.PluginUtilsV550() self.version = "v5_5_0"
# Copyright (c) 2015 Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sahara.plugins.cdh.v5_4_0 import plugin_utils as pu from sahara.tests.unit.plugins.cdh import base_plugin_utils_test class TestPluginUtilsV540(base_plugin_utils_test.TestPluginUtilsHigherThanV5): def setUp(self): super(TestPluginUtilsV540, self).setUp() self.plug_utils = pu.PluginUtilsV540() self.version = "v5_4_0"
Tweak resend button for acceptance testing
import Ember from 'ember'; import layout from '../../templates/components/nypr-accounts/resend-button'; import fetch from 'fetch'; import { task, timeout } from 'ember-concurrency'; import { rejectUnsuccessfulResponses } from 'nypr-account-settings/utils/fetch-utils'; export default Ember.Component.extend({ layout, tagName: '', target: null, email: null, resendAction: null, ready: true, success: false, error: false, autoReset: true, resetDelay: Ember.testing ? 10 : 10000, successMessage: 'Email resent', errorMessage: 'Email not resent. Try again later', actions: { resend(target, email) { let resendAction = () => fetch(`${target}?email=${email}`, {method: 'GET', mode: 'cors'}) .then(rejectUnsuccessfulResponses); this.get('tryResend').perform(resendAction); } }, tryResend: task(function * (resendAction) { try { yield resendAction(); this.set('ready', false); this.set('success', true); } catch(e) { this.set('ready', false); this.set('error', true); } finally { if (this.get('autoReset')) { yield timeout(this.get('resetDelay')); this.reset(); } } }).drop(), reset() { this.set('success', false); this.set('error', false); this.set('ready', true); } });
import Ember from 'ember'; import layout from '../../templates/components/nypr-accounts/resend-button'; import fetch from 'fetch'; import { task, timeout } from 'ember-concurrency'; import { rejectUnsuccessfulResponses } from 'nypr-account-settings/utils/fetch-utils'; export default Ember.Component.extend({ layout, tagName: '', target: null, email: null, resendAction: null, ready: true, success: false, error: false, autoReset: true, resetDelay: 10000, successMessage: 'Email resent', errorMessage: 'Email not resent. Try again later', actions: { resend(target, email) { let resendAction = () => fetch(`${target}?email=${email}`, {method: 'GET', mode: 'cors'}) .then(rejectUnsuccessfulResponses); this.get('tryResend').perform(resendAction); } }, tryResend: task(function * (resendAction) { try { yield resendAction(); this.set('ready', false); this.set('success', true); } catch(e) { this.set('ready', false); this.set('error', true); } finally { if (this.get('autoReset')) { yield timeout(this.get('resetDelay')); this.reset(); } } }).drop(), reset() { this.set('success', false); this.set('error', false); this.set('ready', true); } });
Change return type handling for AcmoTranslator
package org.agmip.ui.acmoui; import java.io.File; import org.agmip.acmo.translators.AcmoTranslator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TranslateRunner implements Runnable { private AcmoTranslator translator; private String inputDirectory; private String outputDirectory; private static Logger LOG = LoggerFactory.getLogger(TranslateRunner.class); public TranslateRunner(AcmoTranslator translator, String inputDirectory, String outputDirectory) { this.translator = translator; this.inputDirectory = inputDirectory; this.outputDirectory = outputDirectory; } @Override public void run() { LOG.debug("Starting new thread!"); File ret = translator.execute(inputDirectory, outputDirectory); if (ret != null && ret.exists()) { // TODO: Something to relate to the user something bad has happened. } } }
package org.agmip.ui.acmoui; import org.agmip.acmo.translators.AcmoTranslator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TranslateRunner implements Runnable { private AcmoTranslator translator; private String inputDirectory; private String outputDirectory; private static Logger LOG = LoggerFactory.getLogger(TranslateRunner.class); public TranslateRunner(AcmoTranslator translator, String inputDirectory, String outputDirectory) { this.translator = translator; this.inputDirectory = inputDirectory; this.outputDirectory = outputDirectory; } @Override public void run() { LOG.debug("Starting new thread!"); boolean success = translator.execute(inputDirectory, outputDirectory); if (!success) { // TODO: Something to relate to the user something bad has happened. } } }
Halt emails for time being
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
Update Controller to accept args
var Controller = function(args) { this.actorCanvas = args.actorCanvas; this.pac = new Actor({ context: this.actorCanvas.context, startX: 113, startY: 212, name: "m", direction: "right" }); this.blinky = new Ghost({ context: this.actorCanvas.context, direction: "left", name: "b", startX: 112, startY: 116 }); this.inky = new Ghost({ context: this.actorCanvas.context, direction: "up", name: "i", startX: 96, startY: 139 }); this.pinky = new Ghost({ context: this.actorCanvas.context, direction: "right", name: "p", startX: 112, startY: 139 }); this.clyde = new Ghost({ context: this.actorCanvas.context, direction: "down", name: "c", startX: 128, startY: 139 }); }
var Controller = function() { this.pac = new Actor({ context: actorCanvas.context, startX: 113, startY: 212, name: "m", direction: "right" }); this.blinky = new Ghost({ context: actorCanvas.context, direction: "left", name: "b", startX: 112, startY: 116 }); this.inky = new Ghost({ context: actorCanvas.context, direction: "up", name: "i", startX: 96, startY: 139 }); this.pinky = new Ghost({ context: actorCanvas.context, direction: "right", name: "p", startX: 112, startY: 139 }); this.clyde = new Ghost({ context: actorCanvas.context, direction: "down", name: "c", startX: 128, startY: 139 }); }
Check every element of slices
package models import ( "testing" ) func SetUser() *User { return &User { LoginName: "loginName", GitHubUsername: "github_user", SlackUsername: "slack_user", SlackUserId: "SLACKID", } } func TestSlackMention(t *testing.T) { user := SetUser() expect := "<@SLACKID|slack_user>" actual := user.SlackMention() if actual != expect { t.Fatalf("%v does not much to expected: %v", actual, expect) } } func TestEnvs(t *testing.T) { user := SetUser() expect := []string{ "GITHUB_USERNAME=github_user", "SLACK_MENTION=<@SLACKID|slack_user>", } actual := user.Envs() if len(actual) != len(expect) { t.Fatalf("%v does not much to expected: %v", len(actual), len(expect)) } for i := range expect { if expect[i] != actual[i] { t.Fatalf("%v does not much to expected: %v", actual, expect) } } }
package models import ( "testing" ) func SetUser() *User { return &User { LoginName: "loginName", GitHubUsername: "github_user", SlackUsername: "slack_user", SlackUserId: "SLACKID", } } func TestSlackMention(t *testing.T) { user := SetUser() expect := "<@SLACKID|slack_user>" actual := user.SlackMention() if actual != expect { t.Fatalf("%v does not much to expected: %v", actual, expect) } } func TestEnvs(t *testing.T) { user := SetUser() expect := []string{ "GITHUB_USERNAME=github_user", "SLACK_MENTION=<@SLACKID|slack_user>", } actual := user.Envs() if len(actual) != len(expect) { t.Fatalf("%v does not much to expected: %v", len(actual), len(expect)) } }
Fix case of finding the top of tree node
/*- * Copyright 2015 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.tree; public class TreeUtils { /** * Get the path * @param tree * @param node * @return path to node, return null if not found */ public static String getPath(Tree tree, Node node) { GroupNode g = tree.getGroupNode(); if (g == node) { return tree.getNodeLink().getFullName(); } return getPathDepthFirst(tree.getGroupNode(), node); } private static String getPathDepthFirst(final GroupNode group, final Node node) { for (NodeLink l : group) { if (l.getDestination() == node) { return l.getFullName(); } else if (l.isDestinationGroup()) { String p = getPathDepthFirst((GroupNode) l.getDestination(), node); if (p != null) return p; } } return null; } }
/*- * Copyright 2015 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.tree; public class TreeUtils { /** * Get the path * @param tree * @param node * @return path to node, return null if not found */ public static String getPath(Tree tree, Node node) { return getPathDepthFirst(tree.getGroupNode(), node); } private static String getPathDepthFirst(final GroupNode group, final Node node) { for (NodeLink l : group) { if (l.getDestination() == node) { return l.getFullName(); } else if (l.isDestinationGroup()) { String p = getPathDepthFirst((GroupNode) l.getDestination(), node); if (p != null) return p; } } return null; } }
Allow path to be explicitly set when using what-is-this
import os import subprocess import sys def find_command(name): return commands[name] def what_is_this_command(): directory = sys.argv[2] if len(sys.argv) > 2 else os.getcwd() repository = find_repository(directory) if repository is None: print "Could not find source control repository" else: print "{0}+file://{1}".format(repository.type, repository.path) def find_repository(directory): directory = os.path.abspath(directory) while directory is not None: files = os.listdir(directory) if ".git" in files: return Repository(os.path.join(directory, ".git"), "git") directory = parent(directory) return None class Repository(object): def __init__(self, repo_path, repo_type): self.path = repo_path self.type = repo_type def parent(file_path): parent = os.path.dirname(file_path) if file_path == parent: return None else: return parent commands = { "whatisthis": what_is_this_command, "what-is-this": what_is_this_command }
import os import subprocess import sys def find_command(name): return commands[name] def what_is_this_command(): repository = find_current_repository() if repository is None: print "Could not find source control repository" else: print "{0}+file://{1}".format(repository.type, repository.path) def find_current_repository(): directory = os.getcwd() while directory is not None: files = os.listdir(directory) if ".git" in files: return Repository(os.path.join(directory, ".git"), "git") directory = parent(directory) return None class Repository(object): def __init__(self, repo_path, repo_type): self.path = repo_path self.type = repo_type def parent(file_path): parent = os.path.dirname(file_path) if file_path == parent: return None else: return parent commands = { "whatisthis": what_is_this_command, "what-is-this": what_is_this_command }
Fix log option with ternary operator
var path = require('path'); var batch = require('gulp-batch'); module.exports = init; function init(options){ options = defaultOptions(options); registerTask(options); } function defaultOptions(options){ options = options || {}; options.gulp = options.gulp || require('gulp'); options.task = options.task || 'watch'; options.dependencies = options.dependencies || ['default']; options.watch = options.watch || []; options.batch = options.batch || {}; options.log = (typeof options.log !== 'undefined') ? options.log : true; options.start = options.start || 'default'; return options; } function registerTask(options){ var gulp = options.gulp; gulp.task(options.task, options.dependencies, function(){ gulp.watch(options.watch, batch(options.batch, function(events, done){ events .on('data', function(data){ if(options.log){ console.log(data.type, path.basename(data.path)); } }) .on('end', function(){ gulp.start(options.start, done); }); })); }); }
var path = require('path'); var batch = require('gulp-batch'); module.exports = init; function init(options){ options = defaultOptions(options); registerTask(options); } function defaultOptions(options){ options = options || {}; options.gulp = options.gulp || require('gulp'); options.task = options.task || 'watch'; options.dependencies = options.dependencies || ['default']; options.watch = options.watch || []; options.batch = options.batch || {}; options.log = options.log || true; options.start = options.start || 'default'; return options; } function registerTask(options){ var gulp = options.gulp; gulp.task(options.task, options.dependencies, function(){ gulp.watch(options.watch, batch(options.batch, function(events, done){ events .on('data', function(data){ if(options.log){ console.log(data.type, path.basename(data.path)); } }) .on('end', function(){ gulp.start(options.start, done); }); })); }); }
Fix support for older gevent versions. Gevent 1.5 removed the `gevent.signal` alias, but some older versions do not have the new `signal_handler` function.
import os import signal import sys import click import gevent import pyinfra from .legacy import run_main_with_legacy_arguments from .main import cli, main # Set CLI mode pyinfra.is_cli = True # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) behave as if imported from the cwd sys.path.append('.') # Shut it click click.disable_unicode_literals_warning = True # noqa # Force line buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1) def _handle_interrupt(signum, frame): click.echo('Exiting upon user request!') sys.exit(0) try: # Kill any greenlets on ctrl+c gevent.signal_handler(signal.SIGINT, gevent.kill) except AttributeError: # Legacy (gevent <1.2) support gevent.signal(signal.SIGINT, gevent.kill) signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main def execute_pyinfra(): # Legacy support for pyinfra <0.4 using docopt if '-i' in sys.argv: run_main_with_legacy_arguments(main) else: cli() if __name__ == 'pyinfra_cli.__main__': execute_pyinfra()
import os import signal import sys import click import gevent import pyinfra from .legacy import run_main_with_legacy_arguments from .main import cli, main # Set CLI mode pyinfra.is_cli = True # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) behave as if imported from the cwd sys.path.append('.') # Shut it click click.disable_unicode_literals_warning = True # noqa # Force line buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1) def _handle_interrupt(signum, frame): click.echo('Exiting upon user request!') sys.exit(0) gevent.signal_handler(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main def execute_pyinfra(): # Legacy support for pyinfra <0.4 using docopt if '-i' in sys.argv: run_main_with_legacy_arguments(main) else: cli() if __name__ == 'pyinfra_cli.__main__': execute_pyinfra()
Add new resource URL to whitelist
'use strict'; var morphopedia = angular.module( 'morphopedia', [ 'ngResource', 'matchMedia', 'angular-preload-image', 'leaflet-directive', 'angular.filter', 'root', 'mobile-angular-ui' ] ); morphopedia.config( function( $urlRouterProvider, $locationProvider, $sceDelegateProvider, $logProvider ) { $logProvider.debugEnabled(false); $urlRouterProvider.otherwise( '/' ); $locationProvider.html5Mode( true ); // Whitelist AWS for asset-loading $sceDelegateProvider.resourceUrlWhitelist([ // Allow same origin resource loads. 'self', // Allow loading from our assets domain. 'https://morphassets.s3.amazonaws.com/**' ]); } ); morphopedia.run( [ '$rootScope', function( $rootScope ) { // For Mobile Angular UI compatibility $rootScope.$on( '$stateChangeStart', function( ) { $rootScope.$broadcast( '$routeChangeStart' ); } ); $rootScope.$on( '$stateChangeSuccess', function( event, toState, toParams, fromState, fromParams ) { $rootScope.fromState = fromState; $rootScope.fromParams = fromParams; $rootScope.toState = toState; $rootScope.toParams = toParams; } ); } ] );
'use strict'; var morphopedia = angular.module( 'morphopedia', [ 'ngResource', 'matchMedia', 'angular-preload-image', 'leaflet-directive', 'angular.filter', 'root', 'mobile-angular-ui' ] ); morphopedia.config( function( $urlRouterProvider, $locationProvider, $sceDelegateProvider, $logProvider ) { $logProvider.debugEnabled(false); $urlRouterProvider.otherwise( '/' ); $locationProvider.html5Mode( true ); // Whitelist AWS for asset-loading $sceDelegateProvider.resourceUrlWhitelist([ // Allow same origin resource loads. 'self', // Allow loading from our assets domain. 'https://morphmorphupdated2.s3.amazonaws.com/**' ]); } ); morphopedia.run( [ '$rootScope', function( $rootScope ) { // For Mobile Angular UI compatibility $rootScope.$on( '$stateChangeStart', function( ) { $rootScope.$broadcast( '$routeChangeStart' ); } ); $rootScope.$on( '$stateChangeSuccess', function( event, toState, toParams, fromState, fromParams ) { $rootScope.fromState = fromState; $rootScope.fromParams = fromParams; $rootScope.toState = toState; $rootScope.toParams = toParams; } ); } ] );
Update the put put text
musketeersName = 'Tom Dick Harry' print 'Three musketeers are', musketeersName musketeer_1 = musketeersName[0:3] print 'First musketeer :', musketeer_1 musketeer_2 = musketeersName[4:8] print 'Second musketeer :', musketeer_2 musketeer_3 = musketeersName[9:14] print 'Third musketeer :', musketeer_3 print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n" musketeer_3 = musketeersName[9:20] print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3 print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n" firstTwoChars = musketeersName[:2] print 'First Two characters of the string :', firstTwoChars lastTwoChars = musketeersName[12:] print 'Last Two characters of the string :', lastTwoChars allChars = musketeersName[:] print 'All characters of the string :', allChars
musketeersName = 'Tom Dick Harry' print 'Three musketeers are', musketeersName musketeer_1 = musketeersName[0:3] print 'First musketeer :', musketeer_1 musketeer_2 = musketeersName[4:8] print 'Second musketeer :', musketeer_2 musketeer_3 = musketeersName[9:14] print 'Third musketeer :', musketeer_3 print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n" musketeer_3 = musketeersName[9:20] print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3 print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n" firstTwoChars = musketeersName[:2] print 'First Two characters of the string :', firstTwoChars lastTwoChars = musketeersName[12:] print 'First Two characters of the string :', lastTwoChars allChars = musketeersName[:] print 'All characters of the string :', allChars
Fix the "no else after return" lint
""" Binary search """ def binary_search0(xs, x): """ Perform binary search for a specific value in the given sorted list :param xs: a sorted list :param x: the target value :return: an index if the value was found, or None if not """ lft, rgt = 0, len(xs) - 1 while lft <= rgt: mid = (lft + rgt) // 2 if xs[mid] == x: return mid if xs[mid] < x: lft = mid + 1 else: rgt = mid - 1 return None def binary_search1(xs, x): """ Perform binary search for a specific value in the given sorted list :param xs: a sorted list :param x: the target value :return: an index if the value was found, or None if not """ lft, rgt = 0, len(xs) while lft < rgt: mid = (lft + rgt) // 2 if xs[mid] == x: return mid if xs[mid] < x: lft = mid + 1 else: rgt = mid return None
""" Binary search """ def binary_search0(xs, x): """ Perform binary search for a specific value in the given sorted list :param xs: a sorted list :param x: the target value :return: an index if the value was found, or None if not """ lft, rgt = 0, len(xs) - 1 while lft <= rgt: mid = (lft + rgt) // 2 if xs[mid] == x: return mid elif x < xs[mid]: rgt = mid - 1 elif x > xs[mid]: lft = mid + 1 return None def binary_search1(xs, x): """ Perform binary search for a specific value in the given sorted list :param xs: a sorted list :param x: the target value :return: an index if the value was found, or None if not """ lft, rgt = 0, len(xs) while lft < rgt: mid = (lft + rgt) // 2 if xs[mid] == x: return mid elif x < xs[mid]: rgt = mid elif x > xs[mid]: lft = mid + 1 return None
Fix a couple of typos in the program description
import os import re ''' This is used to revert back a Dropbox conflict. So in this case I want to keep all the files that were converted to conflict copies. So I just strip out the conflict string ie (some computer names's conflict copy some date) .ext and remove that conflict part of the string, and override the original file by that name. ''' for root, dirs, files, in os.walk(r"path to your drop box file with conflicts"): for file in files: file_matcher = re.search(r"(.+) (\(.+'s conflicted copy [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*\))(.+)?", file) if file_matcher: full_path = os.path.join(root, file) conflict_file_name = file_matcher.group(0) clean_file_name = file_matcher.group(1) conflict_string = file_matcher.group(2) file_ext = file_matcher.group(3) new_name_file_name = clean_file_name if file_ext: new_name_file_name += file_ext new_path = os.path.join(root, new_name_file_name) print("from: " + full_path + " to: " + new_path) os.replace(full_path, new_path)
import os import re ''' This is used to revert back a Dropbox conflict. So in this case I want to keep all the files that where converted to conflict copies. So I just strip out the conflict string ie (some computer names's conflict copy some date) .ext and remove that conflict part of the string, and overate the original file by that name. ''' for root, dirs, files, in os.walk(r"path to your drop box file with conflicts"): for file in files: file_matcher = re.search(r"(.+) (\(.+'s conflicted copy [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*\))(.+)?", file) if file_matcher: full_path = os.path.join(root, file) conflict_file_name = file_matcher.group(0) clean_file_name = file_matcher.group(1) conflict_string = file_matcher.group(2) file_ext = file_matcher.group(3) new_name_file_name = clean_file_name if file_ext: new_name_file_name += file_ext new_path = os.path.join(root, new_name_file_name) print("from: " + full_path + " to: " + new_path) os.replace(full_path, new_path)
Change path to end with separator if it refers to a group
/*- * Copyright 2015 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.tree; public class TreeUtils { /** * Get the path which ends with {@value Node#SEPARATOR} if it refers to a group * @param tree * @param node * @return path to node, return null if not found */ public static String getPath(Tree tree, Node node) { GroupNode g = tree.getGroupNode(); if (g == node) { return tree.getNodeLink().getFullName(); } String p = getPathDepthFirst(tree.getGroupNode(), node); if (node instanceof GroupNode && !p.endsWith(Node.SEPARATOR)) { p = p + Node.SEPARATOR; } return p; } private static String getPathDepthFirst(final GroupNode group, final Node node) { for (NodeLink l : group) { if (l.getDestination() == node) { return l.getFullName(); } else if (l.isDestinationGroup()) { String p = getPathDepthFirst((GroupNode) l.getDestination(), node); if (p != null) return p; } } return null; } }
/*- * Copyright 2015 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.tree; public class TreeUtils { /** * Get the path * @param tree * @param node * @return path to node, return null if not found */ public static String getPath(Tree tree, Node node) { GroupNode g = tree.getGroupNode(); if (g == node) { return tree.getNodeLink().getFullName(); } return getPathDepthFirst(tree.getGroupNode(), node); } private static String getPathDepthFirst(final GroupNode group, final Node node) { for (NodeLink l : group) { if (l.getDestination() == node) { return l.getFullName(); } else if (l.isDestinationGroup()) { String p = getPathDepthFirst((GroupNode) l.getDestination(), node); if (p != null) return p; } } return null; } }
Update the names of custom properties in the epub-reflowable module
EpubReflowable.ReflowableCustomizer = Backbone.Model.extend({ initialize : function (attributes, options) { this.$parentEl = $(this.get("parentElement")); this.set("customBorder", new EpubReflowable.ReflowableCustomBorder({ targetElement : this.get("readiumFlowingContent") })); this.set("customTheme", new EpubReflowable.ReflowableCustomTheme({ iframeElement : this.get("readiumFlowingContent") })); }, // ----- PUBLIC INTERFACE ------------------------------------------------------------------- setCustomStyle : function (customProperty, styleNameOrCSS) { if (customProperty === "reflowable-epub-border" || customProperty === "epub-border") { this.get("customBorder").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "reflowable-spine-divider" || customProperty === "spine-divider") { this.get("spineDividerStyleView").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "reflowable-page-border" || customProperty === "page-border") { this.get("customBorder").setCurrentStyle(styleNameOrCSS); this.get("spineDividerStyleView").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "reflowable-page-theme") { this.get("customTheme").setCurrentStyle(styleNameOrCSS); } } // ----- PRIVATE HELPERS ------------------------------------------------------------------- });
EpubReflowable.ReflowableCustomizer = Backbone.Model.extend({ initialize : function (attributes, options) { this.$parentEl = $(this.get("parentElement")); this.set("customBorder", new EpubReflowable.ReflowableCustomBorder({ targetElement : this.get("readiumFlowingContent") })); this.set("customTheme", new EpubReflowable.ReflowableCustomTheme({ iframeElement : this.get("readiumFlowingContent") })); }, // ----- PUBLIC INTERFACE ------------------------------------------------------------------- setCustomStyle : function (customProperty, styleNameOrCSS) { if (customProperty === "border") { this.get("customBorder").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "spine-divider") { this.get("spineDividerStyleView").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "page-border") { this.get("customBorder").setCurrentStyle(styleNameOrCSS); this.get("spineDividerStyleView").setCurrentStyle(styleNameOrCSS); } else if (customProperty === "page-theme") { this.get("customTheme").setCurrentStyle(styleNameOrCSS); } } // ----- PRIVATE HELPERS ------------------------------------------------------------------- });
FIX TO THE MOST EPIC BUG EVER (HOPEFULLY)
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), mongoose = require('mongoose'), User = mongoose.model('User'); /** * User middleware */ exports.userByID = function(req, res, next, id) { User.findOne({ _id: id }).exec(function(err, user) { if (err) return next(err); if (!user) return next(new Error('Failed to load User ' + id)); req.profile = user; next(); }); }; /** * Require login routing middleware */ exports.requiresLogin = function(req, res, next) { if (!req.isAuthenticated()) { return res.status(401).send({ message: 'User is not logged in' }); } next(); }; /** * User authorizations routing middleware */ exports.hasAuthorization = function(roles) { var _this = this; return function(req, res, next) { _this.requiresLogin(req, res, function() { if (_.intersection(req.user.roles, roles).length) { return next(); } else if(req.user.roles.indexOf("admin") === -1){ return res.status(403).send({ message: 'User is not authorized' }); } }); }; };
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), mongoose = require('mongoose'), User = mongoose.model('User'); /** * User middleware */ exports.userByID = function(req, res, next, id) { User.findOne({ _id: id }).exec(function(err, user) { if (err) return next(err); if (!user) return next(new Error('Failed to load User ' + id)); req.user = user; next(); }); }; /** * Require login routing middleware */ exports.requiresLogin = function(req, res, next) { if (!req.isAuthenticated()) { return res.status(401).send({ message: 'User is not logged in' }); } next(); }; /** * User authorizations routing middleware */ exports.hasAuthorization = function(roles) { var _this = this; return function(req, res, next) { _this.requiresLogin(req, res, function() { if (_.intersection(req.user.roles, roles).length) { return next(); } else if(req.user.roles.indexOf("admin") === -1){ return res.status(403).send({ message: 'User is not authorized' }); } }); }; };
Remove the old upload module
// Socket import '../modules/socket/socket-server'; // Auth modules import '../modules/facebook/facebook'; import '../modules/google/google'; import '../modules/session/session'; import '../modules/signin/signin'; import '../modules/signup/signup'; import '../modules/resource/resource'; import '../modules/belong/belong'; /* ########### */ import '../modules/relations/relations'; import '../modules/guard/guard-server'; import './../modules/count/count'; import './../modules/note/note'; import '../modules/score/score'; import '../modules/gcm/gcm-server'; import '../modules/postgres/postgres'; import '../modules/image-upload/image-upload'; // import "./../modules/ui/ui-server"; import '../modules/http/http'; // if fired before socket server then the http/init listener might not be listening.. // Email server import '../modules/email/email-daemon';
// Socket import '../modules/socket/socket-server'; // Auth modules import '../modules/facebook/facebook'; import '../modules/google/google'; import '../modules/session/session'; import '../modules/signin/signin'; import '../modules/signup/signup'; import '../modules/resource/resource'; import '../modules/belong/belong'; /* ########### */ import '../modules/relations/relations'; import '../modules/guard/guard-server'; import './../modules/count/count'; import './../modules/note/note'; import './../modules/upload/upload'; import '../modules/score/score'; import '../modules/gcm/gcm-server'; import '../modules/postgres/postgres'; import '../modules/image-upload/image-upload'; // import "./../modules/ui/ui-server"; import '../modules/http/http'; // if fired before socket server then the http/init listener might not be listening.. // Email server import '../modules/email/email-daemon';
Use stateless function instead of class for counter implementation
import * as counterActions from '../../common/counter/actions'; import React, { PropTypes as RPT } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; function Counter(props) { const { actions, counter } = props; return ( <div> <h2>Counter: {counter}</h2> <button onClick={actions.increment}>inc</button> <button onClick={actions.decrement}>dec</button> <button onClick={actions.magicAction2}>asyncss</button> </div> ); } Counter.propTypes = { counter: RPT.number, actions: RPT.object }; export default connect( (state) => { const counter = state.counter.counter; return { counter }; }, (dispatch) => { const actions = bindActionCreators(counterActions, dispatch); return { actions }; } )(Counter);
import React, { PropTypes as RPT, Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as counterActions from '../../common/counter/actions'; @connect( (state) => { const counter = state.counter.counter; return { counter }; }, (dispatch) => { const actions = bindActionCreators(counterActions, dispatch); return { actions }; } ) export default class Counter extends Component { static propTypes = { counter: RPT.number, actions: RPT.object } render() { const { actions } = this.props; return ( <div> <h2>Counter: {this.props.counter}</h2> <button onClick={actions.increment}>inc</button> <button onClick={actions.decrement}>dec</button> <button onClick={actions.magicAction2}>asyncss</button> </div> ); } }
Fix typo in pipe docstring Signed-off-by: Zac Delventhal <593147d2808cd66b7e2ad59ca4b0c07d6c52cddd@gmail.com>
/** * @callback Into * @param {function} fn - the next function in the pipe * @param {...any} [args] - additional arguments to apply to function * @returns Pipeable */ /** * @typedef Pipeable * @prop {Into} into - pipes the value into a new function * @prop {function(): any} done - breaks the chain, returning the final value */ /** * Allows a chain of functions to be built using an `into` method to pass in the * next function. Use the `done` method to complete the chain and return the value * * @param {any} operand - the value to pipe * @returns {Pipeable} */ export const pipe = operand => ({ into: (fn, ...args) => pipe(fn(operand, ...args)), done: () => operand, }); /** * Creates a new version of a function which uses the first parameter in place of `this` * * @param {function} fn * @returns {function(...any): any} */ export const thisFirst = fn => fn.call.bind(fn);
/** * @callback Into * @param {any} operand - value to pipe into a function * @param {...any} [args] - additional arguments to apply to function * @returns Pipeable */ /** * @typedef Pipeable * @prop {Into} into - pipes the value into a new function * @prop {function(): any} done - breaks the chain, returning the final value */ /** * Allows a chain of functions to be built using an `into` method to pass in the * next function. Use the `done` method to complete the chain and return the value * * @param {any} operand - the value to pipe * @returns {Pipeable} */ export const pipe = operand => ({ into: (fn, ...args) => pipe(fn(operand, ...args)), done: () => operand, }); /** * Creates a new version of a function which uses the first parameter in place of `this` * * @param {function} fn * @returns {function(...any): any} */ export const thisFirst = fn => fn.call.bind(fn);
Use test-peer-range for logs, not target peer
'use strict' import {Runner} from '../' import yargs from 'yargs' import prop from 'dot-prop' import {resolve} from 'path' import {createLogger} from 'clout' const {cwd} = process const pkg = require(resolve(cwd(), 'package.json')) const log = createLogger('test-peer-range') const {argv} = yargs .demand(1) .option('script', { default: 'test-main', describe: 'test script' }) const [peer] = argv._ const {script, verbose} = argv const range = prop.get(pkg, `peerDependencies.${peer}`) new Runner(peer, range, {script}) .on('versions', (versions) => { log(`Testing ${peer} versions ${versions.join(', ')}`) }) .on('preinstall', (version) => { log(`Installing ${peer}@${version}`) }) .on('postinstall', (version) => { log(`Installed ${peer}@${version}`) }) .on('prescript', (version) => { log(`Starting "${script}" for ${peer}@${version}`) }) .on('result', ({passed, version}) => { const outcome = passed ? 'Passed' : 'Failed' log(`${outcome}: ${peer}@${version}`) }) .run() .catch(fail) function fail (err) { log.error(err) console.error(err.stack) process.exit(1) }
'use strict' import {Runner} from '../' import yargs from 'yargs' import prop from 'dot-prop' import {resolve} from 'path' import {createLogger} from 'clout' const {cwd} = process const pkg = require(resolve(cwd(), 'package.json')) const log = createLogger(pkg.name) const {argv} = yargs .demand(1) .option('script', { default: 'test-main', describe: 'test script' }) const [peer] = argv._ const {script, verbose} = argv const range = prop.get(pkg, `peerDependencies.${peer}`) new Runner(peer, range, {script}) .on('versions', (versions) => { log(`Testing ${peer} versions ${versions.join(', ')}`) }) .on('preinstall', (version) => { log(`Installing ${peer}@${version}`) }) .on('postinstall', (version) => { log(`Installed ${peer}@${version}`) }) .on('prescript', (version) => { log(`Starting "${script}" for ${peer}@${version}`) }) .on('result', ({passed, version}) => { const outcome = passed ? 'Passed' : 'Failed' log(`${outcome}: ${peer}@${version}`) }) .run() .catch(fail) function fail (err) { log.error(err) console.error(err.stack) process.exit(1) }
Increase delay of clean_concourse plugin to 2s This plugin assumes that all the elements are present and the page rendered after 10ms, and if not, it fails because it cannot find the right DOM elements. The new version of concourse 2.4.0 takes longer to completely render in the dashboard screen, specially when we have 3 frames as we do. Because that the script does not work in our dashboard. In this commit we workaround this issue by delaying the execution of the script much more longer, up to 2000ms or 2s. A more elegant solution should be waiting/polling until all elements are present and then apply the changes. But as this is a simple script for our dashboards it is not so relevant.
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital",""); var element = document.getElementById("top-bar-app"); element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; // Move it to the bottom because there's more space there. element.style.position = "absolute"; element.style.bottom = "0"; var element = document.getElementsByClassName("bottom")[0]; // Remove the padding because the top bar isn't there any more. element.style.paddingTop = "0"; } }, 2000);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital",""); var element = document.getElementById("top-bar-app"); element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; // Move it to the bottom because there's more space there. element.style.position = "absolute"; element.style.bottom = "0"; var element = document.getElementsByClassName("bottom")[0]; // Remove the padding because the top bar isn't there any more. element.style.paddingTop = "0"; } }, 10);
TST: Update for unit tests for PR 37
""" Unit tests for grid_utils module. """ from datetime import datetime import numpy as np from tint import grid_utils from tint.testing.sample_objects import grid, field from tint.testing.sample_objects import params, grid_size def test_parse_grid_datetime(): dt = grid_utils.parse_grid_datetime(grid) assert(dt == datetime(2015, 7, 10, 18, 34, 102000)) def test_get_grid_size(): grid_size = grid_utils.get_grid_size(grid) assert np.all(grid_size == np.array([500., 500., 500.])) def test_extract_grid_data(): raw, filtered = grid_utils.extract_grid_data(grid, field, grid_size, params) assert np.max(filtered) == 11 assert np.min(filtered) == 0
""" Unit tests for grid_utils module. """ from datetime import datetime import numpy as np from tint import grid_utils from tint.testing.sample_objects import grid, field from tint.testing.sample_objects import params, grid_size def test_parse_grid_datetime(): dt = grid_utils.parse_grid_datetime(grid) assert(dt == datetime(2015, 7, 10, 18, 34, 6)) def test_get_grid_size(): grid_size = grid_utils.get_grid_size(grid) assert np.all(grid_size == np.array([500., 500., 500.])) def test_extract_grid_data(): raw, filtered = grid_utils.extract_grid_data(grid, field, grid_size, params) assert np.max(filtered) == 11 assert np.min(filtered) == 0
INDY-1199: Make interface of NetworkI3PCWatcher more clear Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
from typing import Callable, Iterable from plenum.server.quorums import Quorums class NetworkI3PCWatcher: def __init__(self, cb: Callable): self._nodes = set() self.connected = set() self.callback = cb self.quorums = Quorums(0) def connect(self, name: str): self.connected.add(name) def disconnect(self, name: str): had_consensus = self._has_consensus() self.connected.discard(name) if had_consensus and not self._has_consensus(): self.callback() @property def nodes(self): return self._nodes def set_nodes(self, nodes: Iterable[str]): self._nodes = set(nodes) self.quorums = Quorums(len(self._nodes)) def _has_consensus(self): return self.quorums.weak.is_reached(len(self.connected))
from typing import Callable, Iterable from plenum.server.quorums import Quorums class NetworkI3PCWatcher: def __init__(self, cb: Callable): self.nodes = set() self.connected = set() self.callback = cb self.quorums = Quorums(0) def connect(self, name: str): self.connected.add(name) def disconnect(self, name: str): had_consensus = self._has_consensus() self.connected.discard(name) if had_consensus and not self._has_consensus(): self.callback() def set_nodes(self, nodes: Iterable[str]): self.nodes = set(nodes) self.quorums = Quorums(len(self.nodes)) def _has_consensus(self): return self.quorums.weak.is_reached(len(self.connected))
Fix URL to point to a valid repo
import os from setuptools import setup, find_packages setup(name='Coffin', version=".".join(map(str, __import__("coffin").__version__)), description='Jinja2 adapter for Django', author='Christopher D. Leary', author_email='cdleary@gmail.com', maintainer='David Cramer', maintainer_email='dcramer@gmail.com', url='http://github.com/coffin/coffin', packages=find_packages(), #install_requires=['Jinja2', 'django>=1.2'], classifiers=[ "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "Operating System :: OS Independent", "Topic :: Software Development" ], )
import os from setuptools import setup, find_packages setup(name='Coffin', version=".".join(map(str, __import__("coffin").__version__)), description='Jinja2 adapter for Django', author='Christopher D. Leary', author_email='cdleary@gmail.com', maintainer='David Cramer', maintainer_email='dcramer@gmail.com', url='http://github.com/dcramer/coffin', packages=find_packages(), #install_requires=['Jinja2', 'django>=1.2'], classifiers=[ "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "Operating System :: OS Independent", "Topic :: Software Development" ], )
Revert "Update example workflow to show you can use classes" This reverts commit dbce79102efa8fee233af95939f1ff0b9d060b00.
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 @activity.with_attributes(task_list='quickstart', version='example') def delay(t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' task_list = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(delay, t, y) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) futures.wait(yy, z) return z.result
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 # A simpleflow activity can be any callable, so a function works, but a class # will also work given the processing happens in __init__() @activity.with_attributes(task_list='quickstart', version='example') class Delay(object): def __init__(self, t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' task_list = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(Delay, t, y) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) futures.wait(yy, z) return z.result
Move around assertions as Ian talked about
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError as e: self.assertEqual(count.counter, 4) self.failIf('We wanted this to happen' not in str(e))
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError: pass finally: self.assertEqual(count.counter, 4)
Add JWT setting to seed
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SeedSettingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::table( 'settings' )->insert( [ [ 'key' => 'registration_open', 'value' => '0' ], [ 'key' => 'instance_title', 'value' => 'ROUTE-TO-PA' ], [ 'key' => 'api_check_jsonp_enable', 'value' => '1' ], [ 'key' => 'api_check_cors_enable', 'value' => '1' ], [ 'key' => 'fb_app_id', 'value' => '' ], [ 'key' => 'fb_app_secret', 'value' => '' ], [ 'key' => 'jwt_enable', 'value' => '0' ], [ 'key' => 'key_private', 'value' => '' ], [ 'key' => 'key_public', 'value' => '' ], ] ); } /** * Reverse the migrations. * * @return void */ public function down() { // } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SeedSettingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::table( 'settings' )->insert( [ [ 'key' => 'registration_open', 'value' => '0' ], [ 'key' => 'instance_title', 'value' => 'ROUTE-TO-PA' ], [ 'key' => 'api_check_jsonp_enable', 'value' => '1' ], [ 'key' => 'api_check_cors_enable', 'value' => '1' ], [ 'key' => 'fb_app_id', 'value' => '' ], [ 'key' => 'fb_app_secret', 'value' => '' ], ] ); } /** * Reverse the migrations. * * @return void */ public function down() { // } }
Fix nn_freemsg SIGSEGV on NULL nn_freemsg does not accept NULL argument (unlike libc free) and triggers SIGSEGV.
package nanomsg; import com.google.common.base.Preconditions; import com.sun.jna.Pointer; import java.nio.ByteBuffer; import static nanomsg.Error.check; import static nanomsg.Nanomsg.NANOMSG; public class Message implements AutoCloseable { private Pointer message; private final int size; Message(Pointer message, int size) { this.message = message; this.size = size; } @Override public synchronized void close() { if (message != null) { check(NANOMSG.nn_freemsg(message)); message = null; } } @Override protected void finalize() throws Throwable { close(); } public synchronized ByteBuffer getDirectByteBuffer() { Preconditions.checkState(message != null); return message.getByteBuffer(0, size); } public synchronized ByteBuffer getByteBuffer() { Preconditions.checkState(message != null); ByteBuffer buffer = getDirectByteBuffer(); ByteBuffer copy = ByteBuffer.allocate(buffer.remaining()); copy.put(buffer).flip(); return copy; } }
package nanomsg; import com.google.common.base.Preconditions; import com.sun.jna.Pointer; import java.nio.ByteBuffer; import static nanomsg.Error.check; import static nanomsg.Nanomsg.NANOMSG; public class Message implements AutoCloseable { private Pointer message; private final int size; Message(Pointer message, int size) { this.message = message; this.size = size; } @Override public synchronized void close() { check(NANOMSG.nn_freemsg(message)); message = null; } @Override protected void finalize() throws Throwable { close(); } public synchronized ByteBuffer getDirectByteBuffer() { Preconditions.checkState(message != null); return message.getByteBuffer(0, size); } public synchronized ByteBuffer getByteBuffer() { Preconditions.checkState(message != null); ByteBuffer buffer = getDirectByteBuffer(); ByteBuffer copy = ByteBuffer.allocate(buffer.remaining()); copy.put(buffer).flip(); return copy; } }
BAP-771: Extend APYJsFormValidationBundle to make it compatible with custom errors styles - fix test
<?php namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Oro\Bundle\JsFormValidationBundle\DependencyInjection\OroJsFormValidationExtension; class OroJsFormValidationExtensionTest extends \PHPUnit_Framework_TestCase { public function testLoad() { $container = new ContainerBuilder(); $extension = new OroJsFormValidationExtension(); $configs = array(array()); $extension->load($configs, $container); $this->assertTrue( $container->hasDefinition('jsfv.generator'), 'The jsfv.generator is overridden' ); } }
<?php namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Oro\Bundle\JsFormValidationBundle\DependencyInjection\OroJsFormValidationExtension; class OroJsFormValidationExtensionTest extends \PHPUnit_Framework_TestCase { public function testLoad() { $container = new ContainerBuilder(); $extension = new OroJsFormValidationExtension(); $configs = array(array()); $extension->load($configs, $container); $this->assertTrue( $container->hasDefinition('oro_jsfv.event_listener.load_constraints_listener'), 'The load constraints listener is loaded' ); } }
[MISC] Change the comment style for single line comments
var config = require('./Build/Config'); module.exports = function(grunt) { 'use strict'; // Display the execution time of grunt tasks require('time-grunt')(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require('load-grunt-configs')(grunt, { config : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask('default', ['compass:dev', 'jshint']); /** * Travis CI task * Replaces all replace strings with the standard meta data stored in the package.json * and tests all JS files with JSHint, this task is used by Travis CI. */ grunt.registerTask('travis', ['replace:init', 'jshint']); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks('Build/Grunt-Tasks'); };
var config = require('./Build/Config'); module.exports = function(grunt) { 'use strict'; // Display the execution time of grunt tasks require('time-grunt')(grunt); /** * Load all grunt-tasks in 'Build/Grunt-Options'. */ var gruntOptionsObj = require('load-grunt-configs')(grunt, { config : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); /** * Load all grunt-plugins that are specified in the 'package.json' file. */ require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask('default', ['compass:dev', 'jshint']); /** * Travis CI task * Replaces all replace strings with the standard meta data stored in the package.json * and tests all JS files with JSHint, this task is used by Travis CI. */ grunt.registerTask('travis', ['replace:init', 'jshint']); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks('Build/Grunt-Tasks'); };
Add LOK members to the team list
import * as actions from '../actions/StatusActions' import React from 'react' import TeamList from './TeamList' import TeamListItem from './TeamListItem' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' export const TeamPage = (props) => { let memberItems = props.region.members.map(member => { return ( <TeamListItem key={member.id} name={member.name} phone={member.phone} onClick={() => console.log(`name: ${member.name}`)} /> ) }) return ( <div> <h2 className="alt-header">{props.region.name}</h2> {memberItems} <TeamList teams={props.region.teams}/> </div> ) } TeamPage.propTypes = { region: React.PropTypes.object, } function mapStateToProps(state, ownProps) { let newState if (state.routing.locationBeforeTransitions) { return { region: state.routing.locationBeforeTransitions.state } } return { region: state.statusReducer.find(region => region.id === state.params.id) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(TeamPage)
import * as actions from '../actions/StatusActions' import React from 'react' import TeamList from './TeamList' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' export const TeamPage = (props) => { return ( <div> <h2 className="alt-header">{props.region.name}</h2> <TeamList teams={props.region.teams}/> </div> ) } TeamPage.propTypes = { region: React.PropTypes.object, } function mapStateToProps(state, ownProps) { let newState if (state.routing.locationBeforeTransitions) { return { region: state.routing.locationBeforeTransitions.state } } return { region: state.statusReducer.find(region => region.id === state.params.id) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(TeamPage)
Update language to directive form
$(function() { // TODO: Add alternate between advanced and intro var topic = $('h1.docs-page-title').text(); var header = 'Master ' + topic; var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; var cta = 'Learn More'; var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + '<p class="ad-unit-text">' + body + '</p>' + '<a class="button ad-unit-button" href="' + link+ '">' + cta + '</a></div>'; $('#TOCAdUnit').html(html); });
var _kmq = _kmq || []; $(function() { // No need to do a timeout for default case, if KM times out just don't show ad. _kmq.push(function(){ // Set up the experiment (this is the meat and potatoes) var type = KM.ab("Foundation Docs Upsell Type", ["question", "directive"]); // TODO: Add alternate between advanced and intro var topic = $('h1.docs-page-title').text(); var header; if (type === 'directive') { header = 'Master ' + topic; } else { header = 'Struggling with ' + topic + '?'; } var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; var cta = 'Learn More'; var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + '<p class="ad-unit-text">' + body + '</p>' + '<a class="button ad-unit-button" href="' + link+ '">' + cta + '</a></div>'; $('#TOCAdUnit').html(html); }); });
Add uninstall into the build
module.exports = function(grunt) { "use strict"; var exec = require("child_process").exec, fs = require("fs"); grunt.initConfig({ compress : { main : { options : { archive : "./build/digexp-toolkit.zip" }, files : [{ expand : true, cwd : ".", src : ["install.cmd", "install.sh", "uninstall.cmd", "uninstall.sh", "readme.md", "wcm-design.tar.gz", "dashboard.tar.gz", "sp-server.tar.gz", "LICENSE", "NOTICE"], dest : "/", filter : "isFile" }] } } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.registerTask("default", []); grunt.registerTask("build", ["compress:main", "_build"]); /** * Builds the app */ grunt.registerTask("_build", function() { }); };
module.exports = function(grunt) { "use strict"; var exec = require("child_process").exec, fs = require("fs"); grunt.initConfig({ compress : { main : { options : { archive : "./build/digexp-toolkit.zip" }, files : [{ expand : true, cwd : ".", src : ["install.cmd", "install.sh", "readme.md", "wcm-design.tar.gz", "dashboard.tar.gz", "sp-server.tar.gz", "LICENSE", "NOTICE"], dest : "/", filter : "isFile" }] } } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.registerTask("default", []); grunt.registerTask("build", ["compress:main", "_build"]); /** * Builds the app */ grunt.registerTask("_build", function() { }); };
Improve log message when no CSRF token found Closes gh-10436
/* * Copyright 2002-2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.csrf; /** * Thrown when no expected {@link CsrfToken} is found but is required. * * @author Rob Winch * @since 3.2 */ @SuppressWarnings("serial") public class MissingCsrfTokenException extends CsrfException { public MissingCsrfTokenException(String actualToken) { super("Could not verify the provided CSRF token because no token was found to compare."); } }
/* * Copyright 2002-2013 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.csrf; /** * Thrown when no expected {@link CsrfToken} is found but is required. * * @author Rob Winch * @since 3.2 */ @SuppressWarnings("serial") public class MissingCsrfTokenException extends CsrfException { public MissingCsrfTokenException(String actualToken) { super("Could not verify the provided CSRF token because your session was not found."); } }
Convert OMDB scrapper to grab xml
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # xml and saves a copy for later import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # JSON and saves a copy for later import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile)
Fix the test case for npm 1.0
var fs = require('fs'); var http = require('http-stack'); var assert = require('assert'); var icecast = require('../'); exports['test 4EverFloyd-1.dump'] = function() { var stream = fs.createReadStream(__dirname + "/dumps/4EverFloyd-1.dump"); var req = new http.HttpRequestStack(stream); req.on('response', onResponse); function onResponse(res) { assert.ok(res.headers); assert.equal(res.headers['icy-metaint'], 8192); var ice = new icecast.IcecastReadStack(req, res.headers['icy-metaint']); ice.on('metadata', onMetadata); ice.on('end', onEnd); } var metadataCount = 0; function onMetadata(title) { metadataCount++; var parsed = icecast.parseMetadata(title); assert.equal(parsed.StreamTitle, 'Shine on You Crazy Diamond, Pts. 1-5 - Shine on You Crazy Diamond, Pts. 1-5'); assert.equal(parsed.StreamUrl, 'http:\/\/www.4EverFloyd.com'); } function onEnd() { assert.equal(metadataCount, 1); } }
var fs = require('fs'); var http = require('http-stack'); var assert = require('assert'); var icecast = require('icecast-stack'); exports['test 4EverFloyd-1.dump'] = function() { var stream = fs.createReadStream(__dirname + "/dumps/4EverFloyd-1.dump"); var req = new http.HttpRequestStack(stream); req.on('response', onResponse); function onResponse(res) { assert.ok(res.headers); assert.equal(res.headers['icy-metaint'], 8192); var ice = new icecast.IcecastReadStack(req, res.headers['icy-metaint']); ice.on('metadata', onMetadata); ice.on('end', onEnd); } var metadataCount = 0; function onMetadata(title) { metadataCount++; var parsed = icecast.parseMetadata(title); assert.equal(parsed.StreamTitle, 'Shine on You Crazy Diamond, Pts. 1-5 - Shine on You Crazy Diamond, Pts. 1-5'); assert.equal(parsed.StreamUrl, 'http:\/\/www.4EverFloyd.com'); } function onEnd() { assert.equal(metadataCount, 1); } }
Improve code style, fix JSDoc annotation
'use strict'; // FUNCTIONS // var ln = Math.log; // WEIGHT TF-IDF // /** * Weights a document-term matrix (stored as an array-of-arrays) by * term frequency - inverse document frequency. * * @param {Array} dtm - input document-term matrix (array-of-arrays) * @returns {Array} mutated document-term matrix object (array-of-arrays) */ function weightTfIdf( dtm ) { var word_doc_freq = []; var count; var word; var doc; var idf; var d; var w; for ( w = 0; w < dtm[0].length; w++ ) { count = 0; for ( d = 0; d < dtm.length; d++ ) { if ( dtm[d][w] !== undefined && dtm[d][w] > 0 ) { count++; } } word_doc_freq.push( count ); } for ( doc = 0; doc < dtm.length; doc++ ) { for ( word = 0; word < dtm[0].length; word++ ){ idf = ln( dtm.length ) - ln( 1 + word_doc_freq[word] ); console.log( idf ) if ( dtm[doc][word] !== undefined ) { dtm[doc][word] = dtm[doc][word] * idf; } } } return dtm; } // end FUNCTION weightTfIdf() // EXPORTS // module.exports = weightTfIdf;
'use strict'; // FUNCTIONS // var ln = Math.log; // WEIGHT TF-IDF // /** * Weights a document-term matrix by * term frequency - inverse document frequency. * * @param {Object} dtm - input document-term matrix * @returns {Object} mutated document-term matrix object */ function weightTfIdf( dtm ) { var word_doc_freq = []; for ( var w = 0; w < dtm[0].length; w++ ) { var count = 0; for ( var d = 0; d < dtm.length; d++ ) { if ( dtm[d][w] !== undefined ) { count++; } } word_doc_freq.push( count ); } for ( var doc = 0; doc < dtm.length; doc++ ) { for ( var word = 0; word < dtm[0].length; word++ ){ var idf = ln( dtm.length ) - ln( 1 + word_doc_freq[word] ); if ( dtm[doc][word] !== undefined ) { dtm[doc][word] = dtm[doc][word] * idf; } } } return dtm; } // end FUNCTION weightTfIdf() // EXPORTS // module.exports = weightTfIdf;
Add routes for TOS and Copyright
{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <footer class="footer no-print"> <div class="footer__row"> <a class="footer__link" href="{{ route('wiki.show', ['page' => 'Legal/TOS']) }}" target="_blank">Terms of Service</a> <a class="footer__link" href="{{ route('wiki.show', ['page' => 'Legal/Copyright'])" target="_blank">Copyright (DMCA)</a> <a class="footer__link" href="{{ osu_url('status.server') }}" target="_blank">Server Status</a> <a class="footer__link" href="{{ osu_url('status.osustatus') }}" target="_blank">@osustatus</a> </div> <div class="footer__row">ppy powered 2007-{{ date('Y') }}</div> <div class="js-sync-height--target" data-sync-height-id="permanent-fixed-footer"></div> </footer>
{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <footer class="footer no-print"> <div class="footer__row"> <a class="footer__link" href="{{ osu_url('legal.tos') }}" target="_blank">Terms of Service</a> <a class="footer__link" href="{{ osu_url('legal.dmca') }}" target="_blank">Copyright (DMCA)</a> <a class="footer__link" href="{{ osu_url('status.server') }}" target="_blank">Server Status</a> <a class="footer__link" href="{{ osu_url('status.osustatus') }}" target="_blank">@osustatus</a> </div> <div class="footer__row">ppy powered 2007-{{ date('Y') }}</div> <div class="js-sync-height--target" data-sync-height-id="permanent-fixed-footer"></div> </footer>
Adjust javadocs as the usage has changed
/* * Copyright 2011 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.codec.frame; /** * An {@link Exception} which is thrown when the length of the frame * decoded is greater than the maximum. * * @apiviz.hidden */ public class TooLongFrameException extends Exception { private static final long serialVersionUID = -1995801950698951640L; /** * Creates a new instance. */ public TooLongFrameException() { super(); } /** * Creates a new instance. */ public TooLongFrameException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public TooLongFrameException(String message) { super(message); } /** * Creates a new instance. */ public TooLongFrameException(Throwable cause) { super(cause); } }
/* * Copyright 2011 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.codec.frame; /** * An {@link Exception} which is thrown when the length of the frame * decoded by {@link DelimiterBasedFrameDecoder} is greater than the maximum. * * @apiviz.hidden */ public class TooLongFrameException extends Exception { private static final long serialVersionUID = -1995801950698951640L; /** * Creates a new instance. */ public TooLongFrameException() { super(); } /** * Creates a new instance. */ public TooLongFrameException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public TooLongFrameException(String message) { super(message); } /** * Creates a new instance. */ public TooLongFrameException(Throwable cause) { super(cause); } }
Put favicon into separate function
<?php # Copyright © 2012 Martin Ueding <dev@martin-ueding.de> class BookmarkHelper extends AppHelper { var $helpers = array('Html'); function print_bookmark($that, $bookmark) { echo $that->favicon($bookmark); echo $that->Html->link($bookmark['title'], array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']), array('class' => 'bookmark_link', 'title' => $bookmark['url'])); echo ' '; echo $that->Html->link(__('View', true), array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']), array('class' => 'edit_option')); echo ' '; } function favicon($bookmark) { $html = ''; if (Configure::read('favicon.show')) { $html .= '<img width="16" height="16" src="data:image/ico;base64,' .$this->requestAction('/bookmarks/favicon/'.$bookmark['id']) .'" />'; $html .= ' '; } return $html; } }
<?php # Copyright © 2012 Martin Ueding <dev@martin-ueding.de> class BookmarkHelper extends AppHelper { var $helpers = array('Html'); function print_bookmark($that, $bookmark) { if (Configure::read('favicon.show')) { echo '<img width="16" height="16" src="data:image/ico;base64,' .$this->requestAction('/bookmarks/favicon/'.$bookmark['id']) .'" />'; echo ' '; } echo $that->Html->link($bookmark['title'], array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']), array('class' => 'bookmark_link', 'title' => $bookmark['url'])); echo ' '; echo $that->Html->link(__('View', true), array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']), array('class' => 'edit_option')); echo ' '; } }
Add test case of TalkAction - should dont to set nowtalking if call talk method
'use strict'; const chai = require('chai'); const {expect} = chai; const {sandbox} = require('sinon'); chai.use(require('sinon-chai')); describe('TalkAction', () => { let TalkAction, TalkStore; before(() => { sandbox.create(); TalkAction = require('../../app/actions/TalkAction'); }); beforeEach(() => { delete require.cache[require.resolve('../../app/stores/TalkStore')]; TalkStore = require('../../app/stores/TalkStore'); }); after(() => { sandbox.restore(); }); it('should be set nowtalking in store if called talk action', () => { TalkAction.talk('samplesamplesamplesample'); setTimeout(() => { expect(TalkStore.isTalkingNow()).to.be.equal(true); }, 400); }); it('should dont to set nowtalking in store if called talk action', () => { TalkAction.talk('/disconnect'); setTimeout(() => { expect(TalkStore.isTalkingNow()).to.be.equal(false); }, 400); }); });
'use strict'; const chai = require('chai'); const {expect} = chai; const {sandbox} = require('sinon'); chai.use(require('sinon-chai')); describe('TalkAction', () => { let TalkAction, TalkStore; before(() => { sandbox.create(); TalkAction = require('../../app/actions/TalkAction'); }); beforeEach(() => { delete require.cache[require.resolve('../../app/stores/TalkStore')]; TalkStore = require('../../app/stores/TalkStore'); }); after(() => { sandbox.restore(); }); it('should be set nowtalking in store if called talk action', () => { TalkAction.talk('sample'); setTimeout(() => { expect(TalkStore.isTalkingNow()).to.be.equal(true); }, 100); }); });
Fix cms_page field to have default value Otherwise when cms page is added via code it will fail with error 'Integrity constraint violation: 1048 Column 'show_in_navigation' cannot be null'
<?php /** * Raguvis CmsNavigation */ namespace Raguvis\CmsNavigation\Setup; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; class InstallSchema implements InstallSchemaInterface { /** * Add Include in navigation flag */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); $setup->getConnection()->addColumn( $setup->getTable('cms_page'), 'show_in_navigation', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, 'nullable' => false, 'comment' => 'Flag whether or not CMS page should be included in top navigation', 'default' => 0 ] ); $installer->endSetup(); } }
<?php /** * Raguvis CmsNavigation */ namespace Raguvis\CmsNavigation\Setup; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; class InstallSchema implements InstallSchemaInterface { /** * Add Include in navigation flag */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); $setup->getConnection()->addColumn( $setup->getTable('cms_page'), 'show_in_navigation', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, 'nullable' => false, 'comment' => 'Flag whether or not CMS page should be included in top navigation' ] ); $installer->endSetup(); } }
Add new line at the end of class
<?php /* * This file is part of the Active Collab Controller project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder; use ActiveCollab\Controller\ActionResultEncoder\ActionResultEncoderInterface; use Psr\Http\Message\ResponseInterface; class ScalarEncoder extends ValueEncoder { public function shouldEncode($value): bool { return is_scalar($value); } /** * @param ResponseInterface $response * @param ActionResultEncoderInterface $encoder * @param string $value * @return ResponseInterface */ public function encode(ResponseInterface $response, ActionResultEncoderInterface $encoder, $value): ResponseInterface { return $response->withBody($this->createBodyFromText($value)); } }
<?php /* * This file is part of the Active Collab Controller project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder; use ActiveCollab\Controller\ActionResultEncoder\ActionResultEncoderInterface; use Psr\Http\Message\ResponseInterface; class ScalarEncoder extends ValueEncoder { public function shouldEncode($value): bool { return is_scalar($value); } /** * @param ResponseInterface $response * @param ActionResultEncoderInterface $encoder * @param string $value * @return ResponseInterface */ public function encode(ResponseInterface $response, ActionResultEncoderInterface $encoder, $value): ResponseInterface { return $response->withBody($this->createBodyFromText($value)); } }
Add media URL (used to get the current channel)
package fr.bouyguestelecom.tv.openapi.secondscreen.apiutils; /** * @author Pierre-Etienne Cherière PCHERIER@bouyguestelecom.fr */ public class BboxApiUrl { public static final String USER_INTERFACE = "userinterface"; public static final String REMOTE_CONTROLLER = "remotecontroller"; public static final String SEND_KEY = USER_INTERFACE + "/" + REMOTE_CONTROLLER + "/key"; public static final String SEND_TEXT = USER_INTERFACE + "/" + REMOTE_CONTROLLER + "/text"; public static final String VOLUME = "volume"; public static final String MANAGE_VOLUME = USER_INTERFACE + "/" + VOLUME; public static final String APPLICATIONS = "applications"; public static final String APPLICATIONS_RUN = APPLICATIONS + "/run"; public static final String APPLICATIONS_REGISTER = APPLICATIONS + "/register"; public static final String SECURE_AUTH = "security/token"; public static final String SECURE_CONNECT = "security/sessionId"; public static final String NOTIFICATION = "notification"; public static final String PACKAGE_NAME = "packageName"; public static final String APP_NAME = "appName"; public static final String LOGO_URL = "logoUrl"; public static final String APP_ID = "appId"; public static final String APP_STATE = "appState"; public static final String MEDIA = "media"; }
package fr.bouyguestelecom.tv.openapi.secondscreen.apiutils; /** * @author Pierre-Etienne Cherière PCHERIER@bouyguestelecom.fr */ public class BboxApiUrl { public static final String USER_INTERFACE = "userinterface"; public static final String REMOTE_CONTROLLER = "remotecontroller"; public static final String SEND_KEY = USER_INTERFACE + "/" + REMOTE_CONTROLLER + "/key"; public static final String SEND_TEXT = USER_INTERFACE + "/" + REMOTE_CONTROLLER + "/text"; public static final String VOLUME = "volume"; public static final String MANAGE_VOLUME = USER_INTERFACE + "/" + VOLUME; public static final String APPLICATIONS = "applications"; public static final String APPLICATIONS_RUN = APPLICATIONS + "/run"; public static final String APPLICATIONS_REGISTER = APPLICATIONS + "/register"; public static final String SECURE_AUTH = "security/token"; public static final String SECURE_CONNECT = "security/sessionId"; public static final String NOTIFICATION = "notification"; public static final String PACKAGE_NAME = "packageName"; public static final String APP_NAME = "appName"; public static final String LOGO_URL = "logoUrl"; public static final String APP_ID = "appId"; public static final String APP_STATE = "appState"; }
Remove moderniz from the Block Header
define([ 'jQuery', ], function() { function Header() { this._$body = $('body'); this._$win = $(window); this._$header = $('.js-header'); }; Header.prototype.init = function() { //this.setStatus(); this.formInit(); } Header.prototype.setStatus = function() { var self = this; var checkIsXsmall = function() { if (self._$win.width() <= 768) { self._$header.removeClass('is-fixed'); self._$body.removeAttr('style'); return true; } } var update = function() { if(checkIsXsmall()) return; self._$header.addClass('is-fixed'); self._$body.css({'padding-top': self._$header.height() + 'px'}); } update(); self._$win.on('resize.header', function(){ update(); }); } Header.prototype.formInit = function() { console.log('form init'); } return Header; });
define([ 'Modernizr', 'jQuery', ], function() { function Header() { this._$body = $('body'); this._$win = $(window); this._$header = $('.js-header'); }; Header.prototype.init = function() { //this.setStatus(); this.formInit(); } Header.prototype.setStatus = function() { var self = this; var checkIsXsmall = function() { if (self._$win.width() <= 768) { self._$header.removeClass('is-fixed'); self._$body.removeAttr('style'); return true; } } var update = function() { if(checkIsXsmall()) return; self._$header.addClass('is-fixed'); self._$body.css({'padding-top': self._$header.height() + 'px'}); } update(); self._$win.on('resize.header', function(){ update(); }); } Header.prototype.formInit = function() { console.log('form init'); } return Header; });
Add equals() to the unit test to satisfy checkstyle
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.util; import static org.junit.Assert.*; import org.junit.Test; public class OpenHashSetTest { static class Value { @Override public int hashCode() { return 1; } @Override public boolean equals(Object o) { return this == o; } } @Test public void addRemoveCollision() { Value v1 = new Value(); Value v2 = new Value(); OpenHashSet<Value> set = new OpenHashSet<Value>(); assertTrue(set.add(v1)); assertFalse(set.add(v1)); assertFalse(set.remove(v2)); assertTrue(set.add(v2)); assertFalse(set.add(v2)); assertTrue(set.remove(v2)); assertFalse(set.remove(v2)); } }
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.util; import static org.junit.Assert.*; import org.junit.Test; public class OpenHashSetTest { static class Value { @Override public int hashCode() { return 1; } } @Test public void addRemoveCollision() { Value v1 = new Value(); Value v2 = new Value(); OpenHashSet<Value> set = new OpenHashSet<Value>(); assertTrue(set.add(v1)); assertFalse(set.add(v1)); assertFalse(set.remove(v2)); assertTrue(set.add(v2)); assertFalse(set.add(v2)); assertTrue(set.remove(v2)); assertFalse(set.remove(v2)); } }
Remove "Testing" as best word every time Signed-off-by: Reicher <d5b86a7882b5bcb4262a5e66c6cf4ed497795bc7@gmail.com>
MiniPanel = function (game, text, x, y) { Phaser.Group.call(this, game); var style = { font: "25px Arial", align: "center" }; this.label = game.add.text(x, y, text, style) this.label.anchor.setTo(0.5) var middle = this.game.add.tileSprite(x, y, this.label.width-50, 50, 'sprites', 'best-word-frame-middle'); middle.anchor.setTo(0.5) this.add(middle) var left = this.create(x+1-middle.width/2, y, 'sprites', 'best-word-frame-left') left.anchor.setTo(1, 0.5) var right = this.create(x-1+middle.width/2, y, 'sprites', 'best-word-frame-right') right.anchor.setTo(0, 0.5) this.add(this.label) } MiniPanel.prototype = Object.create(Phaser.Group.prototype) MiniPanel.prototype.constructor = MiniPanel MiniPanel.prototype.remove = function() { this.game.add.tween(this).to({alpha: 0}, 3000, Phaser.Easing.Quadratic.In, true); } MiniPanel.prototype.update = function(text) { }
MiniPanel = function (game, text, x, y) { Phaser.Group.call(this, game); text = "TESTING" var style = { font: "25px Arial", align: "center" }; this.label = game.add.text(x, y, text, style) this.label.anchor.setTo(0.5) var middle = this.game.add.tileSprite(x, y, this.label.width-50, 50, 'sprites', 'best-word-frame-middle'); middle.anchor.setTo(0.5) this.add(middle) var left = this.create(x+1-middle.width/2, y, 'sprites', 'best-word-frame-left') left.anchor.setTo(1, 0.5) var right = this.create(x-1+middle.width/2, y, 'sprites', 'best-word-frame-right') right.anchor.setTo(0, 0.5) this.add(this.label) } MiniPanel.prototype = Object.create(Phaser.Group.prototype) MiniPanel.prototype.constructor = MiniPanel MiniPanel.prototype.remove = function() { this.game.add.tween(this).to({alpha: 0}, 3000, Phaser.Easing.Quadratic.In, true); } MiniPanel.prototype.update = function(text) { }
Add __dirname var for browser.
/** This code is to be ran on client side * so that the browser can execute JS for node correctly. */ var inherits = function (ctor, superCtor) { /** See nodejs lib sys. */ var tempCtor = function(){}; tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; var stdio_stdout = { write: function(data) { data = data.replace(/\n/g, '<br />'); document.body.innerHTML += data; } }; process = { exit: function(){}, argv: ['-v', '-d'], browser: true, memoryUsage: function() {return 'Not available'}, stdout: stdio_stdout, stdio: stdio_stdout, binding: function() {return { writeError: function(data) {console.error(data)} }}, inherits: inherits }; __dirname = 'browser'; if(!Object.keys) { // The function is only defined in V8. Object.keys = function(obj) { var keys = new Array(); for(var key in obj) { keys.push(key); } return keys; } }
/** This code is to be ran on client side * so that the browser can execute JS for node correctly. */ var inherits = function (ctor, superCtor) { /** See nodejs lib sys. */ var tempCtor = function(){}; tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; var stdio_stdout = { write: function(data) { data = data.replace(/\n/g, '<br />'); document.body.innerHTML += data; } }; process = { exit: function(){}, argv: ['-v', '-d'], browser: true, memoryUsage: function() {return 'Not available'}, stdout: stdio_stdout, stdio: stdio_stdout, binding: function() {return { writeError: function(data) {console.error(data)} }}, inherits: inherits }; if(!Object.keys) { // The function is only defined in V8. Object.keys = function(obj) { var keys = new Array(); for(var key in obj) { keys.push(key); } return keys; } }
Undo - some expectation expects this port.
'use strict'; var express = require('express'), constants = require('../../app/config/constants'), config = require('../../app/config/config'), should = require('should'), cookieParser = require('cookie-parser'), routes = require('../../app/routes'), request = require('supertest')('http://localhost:3000'); describe('Local routing', function(){ var server; beforeEach(function(){ var app = express(); app.use(cookieParser()); app.use(constants.LOCAL_PATH, routes.local); server = app.listen(3000); }); afterEach(function(){ server.close(); }); it('should return local config object', function(done){ request .get(constants.LOCAL_PATH + constants.CLIENT_CONFIG_PATH) .expect(200, function(err, res){ should.not.exist(err); should(res.body).containDeep(config.clientConfig); done(); }); }); it('should remove acces_token cookie', function(done){ request .get(constants.LOCAL_PATH + constants.SIGN_OUT_PATH) .expect('set-cookie', /access_token=; Path=\/api;/) .expect(200, done); }); });
'use strict'; var express = require('express'), constants = require('../../app/config/constants'), config = require('../../app/config/config'), should = require('should'), cookieParser = require('cookie-parser'), routes = require('../../app/routes'), request = require('supertest')('http://localhost:3000'); describe('Local routing', function(){ var server; beforeEach(function(){ var app = express(); app.use(cookieParser()); app.use(constants.LOCAL_PATH, routes.local); server = app.listen(3005); }); afterEach(function(){ server.close(); }); it('should return local config object', function(done){ request .get(constants.LOCAL_PATH + constants.CLIENT_CONFIG_PATH) .expect(200, function(err, res){ should.not.exist(err); should(res.body).containDeep(config.clientConfig); done(); }); }); it('should remove acces_token cookie', function(done){ request .get(constants.LOCAL_PATH + constants.SIGN_OUT_PATH) .expect('set-cookie', /access_token=; Path=\/api;/) .expect(200, done); }); });
USe safe on collection iteration
package alien4cloud.tosca.serializer; import java.util.Set; import org.alien4cloud.tosca.model.CSARDependency; import static alien4cloud.utils.AlienUtils.safe; /** * A {@code ToscaImportsUtils} is a helper class that generates TOSCA imports. * * @author Loic Albertin */ public class ToscaImportsUtils { public static String generateImports(Set<CSARDependency> dependencies) { StringBuilder sb = new StringBuilder(); safe(dependencies).forEach(d -> { if (sb.length() != 0) { sb.append("\n"); } sb.append(" - "); sb.append(d.getName()); sb.append(":"); sb.append(d.getVersion()); }); return sb.toString(); } }
package alien4cloud.tosca.serializer; import java.util.Set; import org.alien4cloud.tosca.model.CSARDependency; /** * A {@code ToscaImportsUtils} is a helper class that generates TOSCA imports. * * @author Loic Albertin */ public class ToscaImportsUtils { public static String generateImports(Set<CSARDependency> dependencies) { StringBuilder sb = new StringBuilder(); dependencies.forEach(d -> { if (sb.length() != 0) { sb.append("\n"); } sb.append(" - "); sb.append(d.getName()); sb.append(":"); sb.append(d.getVersion()); }); return sb.toString(); } }
Clean up after sync integration tests
from ...testcases import DustyIntegrationTestCase from ...fixtures import busybox_single_app_bundle_fixture class TestSyncCLI(DustyIntegrationTestCase): def setUp(self): super(TestSyncCLI, self).setUp() busybox_single_app_bundle_fixture() self.run_command('bundles activate busyboxa') self.run_command('up') def tearDown(self): super(TestSyncCLI, self).tearDown() self.run_command('bundles deactivate busyboxa') try: self.run_command('stop') except Exception: pass def test_sync_repo(self): self.exec_in_container('busyboxa', 'rm -rf /repo') self.assertFileNotInContainer('busyboxa', '/repo/README.md') self.run_command('sync fake-repo') self.assertFileContentsInContainer('busyboxa', '/repo/README.md', '# fake-repo')
from mock import patch from ...testcases import DustyIntegrationTestCase from ...fixtures import busybox_single_app_bundle_fixture class TestSyncCLI(DustyIntegrationTestCase): def setUp(self): super(TestSyncCLI, self).setUp() busybox_single_app_bundle_fixture() self.run_command('bundles activate busyboxa') self.run_command('up') def test_sync_repo(self): self.exec_in_container('busyboxa', 'rm -rf /repo') self.assertFileNotInContainer('busyboxa', '/repo/README.md') self.run_command('sync fake-repo') self.assertFileContentsInContainer('busyboxa', '/repo/README.md', '# fake-repo')
Move comment to conditional block
var traceur = Npm.require('traceur'); Plugin.registerSourceHandler("next.js", function (compileStep) { var oldPath = compileStep.inputPath; var newPath = oldPath.replace(/\.next\.js$/, '.now.js'); var source = compileStep.read().toString('utf8'); var options = { filename: oldPath, sourceMap: true }; var output = traceur.compile(source, options); if (output.errors.length) { output.errors.forEach(function (err) { // errors are split into four parts var errorParts = err.split(/: */); var SOURCEPATH = 0; var LINE = 1; var COLUMN = 2; var MESSAGE = 3; // throw a plugin error compileStep.error({ message: errorParts[MESSAGE], sourcePath: errorParts[SOURCEPATH], line: parseInt(errorParts[LINE], 10) - 1, column: parseInt(errorParts[COLUMN], 10) + 1 }); }); } else { compileStep.addJavaScript({ sourcePath: oldPath, path: newPath, data: output.js, sourceMap: output.sourceMap }); } });
var traceur = Npm.require('traceur'); Plugin.registerSourceHandler("next.js", function (compileStep) { var oldPath = compileStep.inputPath; var newPath = oldPath.replace(/\.next\.js$/, '.now.js'); var source = compileStep.read().toString('utf8'); var options = { filename: oldPath, sourceMap: true }; var output = traceur.compile(source, options); // errors are split into four parts if (output.errors.length) { output.errors.forEach(function (err) { var errorParts = err.split(/: */); var SOURCEPATH = 0; var LINE = 1; var COLUMN = 2; var MESSAGE = 3; // throw a plugin error compileStep.error({ message: errorParts[MESSAGE], sourcePath: errorParts[SOURCEPATH], line: parseInt(errorParts[LINE], 10) - 1, column: parseInt(errorParts[COLUMN], 10) + 1 }); }); } else { compileStep.addJavaScript({ sourcePath: oldPath, path: newPath, data: output.js, sourceMap: output.sourceMap }); } });
Replace golang.org link with godoc.org link [skip ci]
package async import ( "container/list" "sync" ) /* Used to contain the Routine functions to be processed This list inherits https://godoc.org/container/list and contains all of the functionality that it contains, with a minor tweak to Remove. Instead of Remove returning the element, it returns our routine. This is used to ensure that our Routine is removed from the list before it's ran, and therefore isn't able to be called again. */ type List struct { *list.List Wait sync.WaitGroup } /* Create a new list */ func New() *List { return &List{ List: list.New(), } } /* Add a Routine function to the current list */ func (l *List) Add(routine Routine) (*List, *list.Element) { element := l.PushBack(routine) return l, element } /* Add multiple Routine functions to the current list */ func (l *List) Multiple(routines ...Routine) (*List, []*list.Element) { var ( elements = make([]*list.Element, 0) ) for i := 0; i < len(routines); i++ { _, e := l.Add(routines[i]) elements = append(elements, e) } return l, elements } /* Remove an element from the current list */ func (l *List) Remove(element *list.Element) (*List, Routine) { routine := l.List.Remove(element).(Routine) return l, routine }
package async import ( "container/list" "sync" ) /* Used to contain the Routine functions to be processed This list inherits http://golang.org/pkg/container/list/ and contains all of the functionality that it contains, with a minor tweak to Remove. Instead of Remove returning the element, it returns our routine. This is used to ensure that our Routine is removed from the list before it's ran, and therefore isn't able to be called again. */ type List struct { *list.List Wait sync.WaitGroup } /* Create a new list */ func New() *List { return &List{ List: list.New(), } } /* Add a Routine function to the current list */ func (l *List) Add(routine Routine) (*List, *list.Element) { element := l.PushBack(routine) return l, element } /* Add multiple Routine functions to the current list */ func (l *List) Multiple(routines ...Routine) (*List, []*list.Element) { var ( elements = make([]*list.Element, 0) ) for i := 0; i < len(routines); i++ { _, e := l.Add(routines[i]) elements = append(elements, e) } return l, elements } /* Remove an element from the current list */ func (l *List) Remove(element *list.Element) (*List, Routine) { routine := l.List.Remove(element).(Routine) return l, routine }
Revert auth change made by @JavascriptFTW
var CJS = require("../backend/contest_judging_sys.js"); let fbAuth = CJS.fetchFirebaseAuth(); var createEntryHolder = function(entryData) { return $("<h5>").addClass("center").text(entryData.name); }; var setupPage = function() { CJS.loadXContestEntries("4688911017312256", function(response) { for (let entryId in response) { let thisEntry = response[entryId]; $("#entries").append(createEntryHolder(thisEntry)).append($("<div>").addClass("divider")); } }, 30); }; if (fbAuth === null) { CJS.authenticate(); } else { if (fbAuth === null) { $("#authBtn").text("Hello, guest! Click me to login."); } else { $("#authBtn").text(`Welcome, ${CJS.fetchFirebaseAuth().google.displayName}! (Not you? Click here)`); } setupPage(); } $("#authBtn").on("click", function(evt) { evt.preventDefault(); if (fbAuth === null) { CJS.authenticate(); } else { CJS.authenticate(true); } });
var CJS = require("../backend/contest_judging_sys.js"); let fbAuth = CJS.fetchFirebaseAuth(); var createEntryHolder = function(entryData) { return $("<h5>").addClass("center").text(entryData.name); }; var setupPage = function() { if (fbAuth === null) { $("#authBtn").text("Hello, guest! Click me to login."); } else { $("#authBtn").text(`Welcome, ${CJS.fetchFirebaseAuth().google.displayName}! (Not you? Click here)`); } CJS.loadXContestEntries("4688911017312256", function(response) { for (let entryId in response) { let thisEntry = response[entryId]; $("#entries").append(createEntryHolder(thisEntry)).append($("<div>").addClass("divider")); } }, 30); }; setupPage(); $("#authBtn").on("click", function(evt) { evt.preventDefault(); if (fbAuth === null) { CJS.authenticate(); } else { CJS.authenticate(true); } });
[proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
Test alias methods in a menu
<?php namespace Bluora\LaravelNavigationBuilder\Tests; use Bluora\LaravelNavigationBuilder\Collection; use Bluora\LaravelNavigationBuilder\Navigation; use PHPUnit\Framework\TestCase; class NavigationTest extends TestCase { /** * Assert that created object creates the correct output. */ public function testCreateMenu() { $navigation = new Navigation(); $menu = $navigation->createMenu('main'); $collection = (new Collection())->push($menu, 'main'); $this->assertEquals($navigation->getMenu('main'), $menu); $this->assertEquals($navigation->get('main'), $menu); $this->assertEquals($navigation->menu('main'), $menu); $this->assertEquals($navigation->getMenus()->values(), $collection->values()); } /** * Assert that created object creates the correct output. */ public function testCreateMenuWithCallback() { $navigation = new Navigation(); $menu = $navigation->createMenu('main', function ($menu) { $menu->add('Home'); }); $item = $menu->first(); $this->assertNotEquals($item, null); $this->assertEquals('Home', $item->title); $this->assertEquals('home', $item->nickname); } }
<?php namespace Bluora\LaravelNavigationBuilder\Tests; use Bluora\LaravelNavigationBuilder\Collection; use Bluora\LaravelNavigationBuilder\Navigation; use PHPUnit\Framework\TestCase; class NavigationTest extends TestCase { /** * Assert that created object creates the correct output. */ public function testCreateMenu() { $navigation = new Navigation(); $menu = $navigation->createMenu('main'); $collection = (new Collection())->push($menu, 'main'); $this->assertEquals($navigation->getMenu('main'), $menu); $this->assertEquals($navigation->getMenus()->values(), $collection->values()); } /** * Assert that created object creates the correct output. */ public function testCreateMenuWithCallback() { $navigation = new Navigation(); $menu = $navigation->createMenu('main', function ($menu) { $menu->add('Home'); }); $item = $menu->first(); $this->assertNotEquals($item, null); $this->assertEquals('Home', $item->title); $this->assertEquals('home', $item->nickname); } }
Set local path for Rocketeer commands
<?php namespace Rocketeer\Satellite\Abstracts; use Illuminate\Console\Command; use Rocketeer\Satellite\Services\Applications\ApplicationsManager; use Symfony\Component\Console\Input\InputArgument; class AbstractRocketeerCallerCommand extends Command { /** * @type ApplicationsManager */ protected $apps; /** * @param ApplicationsManager $apps */ public function __construct(ApplicationsManager $apps) { parent::__construct(); $this->apps = $apps; } /** * Call a Rocketeer command * * @param string $command */ public function callRocketeerCommand($command) { // Get application $app = $this->apps->getApplication($this->argument('app')); // Swap out Rocketeer's configuration foreach ($app->configuration as $key => $value) { $this->laravel['config']->set('rocketeer::'.$key, $value); } // Set local mode $this->laravel['path.base'] = $app->paths['current']; $this->laravel['rocketeer.rocketeer']->setLocal(true); // Call the deploy command $rocketeer = $this->laravel['rocketeer.console']; $rocketeer->call($command, [], $this->output); } /** * @return array */ protected function getArguments() { return array( ['app', InputArgument::REQUIRED, 'The application to deploy'], ); } }
<?php namespace Rocketeer\Satellite\Abstracts; use Illuminate\Console\Command; use Rocketeer\Satellite\Services\Applications\ApplicationsManager; use Symfony\Component\Console\Input\InputArgument; class AbstractRocketeerCallerCommand extends Command { /** * @type ApplicationsManager */ protected $apps; /** * @param ApplicationsManager $apps */ public function __construct(ApplicationsManager $apps) { parent::__construct(); $this->apps = $apps; } /** * Call a Rocketeer command * * @param string $command */ public function callRocketeerCommand($command) { // Get application $app = $this->apps->getApplication($this->argument('app')); // Swap out Rocketeer's configuration foreach ($app->configuration as $key => $value) { $this->laravel['config']->set('rocketeer::'.$key, $value); } // Set local mode $this->laravel['rocketeer.rocketeer']->setLocal(true); // Call the deploy command $rocketeer = $this->laravel['rocketeer.console']; $rocketeer->call($command, [], $this->output); } /** * @return array */ protected function getArguments() { return array( ['app', InputArgument::REQUIRED, 'The application to deploy'], ); } }
Strengthen PHP scorecard id validation
<?php function is_valid_scorecard_id($id) { if (!$id || preg_match('/\W/', $id) !== 0) { return false; } // These checks probably aren't necessary, but they shouldn't hurt, and // help check that the scorecards stay in the right directory. if (strstr($id, ".") !== false || strstr($id, "/") !== false) { return false; } return true; } function error($code) { if ($code === 400) { header('HTTP/1.1 400 Bad Request'); } else { header('HTTP/1.1 500 Internal Server Error'); } exit(); } if (!isset($_POST['json'])) { error(400); } $json = json_decode($_POST['json'], true); if ($json === NULL) { error(400); } $id = $json['id']; if (!is_valid_scorecard_id($id)) { error(400); } $json = json_encode($json, JSON_PRETTY_PRINT); $file = fopen("scores/$id", "w") or error(500); $write = fwrite($file, "$json\n"); fclose($file); if (!$write) { error(500); }
<?php function is_valid_scorecard_id($id) { if ($id === "" || preg_match('/\W/', $id) === 1) { return false; } return true; } function error($code) { if ($code === 400) { header('HTTP/1.1 400 Bad Request'); } else { header('HTTP/1.1 500 Internal Server Error'); } exit(); } if (!isset($_POST['json'])) { error(400); } $json = json_decode($_POST['json'], true); if ($json === NULL) { error(400); } $id = $json['id']; if (!is_valid_scorecard_id($id)) { error(400); } $json = json_encode($json, JSON_PRETTY_PRINT); $file = fopen("scores/$id", "w") or error(500); $write = fwrite($file, "$json\n"); fclose($file); if (!$write) { error(500); }
Include loader.css dependency in the build process
const normalize = require('path').normalize; const root = 'angular/'; module.exports = { appRoot: require('path').resolve(__dirname, '..'), assetsPath: 'public/assets/', src: { rootPath: root, typescript: normalize(root + '**/*.ts'), sass: { app: normalize(root + 'app/**/*.scss'), globals: normalize(root + 'globals.scss') }, views: normalize(root + 'app/**/*.html') }, dependencies: { js: [ 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/zone.js/dist/zone.js', 'node_modules/reflect-metadata/Reflect.js' ], css: [ 'node_modules/bootstrap/scss/bootstrap-flex.scss', 'node_modules/loaders.css/src/loaders.scss' ] } };
const normalize = require('path').normalize; const root = 'angular/'; module.exports = { appRoot: require('path').resolve(__dirname, '..'), assetsPath: 'public/assets/', src: { rootPath: root, typescript: normalize(root + '**/*.ts'), sass: { app: normalize(root + 'app/**/*.scss'), globals: normalize(root + 'globals.scss') }, views: normalize(root + 'app/**/*.html') }, dependencies: { js: [ 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/zone.js/dist/zone.js', 'node_modules/reflect-metadata/Reflect.js' ], css: [ 'node_modules/bootstrap/scss/bootstrap-flex.scss' ] } };
Remove News button from social bar
<div class="btn-group btn-group-sm" role="group" aria-label="Social Library Links"> <?php if ( !in_array($_SERVER['REMOTE_ADDR'],array('10.14.27.13','10.14.22.162','10.14.22.163')) ):?> <a class="btn btn-default" href="https://facebook.com/spokanelibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/facebook.png"></a> <a class="btn btn-default" href="https://twitter.com/spokanelibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/twitter.png"></a> <a class="btn btn-default" href="https://instagram.com/spokanepubliclibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/instagram.png"></a> <?php endif; ?> <a class="btn btn-default" href="http://spokaneisreading.org" title=""><b>Spokane Is Reading</b></a> <a class="btn btn-default" href="/signup/" title=""><b>Get a Library Card</b></a> <a class="btn btn-default" href="/support/" title=""><b class="">Support Your Library!</b></a> </div>
<div class="btn-group btn-group-sm" role="group" aria-label="Social Library Links"> <?php if ( !in_array($_SERVER['REMOTE_ADDR'],array('10.14.27.13','10.14.22.162','10.14.22.163')) ):?> <a class="btn btn-default" href="https://facebook.com/spokanelibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/facebook.png"></a> <a class="btn btn-default" href="https://twitter.com/spokanelibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/twitter.png"></a> <a class="btn btn-default" href="https://instagram.com/spokanepubliclibrary" title=""><img style="width:16px;" class="" src="/assets/img/icons/32px/instagram.png"></a> <?php endif; ?> <a class="btn btn-default" href="http://spokaneisreading.org" title=""><b>Spokane Is Reading</b></a> <a class="btn btn-default" href="/news/" title=""><b>News</b></a> <a class="btn btn-default" href="/signup/" title=""><b>Get a Library Card</b></a> <a class="btn btn-default" href="/support/" title=""><b class="">Support Your Library!</b></a> </div>
Return if single check exceeds timeout
package waitfor import ( "errors" "time" "golang.org/x/net/context" ) var ErrTimeoutExceeded = errors.New("timeout exceeded") type Check func() bool func ConditionWithTimeout(condition Check, interval, timeout time.Duration) error { errChan := make(chan error) ctx, _ := context.WithTimeout(context.Background(), timeout) go Condition(condition, interval, errChan, ctx) select { case err := <-errChan: return err case <-ctx.Done(): return ErrTimeoutExceeded } } func Condition(condition Check, interval time.Duration, errChan chan error, ctx context.Context) { if condition() { errChan <- nil return } for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-time.After(interval): if condition() { errChan <- nil return } } } }
package waitfor import ( "errors" "time" "golang.org/x/net/context" ) var ErrTimeoutExceeded = errors.New("timeout exceeded") type Check func() bool func ConditionWithTimeout(condition Check, interval, timeout time.Duration) error { errChan := make(chan error) ctx, _ := context.WithTimeout(context.Background(), timeout) go Condition(condition, interval, errChan, ctx) err := <-errChan if err == context.DeadlineExceeded { return ErrTimeoutExceeded } return err } func Condition(condition Check, interval time.Duration, errChan chan error, ctx context.Context) { if condition() { errChan <- nil return } for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-time.After(interval): if condition() { errChan <- nil return } } } }
Add worker emoji to subject
import os import boto3 import botocore.exceptions import logging import requests logger = logging.getLogger(__name__) def format_results_subject(cid, registry_action): '''Format the "subject" part of the harvesting message for results from the various processes. Results: [Action from Registry] on [Worker IP] for Collection ID [###] ''' if '{env}' in registry_action: registry_action = registry_action.format( env=os.environ.get('DATA_BRANCH')) resp = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4') worker_ip = resp.text worker_id = worker_ip.replace('.', '-') return 'Results: {} on :worker: {} for CID: {}'.format( registry_action, worker_id, cid) def publish_to_harvesting(subject, message): '''Publish a SNS message to the harvesting topic channel''' client = boto3.client('sns') # NOTE: this appears to raise exceptions if problem try: client.publish( TopicArn=os.environ['ARN_TOPIC_HARVESTING_REPORT'], Message=message, Subject=subject if len(subject) <= 100 else subject[:100] ) except botocore.exceptions.BotoCoreError, e: logger.error('Exception in Boto SNS: {}'.format(e))
import os import boto3 import botocore.exceptions import logging import requests logger = logging.getLogger(__name__) def format_results_subject(cid, registry_action): '''Format the "subject" part of the harvesting message for results from the various processes. Results: [Action from Registry] on [Worker IP] for Collection ID [###] ''' if '{env}' in registry_action: registry_action = registry_action.format( env=os.environ.get('DATA_BRANCH')) resp = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4') worker_ip = resp.text worker_id = worker_ip.replace('.', '-') return 'Results: {} on {} for CID: {}'.format( registry_action, worker_id, cid) def publish_to_harvesting(subject, message): '''Publish a SNS message to the harvesting topic channel''' client = boto3.client('sns') # NOTE: this appears to raise exceptions if problem try: client.publish( TopicArn=os.environ['ARN_TOPIC_HARVESTING_REPORT'], Message=message, Subject=subject if len(subject) <= 100 else subject[:100] ) except botocore.exceptions.BotoCoreError, e: logger.error('Exception in Boto SNS: {}'.format(e))
Update "Ctrl+Alt+Del" after site change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "https://cad-comic.com/category/ctrl-alt-del/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): # history_capable_date = "2002-10-23" history_capable_days = 20 schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): feed = self.parse_feed("https://cad-comic.com/feed/") for entry in feed.for_date(pub_date): url = entry.summary.src("img") title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "http://www.cad-comic.com/cad/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): history_capable_date = "2002-10-23" schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): page = self.parse_page( "http://www.cad-comic.com/cad/%s" % pub_date.strftime("%Y%m%d") ) url = page.src('img[src*="/comics/"]') title = page.alt('img[src*="/comics/"]') return CrawlerImage(url, title)
Fix flatatt import path for Django 1.9
from django import forms from django.template.loader import render_to_string from django.utils.encoding import force_text from django.utils.safestring import mark_safe try: from django.forms.utils import flatatt except ImportError: from django.forms.util import flatatt class RichTextEditorWidget(forms.Textarea): class Media: js = ('admin/js/ckeditor/ckeditor.js', 'admin/js/ckeditor/jquery-ckeditor.js') def render(self, name, value, attrs={}): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) return mark_safe(render_to_string('ckeditor/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': force_text(value), 'id': final_attrs['id'], }))
from django import forms from django.forms.util import flatatt from django.template.loader import render_to_string from django.utils.encoding import force_text from django.utils.safestring import mark_safe class RichTextEditorWidget(forms.Textarea): class Media: js = ('admin/js/ckeditor/ckeditor.js', 'admin/js/ckeditor/jquery-ckeditor.js') def render(self, name, value, attrs={}): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) return mark_safe(render_to_string('ckeditor/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': force_text(value), 'id': final_attrs['id'], }))
Add gulp-watch ability to auto build This way we don't forget to build as it will just watch the files and build when I change any file in helmsman
// Include gulp var gulp = require('gulp'), watch = require('gulp-watch'); // Include plugins var concat = require('gulp-concat'); // Concatenate JS Files gulp.task('scripts', function() { return watch(['app/bower_components/mousetrap/mousetrap.js', 'app/bower_components/angular-hotkeys/src/hotkeys.js', 'src/*.js'], {ignoreInitial: false}) .pipe(concat('helmsman.js')) .pipe(gulp.dest('build')); }); // Copy html files gulp.task('html', function() { return watch('src/*.html', {ignoreInitial: false}) .pipe(gulp.dest('build')); }); // Default Task gulp.task('default', ['scripts', 'html']);
// Include gulp var gulp = require('gulp'); // Include plugins var concat = require('gulp-concat'); // Concatenate JS Files gulp.task('scripts', function() { return gulp.src(['app/bower_components/mousetrap/mousetrap.js', 'app/bower_components/angular-hotkeys/src/hotkeys.js', 'src/*.js']) .pipe(concat('helmsman.js')) .pipe(gulp.dest('build')); }); // Copy html files gulp.task('html', function() { return gulp.src(['src/*.html']) .pipe(gulp.dest('build')); }); // Default Task gulp.task('default', ['scripts', 'html']);
Upgrade sendfile api to sendFile
/** * Main application routes */ 'use strict'; var errors = require('./components/errors'); var path = require('path'); module.exports = function(app) { // Insert routes below app.use('/api/helpForums', require('./api/helpForum')); app.use('/api/loggers', require('./api/logger')); app.use('/api/clis', require('./api/cli')); app.use('/api/topics', require('./api/topic')); app.use('/api/questions', require('./api/question')); app.use('/api/things', require('./api/thing')); app.use('/api/users', require('./api/user')); app.use('/auth', require('./auth')); // All undefined asset or api routes should return a 404 app.route('/:url(api|auth|components|app|bower_components|assets)/*') .get(errors[404]); // All other routes should redirect to the index.html app.route('/*') .get(function(req, res) { res.sendFile(path.join(app.get('appPath'), 'index.html')); }); };
/** * Main application routes */ 'use strict'; var errors = require('./components/errors'); module.exports = function(app) { // Insert routes below app.use('/api/helpForums', require('./api/helpForum')); app.use('/api/loggers', require('./api/logger')); app.use('/api/clis', require('./api/cli')); app.use('/api/topics', require('./api/topic')); app.use('/api/questions', require('./api/question')); app.use('/api/things', require('./api/thing')); app.use('/api/users', require('./api/user')); app.use('/auth', require('./auth')); // All undefined asset or api routes should return a 404 app.route('/:url(api|auth|components|app|bower_components|assets)/*') .get(errors[404]); // All other routes should redirect to the index.html app.route('/*') .get(function(req, res) { res.sendfile(app.get('appPath') + '/index.html'); }); };
Fix variable name in interface
<?php declare(strict_types=1); namespace SitemapPlugin\Model; use DateTimeInterface; use Doctrine\Common\Collections\Collection; interface UrlInterface { public function getLocation(): string; public function setLocation(string $location): void; public function getLastModification(): ?DateTimeInterface; public function setLastModification(DateTimeInterface $lastModification): void; public function getChangeFrequency(): string; public function setChangeFrequency(ChangeFrequency $changeFrequency): void; public function getPriority(): ?float; public function setPriority(float $priority): void; /** * @return Collection|AlternativeUrlInterface[] */ public function getAlternatives(): Collection; /** * @param AlternativeUrlInterface[] $alternatives */ public function setAlternatives(iterable $alternatives): void; public function addAlternative(AlternativeUrlInterface $alternative): void; public function hasAlternative(AlternativeUrlInterface $alternative): bool; public function removeAlternative(AlternativeUrlInterface $alternative): void; public function hasAlternatives(): bool; /** * @return Collection|ImageInterface[] */ public function getImages(): Collection; /** * @param ImageInterface[] $images */ public function setImages(iterable $images): void; public function addImage(ImageInterface $image): void; public function hasImage(ImageInterface $image): bool; public function removeImage(ImageInterface $image): void; public function hasImages(): bool; }
<?php declare(strict_types=1); namespace SitemapPlugin\Model; use DateTimeInterface; use Doctrine\Common\Collections\Collection; interface UrlInterface { public function getLocation(): string; public function setLocation(string $location): void; public function getLastModification(): ?DateTimeInterface; public function setLastModification(DateTimeInterface $lastModification): void; public function getChangeFrequency(): string; public function setChangeFrequency(ChangeFrequency $changeFrequency): void; public function getPriority(): ?float; public function setPriority(float $priority): void; /** * @return Collection|AlternativeUrlInterface[] */ public function getAlternatives(): Collection; /** * @param AlternativeUrlInterface[] $alternatives */ public function setAlternatives(iterable $alternatives): void; public function addAlternative(AlternativeUrlInterface $image): void; public function hasAlternative(AlternativeUrlInterface $image): bool; public function removeAlternative(AlternativeUrlInterface $image): void; public function hasAlternatives(): bool; /** * @return Collection|ImageInterface[] */ public function getImages(): Collection; /** * @param ImageInterface[] $images */ public function setImages(iterable $images): void; public function addImage(ImageInterface $image): void; public function hasImage(ImageInterface $image): bool; public function removeImage(ImageInterface $image): void; public function hasImages(): bool; }
Allow make_zipfile() to clobber the destination file
# # The OpenDiamond Platform for Interactive Search # Version 5 # # Copyright (c) 2011 Carnegie Mellon University # All rights reserved. # # This software is distributed under the terms of the Eclipse Public # License, Version 1.0 which can be found in the file named LICENSE. # ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES # RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT # import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
# # The OpenDiamond Platform for Interactive Search # Version 5 # # Copyright (c) 2011 Carnegie Mellon University # All rights reserved. # # This software is distributed under the terms of the Eclipse Public # License, Version 1.0 which can be found in the file named LICENSE. # ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES # RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT # import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' if os.path.exists(path): raise Exception("Refusing to clobber destination file") zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
Return null if bkn API result is null
var request = require("request"); var cheerio = require("cheerio"); var URL = "http://www.bkn.go.id/profil-pns"; var bknScrapper = function() { } bknScrapper.prototype.getData = function(id, cb) { var form = { nip: id }; request.post(URL, { form : form}, function(err, resp, body) { var data = {}; if (!body) { return cb(null); } var $ = cheerio.load(body); var entry = $("div.pns-row"); entry.each(function(i, e) { var key = $(e).find(".label").text(); var value = $(e).find(".value").text(); value = value.replace(": ", ""); value = value.replace(/ {2,}/g, ""); data[key] = value; }); cb(data); }) } module.exports = bknScrapper;
var request = require("request"); var cheerio = require("cheerio"); var URL = "http://www.bkn.go.id/profil-pns"; var bknScrapper = function() { } bknScrapper.prototype.getData = function(id, cb) { var form = { nip: id }; request.post(URL, { form : form}, function(err, resp, body) { var data = {}; var $ = cheerio.load(body); var entry = $("div.pns-row"); entry.each(function(i, e) { var key = $(e).find(".label").text(); var value = $(e).find(".value").text(); value = value.replace(": ", ""); value = value.replace(/ {2,}/g, ""); data[key] = value; }); cb(data); }) } module.exports = bknScrapper;
Add cheat mode numbers back to cells, fix mismatch in animation times
import React, { Component } from 'react'; import { CSSTransitionGroup } from 'react-transition-group'; import './Cell.css'; class Cell extends Component { color() { if (this.props.value === 1) { return 'blue'; } else if (this.props.value === 2) { return 'black'; } else { return 'red'; } } render() { const { onClickCell, value, cycle } = this.props; return ( <CSSTransitionGroup component="div" className="Cell" onClick={onClickCell} transitionName="Cell-flip" transitionEnterTimeout={300} transitionLeaveTimeout={300} > <div className="Cell-flipper" key={value}> <div className="Cell-panel" style={{ backgroundColor: this.color() }}> <p style={{ color: 'white' }}> {cycle} </p> </div> </div> </CSSTransitionGroup> ); } } export default Cell;
import React, { Component } from 'react'; import { CSSTransitionGroup } from 'react-transition-group'; import './Cell.css'; class Cell extends Component { color() { if (this.props.value === 1) { return 'blue'; } else if (this.props.value === 2) { return 'black'; } else { return 'red'; } } render() { const { onClickCell, value, cycle } = this.props; return ( <CSSTransitionGroup component="div" className="Cell" onClick={onClickCell} transitionName="Cell-flip" transitionEnterTimeout={500} transitionLeaveTimeout={500} > <div className="Cell-flipper" key={value}> <div className="Cell-panel" style={{ backgroundColor: this.color() }} /> </div> </CSSTransitionGroup> ); } } export default Cell; // <p style={{ color: 'green' }}> // {cycle} // </p>
Tweak up timeout in UDP test
import contextlib, queue, time, unittest from bibliopixel.util import udp TEST_ADDRESS = '127.0.0.1', 5678 TIMEOUT = 0.3 @contextlib.contextmanager def receive_udp(address, results): receiver = udp.QueuedReceiver(address) receiver.start() yield try: while True: results.append(receiver.queue.get(timeout=TIMEOUT)) except queue.Empty: pass class UDPTest(unittest.TestCase): def test_full(self): messages = [s.encode() for s in ('foo', '', 'bar', 'baz', '', 'bing')] expected = [s for s in messages if s] # Note that empty messages are either not sent, or not received. actual = [] with receive_udp(TEST_ADDRESS, actual): sender = udp.QueuedSender(TEST_ADDRESS) sender.start() for m in messages: sender.send(m) self.assertEquals(actual, expected)
import contextlib, queue, time, unittest from bibliopixel.util import udp TEST_ADDRESS = '127.0.0.1', 5678 TIMEOUT = 0.2 @contextlib.contextmanager def receive_udp(address, results): receiver = udp.QueuedReceiver(address) receiver.start() yield try: while True: results.append(receiver.queue.get(timeout=TIMEOUT)) except queue.Empty: pass class UDPTest(unittest.TestCase): def test_full(self): messages = [s.encode() for s in ('foo', '', 'bar', 'baz', '', 'bing')] expected = [s for s in messages if s] # Note that empty messages are either not sent, or not received. actual = [] with receive_udp(TEST_ADDRESS, actual): sender = udp.QueuedSender(TEST_ADDRESS) sender.start() for m in messages: sender.send(m) self.assertEquals(actual, expected)
Test does not have to fail under windows
import unittest import sys from sos_notebook.test_utils import sos_kernel from ipykernel.tests.utils import execute, wait_for_idle, assemble_output class TestSoSKernel(unittest.TestCase): def testKernel(self): with sos_kernel() as kc: execute(kc=kc, code='a = 1') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stdout.strip(), '', f'Stdout is not empty, "{stdout}" received') self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received') execute(kc=kc, code='%use Bash\n%get a\necho $a') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received') self.assertEqual(stdout.strip(), '1', f'Stdout should be 1, "{stdout}" received') if __name__ == '__main__': unittest.main()
import unittest import sys from sos_notebook.test_utils import sos_kernel from ipykernel.tests.utils import execute, wait_for_idle, assemble_output @unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32') class TestSoSKernel(unittest.TestCase): def testKernel(self): with sos_kernel() as kc: execute(kc=kc, code='a = 1') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stdout.strip(), '', f'Stdout is not empty, "{stdout}" received') self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received') execute(kc=kc, code='%use Bash\n%get a\necho $a') stdout, stderr = assemble_output(kc.iopub_channel) self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received') self.assertEqual(stdout.strip(), '1', f'Stdout should be 1, "{stdout}" received') if __name__ == '__main__': unittest.main()
Fix the array key name
<?php namespace Casinelli\CampaignMonitor; class CampaignMonitor { protected $app; public function __construct($app) { $this->app = $app; } public function campaigns($campaignId = null) { return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens()); } public function clients($clientId = null) { return new \CS_REST_Clients($clientId, $this->getAuthTokens()); } public function lists($listId = null) { return new \CS_REST_Lists($listId, $this->getAuthTokens()); } public function segments($segmentId = null) { return new \CS_REST_Segments($segmentId, $this->getAuthTokens()); } public function template($templateId = null) { return new \CS_REST_Templates($templateId, $this->getAuthTokens()); } public function subscribers($listId = null) { return new \CS_REST_Subscribers($listId, $this->getAuthTokens()); } protected function getAuthTokens() { return [ 'api_key' => $this->app['config']['campaignmonitor.api_key'], ]; } }
<?php namespace Casinelli\CampaignMonitor; class CampaignMonitor { protected $app; public function __construct($app) { $this->app = $app; } public function campaigns($campaignId = null) { return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens()); } public function clients($clientId = null) { return new \CS_REST_Clients($clientId, $this->getAuthTokens()); } public function lists($listId = null) { return new \CS_REST_Lists($listId, $this->getAuthTokens()); } public function segments($segmentId = null) { return new \CS_REST_Segments($segmentId, $this->getAuthTokens()); } public function template($templateId = null) { return new \CS_REST_Templates($templateId, $this->getAuthTokens()); } public function subscribers($listId = null) { return new \CS_REST_Subscribers($listId, $this->getAuthTokens()); } protected function getAuthTokens() { return [ 'apy_key' => $this->app['config']['campaignmonitor.api_key'], ]; } }
Fix dimension id read from login packet. This was working only because of pure luck, but that explains problems with players logging in non in overworld dimension.
package protocolsupport.protocol.packet.middle.clientbound.play; import protocolsupport.api.tab.TabAPI; import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket; import protocolsupport.protocol.serializer.PacketDataSerializer; import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedPlayer; public abstract class MiddleLogin<T> extends ClientBoundMiddlePacket<T> { protected int playerEntityId; protected int gamemode; protected int dimension; protected int difficulty; protected int maxplayers; protected String leveltype; protected boolean reducedDebugInfo; @Override public void readFromServerData(PacketDataSerializer serializer) { playerEntityId = serializer.readInt(); gamemode = serializer.readByte(); dimension = serializer.readInt(); difficulty = serializer.readByte(); serializer.readByte(); maxplayers = TabAPI.getMaxTabSize(); leveltype = serializer.readString(16); reducedDebugInfo = serializer.readBoolean(); } @Override public void handle() { storage.addWatchedSelfPlayer(new WatchedPlayer(playerEntityId)); storage.setDimensionId(dimension); } }
package protocolsupport.protocol.packet.middle.clientbound.play; import protocolsupport.api.tab.TabAPI; import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket; import protocolsupport.protocol.serializer.PacketDataSerializer; import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedPlayer; public abstract class MiddleLogin<T> extends ClientBoundMiddlePacket<T> { protected int playerEntityId; protected int gamemode; protected int dimension; protected int difficulty; protected int maxplayers; protected String leveltype; protected boolean reducedDebugInfo; @Override public void readFromServerData(PacketDataSerializer serializer) { playerEntityId = serializer.readInt(); gamemode = serializer.readByte(); dimension = serializer.readByte(); difficulty = serializer.readByte(); serializer.readByte(); maxplayers = TabAPI.getMaxTabSize(); leveltype = serializer.readString(16); reducedDebugInfo = serializer.readBoolean(); } @Override public void handle() { storage.addWatchedSelfPlayer(new WatchedPlayer(playerEntityId)); storage.setDimensionId(dimension); } }
Add constant SUID and minor reformatting svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=410563
/* Copyright 1998, 2002 The Apache Software Foundation or its licensors, as applicable * * 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 java.util.zip; /** * DataFormatException is used to indicate an error in the format of a * particular data stream. */ public class DataFormatException extends Exception { private static final long serialVersionUID = 2219632870893641452L; /** * Constructs a new instance of this class with its walkback filled in. * */ public DataFormatException() { super(); } /** * Constructs a new instance of this class with its walkback and message * filled in. * * @param detailMessage * String The detail message for the exception. */ public DataFormatException(String detailMessage) { super(detailMessage); } }
/* Copyright 1998, 2002 The Apache Software Foundation or its licensors, as applicable * * 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 java.util.zip; /** * DataFormatException is used to indicate an error in the format of a * particular data stream. */ public class DataFormatException extends Exception { /** * Constructs a new instance of this class with its walkback filled in. * */ public DataFormatException() { super(); } /** * Constructs a new instance of this class with its walkback and message * filled in. * * @param detailMessage * String The detail message for the exception. */ public DataFormatException(String detailMessage) { super(detailMessage); } }
Add possibility to override available templates list
<?php namespace Distilleries\LayoutManager\Forms; use App\Helpers\StaticLabel; use Distilleries\FormBuilder\FormValidator; class TemplatableForm extends FormValidator { public static $rules = []; public static $rules_update = null; public function buildForm() { $options = [ 'templatable' => $this->model, 'categories' => [], 'custom-tags' => [], ]; if (array_get($this->formOptions, 'categories')) { $options['categories'] = $this->formOptions['categories']; } if (array_get($this->formOptions, 'templates')) { $options['templates'] = $this->formOptions['templates']; } if (array_get($this->formOptions, 'custom-tags')) { $options['custom-tags'] = $this->formOptions['custom-tags']; } $this ->add('templates', 'template', $options); } }
<?php namespace Distilleries\LayoutManager\Forms; use App\Helpers\StaticLabel; use Distilleries\FormBuilder\FormValidator; class TemplatableForm extends FormValidator { public static $rules = []; public static $rules_update = null; public function buildForm() { $options = [ 'templatable' => $this->model, 'categories' => [], 'custom-tags' => [], ]; if (array_get($this->formOptions, 'categories')) { $options['categories'] = (array_pull($this->formOptions, 'categories')); } if (array_get($this->formOptions, 'custom-tags')) { $options['custom-tags'] = (array_pull($this->formOptions, 'custom-tags')); } $this ->add('templates', 'template', $options); } }
Build slim response from captured output buffer
<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App; $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->get('/macon[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/united-states/macon-ga'); }); $app->get('/canada/oshawa[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/canada/durham-region'); }); $app->get('/canada/whitby[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/canada/durham-region'); }); $app->any('/[{path:.*}]', function(Request $req, Response $res) { ob_start(); // Loads the c5 Environment and Template require_once __DIR__ . '/concrete5/web/router.php'; return $res->getBody()->write(ob_get_clean()); } ); $app->run();
<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App; $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $response; }); $app->get('/macon[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/united-states/macon-ga'); }); $app->get('/canada/oshawa[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/canada/durham-region'); }); $app->get('/canada/whitby[/]', function (Request $req, Response $res) { return $res->withStatus(302)->withHeader('Location', '/canada/durham-region'); }); $app->any('/[{path:.*}]', function(Request $req, Response $res) { // Loads the c5 Environment and Template require_once __DIR__ . '/concrete5/web/router.php'; } ); $app->run();
Correct the comment of BLOCKSIZE
#!/usr/env python # -*- coding: utf-8 -*- """Convert file codecs Usage: convert_codecs.py <sourceFile> <targetFile> <sourceEncoding> <targetEncoding> convert_codecs.py (-h | --help) """ import codecs from docopt import docopt __version__ = '0.1' __author__ = 'Honghe' BLOCKSIZE = 1024 # number of characters in corresponding encoding, not bytes def convert(sourceFile, targetFile, sourceEncoding, targetEncoding): with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile: with codecs.open(targetFile, 'wb', targetEncoding) as tfile: while True: contents = sfile.read(BLOCKSIZE) if not contents: break tfile.write(contents) if __name__ == '__main__': arguments = docopt(__doc__) sourceFile = arguments['<sourceFile>'] targetFile = arguments['<targetFile>'] sourceEncoding = arguments['<sourceEncoding>'] targetEncoding = arguments['<targetEncoding>'] convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
#!/usr/env python # -*- coding: utf-8 -*- """Convert file codecs Usage: convert_codecs.py <sourceFile> <targetFile> <sourceEncoding> <targetEncoding> convert_codecs.py (-h | --help) """ import codecs from docopt import docopt __version__ = '0.1' __author__ = 'Honghe' BLOCKSIZE = 1024**2 # size in bytes def convert(sourceFile, targetFile, sourceEncoding, targetEncoding): with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile: with codecs.open(targetFile, 'wb', targetEncoding) as tfile: while True: contents = sfile.read(BLOCKSIZE) if not contents: break tfile.write(contents) if __name__ == '__main__': arguments = docopt(__doc__) sourceFile = arguments['<sourceFile>'] targetFile = arguments['<targetFile>'] sourceEncoding = arguments['<sourceEncoding>'] targetEncoding = arguments['<targetEncoding>'] convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
Add spaces to session timeout countdown
function remainingTime(timeElement, outputElement) { var now = new Date(), timeout = new Date(timeElement.dataset.time), timeRemaining = (timeout - now) / 1000, secondsRemaining = Math.floor(timeRemaining) % 60, minutesRemaining = Math.floor(timeRemaining / 60) outputElement.innerHTML = minutesRemaining + " minuter och " + secondsRemaining + " sekunder" } function setupBookingOverview() { Array.prototype.forEach.call( document.querySelectorAll(".fn-session-timeout"), function (element) { var timeElement = element.querySelector("time"), outputElement = element.querySelector(".fn-session-timeout-output") setInterval( function() { remainingTime(timeElement, outputElement) }, 1000 ) } ) } exports.setupBookingOverview = setupBookingOverview
function remainingTime(timeElement, outputElement) { var now = new Date(), timeout = new Date(timeElement.dataset.time), timeRemaining = (timeout - now) / 1000, secondsRemaining = Math.floor(timeRemaining) % 60, minutesRemaining = Math.floor(timeRemaining / 60) outputElement.innerHTML = minutesRemaining + "minuter och " + secondsRemaining + "sekunder" } function setupBookingOverview() { Array.prototype.forEach.call( document.querySelectorAll(".fn-session-timeout"), function (element) { var timeElement = element.querySelector("time"), outputElement = element.querySelector(".fn-session-timeout-output") setInterval( function() { remainingTime(timeElement, outputElement) }, 1000 ) } ) } exports.setupBookingOverview = setupBookingOverview
Rename Condorcet::addAlgos -> Condorcet::addMethod 3/3
<?php /* Condorcet PHP Class, with Schulze Methods and others ! Version: 0.94 By Julien Boudry - MIT LICENSE (Please read LICENSE.txt) https://github.com/julien-boudry/Condorcet */ namespace Condorcet; // Registering native Condorcet Methods implementation namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\Copeland'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\KemenyYoung'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\MinimaxWinning'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\MinimaxMargin'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\MinimaxOpposition'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\RankedPairs'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\SchulzeWinning'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\SchulzeMargin'); namespace\Condorcet::addMethod(__NAMESPACE__.'\\Algo\\Methods\\SchulzeRatio'); // Set the default Condorcet Class algorithm namespace\Condorcet::setDefaultMethod('Schulze');
<?php /* Condorcet PHP Class, with Schulze Methods and others ! Version: 0.94 By Julien Boudry - MIT LICENSE (Please read LICENSE.txt) https://github.com/julien-boudry/Condorcet */ namespace Condorcet; // Registering native Condorcet Methods implementation namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\Copeland'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\KemenyYoung'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\MinimaxWinning'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\MinimaxMargin'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\MinimaxOpposition'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\RankedPairs'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\SchulzeWinning'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\SchulzeMargin'); namespace\Condorcet::addAlgos(__NAMESPACE__.'\\Algo\\Methods\\SchulzeRatio'); // Set the default Condorcet Class algorithm namespace\Condorcet::setDefaultMethod('Schulze');
Remove require() to obsolete resolveWhen()
"use strict"; module.exports = { makeRandomAlphanumericalString: require("./source/make-random-alphanumerical-string"), addOneTimeListener: require("./source/add-one-time-listener"), noConcurrentCalls: require("./source/no-concurrent-calls"), repeatAsyncUntil: require("./source/repeat-async-until"), looselyMatches: require("./source/loosely-matches"), tryOrCrash: require("./source/try-or-crash"), methodify: require("./source/methodify"), delayed: require("./source/delayed"), delay: require("./source/delay") };
"use strict"; module.exports = { makeRandomAlphanumericalString: require("./source/make-random-alphanumerical-string"), addOneTimeListener: require("./source/add-one-time-listener"), noConcurrentCalls: require("./source/no-concurrent-calls"), repeatAsyncUntil: require("./source/repeat-async-until"), looselyMatches: require("./source/loosely-matches"), resolveWhen: require("./source/resolve-when"), tryOrCrash: require("./source/try-or-crash"), methodify: require("./source/methodify"), delayed: require("./source/delayed"), delay: require("./source/delay") };
GUACAMOLE-526: Remove debug console.log() from toArrayFilter().
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * A filter for transforming an object into an array of all non-inherited * property values. */ angular.module('index').filter('toArray', [function toArrayFactory() { return function toArrayFiter(input) { // If no object is available, just return an empty array if (!input) { return []; } return Object.keys(input).map(function fetchValueByKey(key) { return input[key]; }); }; }]);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * A filter for transforming an object into an array of all non-inherited * property values. */ angular.module('index').filter('toArray', [function toArrayFactory() { return function toArrayFiter(input) { console.log(input) // If no object is available, just return an empty array if (!input) { return []; } return Object.keys(input).map(function fetchValueByKey(key) { return input[key]; }); }; }]);
Check whether is null before checking if is integer
<?php /** * @license MIT * @license http://opensource.org/licenses/MIT */ namespace Slim\PDO\Clause; /** * Class LimitClause. * * @author Fabian de Laender <fabian@faapz.nl> */ class LimitClause extends ClauseContainer { /** * @var null */ private $limit = null; /** * @param int $number * @param int $offset */ public function limit($number, $offset = 0) { if (!is_int($number) || (!is_null($offset) && !is_int($offset))) { trigger_error('Expects parameters as integers', E_USER_ERROR); } if (!is_null($offset) && $offset >= 0) { $this->limit = intval($number).' OFFSET '.intval($offset); } elseif ($number >= 0) { $this->limit = intval($number); } } /** * @return string */ public function __toString() { if (is_null($this->limit)) { return ''; } return ' LIMIT '.$this->limit; } }
<?php /** * @license MIT * @license http://opensource.org/licenses/MIT */ namespace Slim\PDO\Clause; /** * Class LimitClause. * * @author Fabian de Laender <fabian@faapz.nl> */ class LimitClause extends ClauseContainer { /** * @var null */ private $limit = null; /** * @param int $number * @param int $offset */ public function limit($number, $offset = 0) { if (!is_int($number) || !is_int($offset)) { trigger_error('Expects parameters as integers', E_USER_ERROR); } if ($offset >= 0) { $this->limit = intval($number).' OFFSET '.intval($offset); } elseif ($number >= 0) { $this->limit = intval($number); } } /** * @return string */ public function __toString() { if (is_null($this->limit)) { return ''; } return ' LIMIT '.$this->limit; } }
[python] Send api-key through HTTP cookie.
import urllib import urllib2 __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) req = urllib2.Request(url) req.add_header('User-Agent', self.user_agent) if self.api_key: req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key) sock = urllib2.urlopen(req, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
import urllib __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClientOpener(urllib.FancyURLopener): version = __user_agent__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) opener = EpiDBClientOpener() sock = opener.open(url, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
Enable promisification regardless of initial scope `nano-blue` now promisifies regardless of the initial scope that it was called in.
'use strict'; var bluebird = require('bluebird'); var nano = require('nano'); var _ = require('lodash'); const blacklist = new Set(['use', 'scope']); /** * Promisifies the exposed functions on an object * Based on a similar function in `qano` * * @ref https://github.com/jclohmann/qano */ function deepPromisify(obj) { return _.transform(obj, function(promisifiedObj, value, key) { if (blacklist.has(key)) { promisifiedObj[key] = value; return; } if (typeof value === 'function') { promisifiedObj[key] = bluebird.promisify(value, obj); } else if (typeof value === 'object') { promisifiedObj[key] = deepPromisify(value); } else { promisifiedObj[key] = value; } }); } module.exports = function nanoblue() { var nanoP = deepPromisify(nano.apply(null, arguments)); // replace nano's docModule calls with a promisified version var originalDocModule = nanoP.use; nanoP.use = nanoP.scope = nanoP.db.use = nanoP.db.scope = function() { return deepPromisify(originalDocModule()); }; return nanoP; };
'use strict'; var bluebird = require('bluebird'); var nano = require('nano'); var _ = require('lodash'); const blacklist = new Set(['use']); /** * Promisifies the exposed functions on an object * Based on a similar function in `qano` * * @ref https://github.com/jclohmann/qano */ function deepPromisify(obj) { return _.transform(obj, function(promisifiedObj, value, key) { if (blacklist.has(key)) { promisifiedObj[key] = value; return; } if (typeof value === 'function') { promisifiedObj[key] = bluebird.promisify(value, obj); } else if (typeof value === 'object') { promisifiedObj[key] = deepPromisify(value); } else { promisifiedObj[key] = value; } }); } module.exports = function nanoblue() { return deepPromisify(nano.apply(null, arguments)); };
Refactor duplicate GET requests code
var models = require('../db/models.js'); var util = require('../core/utilities.js'); var reject = function(req, res, err) { util.log('RECEIVED a GET request', req.query); util.log('SENT error code to user', err); res.sendStatus(400); }; var resolve = function(req, res, success) { util.log('RECEIVED a GET request', req.query); util.log('SENT successful response to user', success); res.status(200); res.send(success); }; module.exports = function(router) { //{x: float, y: float, z: float} router.get('/messages', function (req, res) { models.retrieveMarks(req.query).then( resolve.bind(this, req, res), reject.bind(this, req, res) ); }); //{messageId: string} router.get('/comment', function(req, res) { models.retrieveComments(req.query.messageId).then( resolve.bind(this, req, res), reject.bind(this, req, res) ); }); };
var models = require('../db/models.js'); var util = require('../core/utilities.js'); module.exports = function(router) { //{x: float, y: float, z: float} router.get('/messages', function (req, res) { util.log('RECEIVED a GET request', req.query); models.retrieveMarks(req.query) .then(function(msg) { util.log('SENT message array to user', msg); res.status(200); res.send(msg); }, function(err) { util.log('SENT error code to user', err); res.sendStatus(400); }); }); //{messageId: string} router.get('/comment', function(req, res) { util.log('RECEIVED a GET request', req.query); models.retrieveComments(+req.query.messageId) .then(function(comments) { util.log('SENT comments to user', comments); res.status(200); res.send(comments); }, function(err) { util.log('SENT error code to user', err); res.sendStatus(400); }); }); };
Remove intial value for base
angular.module("currencyJa", []) .controller("TradersCtrl", function ($scope, traderService) { $scope.currency = "USD"; $scope.traders = traderService.findByCurrency($scope.currency); $scope.multiplyByBase = function(amount) { var base = parseFloat($scope.base) ? $scope.base : 1 return amount * base } $scope.changeCurrency = function(currency) { $scope.currency = currency; $scope.traders = traderService.findByCurrency($scope.currency); } }) .service('traderService', function() { this.findByCurrency = function(currency) { var traders = [] angular.forEach(gon.traders, function(trader, key) { traders.push({ name: trader.name, buyCash: trader.currencies[currency]['buy_cash'], buyDraft: trader.currencies[currency]['buy_draft'], sellCash: trader.currencies[currency]['sell_cash'], sellDraft: trader.currencies[currency]['sell_draft'] }); }); return traders; }; }); $(function() { $('time').timeago(); });
angular.module("currencyJa", []) .controller("TradersCtrl", function ($scope, traderService) { $scope.base = 1; $scope.currency = "USD"; $scope.traders = traderService.findByCurrency($scope.currency); $scope.multiplyByBase = function(amount) { var base = parseFloat($scope.base) ? $scope.base : 1 return amount * base } $scope.changeCurrency = function(currency) { $scope.currency = currency; $scope.traders = traderService.findByCurrency($scope.currency); } }) .service('traderService', function() { this.findByCurrency = function(currency) { var traders = [] angular.forEach(gon.traders, function(trader, key) { traders.push({ name: trader.name, buyCash: trader.currencies[currency]['buy_cash'], buyDraft: trader.currencies[currency]['buy_draft'], sellCash: trader.currencies[currency]['sell_cash'], sellDraft: trader.currencies[currency]['sell_draft'] }); }); return traders; }; }); $(function() { $('time').timeago(); });
Make destroyOAuthToken action destroy & recreate Octokat instance Fix Bug #32
import * as types from './actionTypes'; import GithubAPI from '../api/githubAPI'; export function oauthTempCodeReceived(tempCode) { return {type: types.OAUTH_TEMP_CODE_RECEIVED, tempCode}; } export function oauthTokenReceived(token) { return {type: types.OAUTH_TOKEN_RECEIVED, token}; } export function oauthTokenDestroyed() { return {type: types.OAUTH_TOKEN_DESTROYED}; } export function oauthAuthUserLoaded(user) { return {type: types.OAUTH_AUTH_USER_LOADED, user}; } export function storeOAuthTempCode(tempCode) { return function (dispatch){ dispatch(oauthTempCodeReceived(tempCode)); }; } export function storeOAuthToken(token) { return function (dispatch){ dispatch(oauthTokenReceived(token)); }; } export function destroyOAuthToken() { return function (dispatch){ return GithubAPI.removeTokenFromOcto().then(() => { dispatch(oauthTokenDestroyed()); }).catch(error => { //TODO: Improve error handling instead of re-throwing error throw(error); }); }; } export function loadAuthenticatedUser() { return function (dispatch){ return GithubAPI.getAuthenticatedUser().then(user => { dispatch(oauthAuthUserLoaded(user)); }).catch(error => { //TODO: Improve error handling instead of re-throwing error throw(error); }); }; }
import * as types from './actionTypes'; import GithubAPI from '../api/githubAPI'; export function oauthTempCodeReceived(tempCode) { return {type: types.OAUTH_TEMP_CODE_RECEIVED, tempCode}; } export function oauthTokenReceived(token) { return {type: types.OAUTH_TOKEN_RECEIVED, token}; } export function oauthTokenDestroyed() { return {type: types.OAUTH_TOKEN_DESTROYED}; } export function oauthAuthUserLoaded(user) { return {type: types.OAUTH_AUTH_USER_LOADED, user}; } export function storeOAuthTempCode(tempCode) { return function (dispatch){ dispatch(oauthTempCodeReceived(tempCode)); }; } export function storeOAuthToken(token) { return function (dispatch){ dispatch(oauthTokenReceived(token)); }; } export function destroyOAuthToken() { return function (dispatch){ dispatch(oauthTokenDestroyed()); }; } export function loadAuthenticatedUser() { return function (dispatch){ return GithubAPI.getAuthenticatedUser().then(user => { dispatch(oauthAuthUserLoaded(user)); }).catch(error => { //TODO: Improve error handling instead of re-throwing error throw(error); }); }; }
Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class child_depart_wizard(orm.TransientModel): _inherit = 'child.depart.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(child_depart_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class end_sponsorship_wizard(orm.TransientModel): _inherit = 'end.sponsorship.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(end_sponsorship_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
Fix error in ticket category management page
<?php // Set page title and set crumbs to index set_page_title(lang('categories')); project_tabbed_navigation(PROJECT_TAB_TICKETS); project_crumbs(array( array(lang('tickets'), get_url('ticket')), array(lang('categories')) )); if(Category::canAdd(logged_user(), active_project())) { add_page_action(lang('add category'), get_url('ticket', 'add_category')); } add_stylesheet_to_page('project/tickets.css'); ?> <?php if (isset($categories) && is_array($categories) && count($categories)) { ?> <div id="listing"> <table width="100%" cellpadding="2" border="0"> <tr bgcolor="#f4f4f4"> <th><?php echo lang('category'); ?></th> <th><?php echo lang('description'); ?></th> <th></th> </tr> <?php foreach ($categories as $category) { ?> <tr> <td><a href="<?php echo $category->getViewUrl() ?>"><?php echo $category->getName() ?></a></td> <td><?php echo $category->getShortDescription() ?></td> <td><a href="<?php echo $category->getEditUrl() ?>"><?php echo lang('edit'); ?></a></td> </tr> <?php } // foreach ?> </table> </div> <?php } else { ?> <p><?php echo lang('no categories in project') ?></p> <?php } // if ?>
<?php // Set page title and set crumbs to index set_page_title(lang('categories')); project_tabbed_navigation(PROJECT_TAB_TICKETS); project_crumbs(array( array(lang('tickets'), get_url('ticket')), array(lang('categories')) )); if(Category::canAdd(logged_user(), active_project())) { add_page_action(lang('add category'), get_url('ticket', 'add_category')); } add_stylesheet_to_page('project/tickets.css'); ?> <?php if(isset($categories) && is_array($categories) && count($categories)) { ?> <div id="listing"> <table width="100%" cellpadding="2" border="0"> <tr bgcolor="#f4f4f4"> <th><?php echo lang('category'); php?></th> <th><?php echo lang('description'); ?></th> <th></th> </tr> <?php foreach($categories as $category) { ?> <tr> <td><a href="<?php echo $category->getViewUrl() ?>"><?php echo $category->getName() ?></a></td> <td><?php echo $category->getShortDescription() ?></td> <td><a href="<?php echo $category->getEditUrl() ?>"><?php echo lang('edit'); ?></a></td> </tr> <?php } // foreach ?> </table> </div> <?php } else { ?> <p><?php echo lang('no categories in project') ?></p> <?php } // if ?>
Add resolve operation to references
<?php class PodioReference extends PodioObject { public function __construct($attributes = array()) { $this->property('type', 'string'); $this->property('id', 'integer'); $this->property('title', 'string'); $this->property('link', 'string'); $this->property('data', 'hash'); $this->property('created_on', 'datetime'); $this->has_one('created_by', 'ByLine'); $this->has_one('created_via', 'Via'); $this->init($attributes); } /** * @see https://developers.podio.com/doc/reference/get-reference-10661022 */ public static function get_for($ref_type, $ref_id, $attributes = array()) { return self::member(Podio::get("/reference/{$ref_type}/{$ref_id}", $attributes)); } /** * @see https://developers.podio.com/doc/reference/search-references-13312595 */ public static function search($attributes = array()) { return Podio::post("/reference/search", $attributes)->json_body(); } /** * @see https://developers.podio.com/doc/reference/resolve-url-66839423 */ public static function resolve($attributes = array()) { return self::member(Podio::get("/reference/resolve", $attributes)); } }
<?php class PodioReference extends PodioObject { public function __construct($attributes = array()) { $this->property('type', 'string'); $this->property('id', 'integer'); $this->property('title', 'string'); $this->property('link', 'string'); $this->property('data', 'hash'); $this->property('created_on', 'datetime'); $this->has_one('created_by', 'ByLine'); $this->has_one('created_via', 'Via'); $this->init($attributes); } /** * @see https://developers.podio.com/doc/reference/get-reference-10661022 */ public static function get_for($ref_type, $ref_id, $attributes = array()) { return self::member(Podio::get("/reference/{$ref_type}/{$ref_id}", $attributes)); } /** * @see https://developers.podio.com/doc/reference/search-references-13312595 */ public static function search($attributes = array()) { return Podio::post("/reference/search", $attributes)->json_body(); } }
Add extra field so _id is passed to make notification read
Requests = new Mongo.Collection('requests'); Meteor.methods({ addRequest: function(requestAttributes) { check(Meteor.userId(), String); check(requestAttributes, { user: Object, project: Object }); if (hasRequestPending(requestAttributes.user.userId, requestAttributes.project.projectId)) { throw new Meteor.Error('User has already requested to join'); } var request = _.extend(requestAttributes, { createdAt: new Date(), status: 'pending' }); var requestId = Requests.insert(request); var request = _.extend(request, { _id: requestId }); createRequestNotification(request); } }); hasRequestPending = function(userId, projectId) { return Requests.find({ 'user.userId': userId, 'project.projectId': projectId, status: 'pending' }).count() > 0; };
Requests = new Mongo.Collection('requests'); Meteor.methods({ addRequest: function(requestAttributes) { check(Meteor.userId(), String); check(requestAttributes, { user: Object, project: Object }); if (hasRequestPending(requestAttributes.user.userId, requestAttributes.project.projectId)) { throw new Meteor.Error('User has already requested to join'); } var request = _.extend(requestAttributes, { createdAt: new Date(), status: 'pending' }); Requests.insert(request); createRequestNotification(request); } }); hasRequestPending = function(userId, projectId) { return Requests.find({ 'user.userId': userId, 'project.projectId': projectId, status: 'pending' }).count() > 0; };
Switch to assertJ to trigger Github Action
/* * Copyright 2021 Jasha Joachimsthal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.jasha.demo.sbtfragments; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = Application.class) class ApplicationTest { @Autowired private CityDao cityDao; @Test void shouldStartSpringContext() { assertThat(cityDao).isNotNull(); } }
/* * Copyright 2021 Jasha Joachimsthal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.jasha.demo.sbtfragments; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = Application.class) class ApplicationTest { @Autowired private CityDao cityDao; @Test void shouldStartSpringContext() { assertNotNull(cityDao); } }