text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix pip developers beliving that they know what is the best for everyone else
import os from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='botnet', version='0.1.0', author='boreq', description = ('IRC bot.'), long_description=read('README.md'), url='https://github.com/boreq/botnet/', license='BSD', packages=find_packages(), install_requires=[ 'blinker>=1.4', 'Click>=2.0', 'requests>=2.12', 'protobuf>=3.0', 'requests-oauthlib>=0.7.0', 'beautifulsoup4>=4.6.0', 'markov @ git+https://github.com/boreq/markov#egg=markov-0.0.0', ], entry_points=''' [console_scripts] botnet=botnet.cli:cli ''' )
import os from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='botnet', version='0.1.0', author='boreq', description = ('IRC bot.'), long_description=read('README.md'), url='https://github.com/boreq/botnet/', license='BSD', packages=find_packages(), install_requires=[ 'blinker>=1.4', 'Click>=2.0', 'requests>=2.12', 'protobuf>=3.0', 'requests-oauthlib>=0.7.0', 'beautifulsoup4>=4.6.0', 'markov==0.0.0', ], entry_points=''' [console_scripts] botnet=botnet.cli:cli ''', dependency_links=[ "git+https://github.com/boreq/markov#egg=markov-0.0.0" ] )
Support multiple templates in TEST_TEMPLATES setting. Unit tests need to be able to test redirects and other features involving multiple web pages. This commit changes the singleton TEST_TEMPLATE setting to TEST_TEMPLATES, which is a list of path, template tuples.
"""test_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url('^accounts/', include('django.contrib.auth.urls')), url(r'^admin/', admin.site.urls), ] TEST_TEMPLATES = getattr( settings, 'TEST_TEMPLATES', [(r'^$', 'test.html')]) for path, template in TEST_TEMPLATES: urlpatterns.append(url(path, TemplateView.as_view(template_name=template)))
"""test_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView TEST_TEMPLATE = getattr(settings, 'TEST_TEMPLATE', 'test.html') urlpatterns = [ url('^accounts/', include('django.contrib.auth.urls')), url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name=TEST_TEMPLATE)), ]
Fix issue with PC WhiteSpace (/r/n) causing test failure.
package org.ihtsdo.buildgeneration; import org.ihtsdo.buildcloud.entity.Package; import org.ihtsdo.buildcloud.entity.helper.TestEntityFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.util.StreamUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; public class BuildGeneratorTest { private BuildGenerator buildGenerator; private String expectedPom; private Package releasePackage; @Before public void setup() throws IOException { buildGenerator = new BuildGenerator(); expectedPom = StreamUtils.copyToString(this.getClass().getResourceAsStream("expected-generated-pom.txt"), Charset.defaultCharset()).replace("\r", ""); releasePackage = new TestEntityFactory().createPackage("International", "International", "Spanish Edition", "Biannual", "RF2"); } @Test public void test() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); buildGenerator.generate(new OutputStreamWriter(out), releasePackage.getBuild()); String actualPom = out.toString(); Assert.assertEquals(expectedPom, actualPom); } }
package org.ihtsdo.buildgeneration; import org.ihtsdo.buildcloud.entity.Package; import org.ihtsdo.buildcloud.entity.helper.TestEntityFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.util.StreamUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; public class BuildGeneratorTest { private BuildGenerator buildGenerator; private String expectedPom; private Package releasePackage; @Before public void setup() throws IOException { buildGenerator = new BuildGenerator(); expectedPom = StreamUtils.copyToString(this.getClass().getResourceAsStream("expected-generated-pom.txt"), Charset.defaultCharset()); releasePackage = new TestEntityFactory().createPackage("International", "International", "Spanish Edition", "Biannual", "RF2"); } @Test public void test() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); buildGenerator.generate(new OutputStreamWriter(out), releasePackage.getBuild()); String actualPom = out.toString(); Assert.assertEquals(expectedPom, actualPom); } }
Add viewcode to sphinx docs
#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode' ] source_suffix = '.rst' master_doc = 'index' project = 'Javelin' copyright = '2017, Ross Whitfield' author = 'Ross Whitfield' version = '0.1.0' release = '0.1.0' exclude_patterns = ['_build'] pygments_style = 'friendly' html_theme = 'sphinx_rtd_theme' # Output file base name for HTML help builder. htmlhelp_basename = 'Javelindoc' latex_documents = [ (master_doc, 'Javelin.tex', 'Javelin Documentation', 'Ross Whitfield', 'manual'), ] intersphinx_mapping = {'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'xarray': ('http://xarray.pydata.org/en/stable/', None), 'ase': ('https://wiki.fysik.dtu.dk/ase/', None), 'diffpy.Structure': ('http://www.diffpy.org/diffpy.structure/', None)} autodoc_default_flags = ['members', 'undoc-members']
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx' ] source_suffix = '.rst' master_doc = 'index' project = 'Javelin' copyright = '2017, Ross Whitfield' author = 'Ross Whitfield' version = '0.1.0' release = '0.1.0' exclude_patterns = ['_build'] pygments_style = 'friendly' html_theme = 'sphinx_rtd_theme' # Output file base name for HTML help builder. htmlhelp_basename = 'Javelindoc' latex_documents = [ (master_doc, 'Javelin.tex', 'Javelin Documentation', 'Ross Whitfield', 'manual'), ] intersphinx_mapping = {'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'xarray': ('http://xarray.pydata.org/en/stable/', None), 'ase': ('https://wiki.fysik.dtu.dk/ase/', None), 'diffpy.Structure': ('http://www.diffpy.org/diffpy.structure/', None)} autodoc_default_flags = ['members', 'undoc-members']
Add a property onto VideoList that calls a function which updates App state with a selectVideo.
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; // const API_KEY = 'PLACE_YOUR_API_KEY_HERE'; class App extends Component { constructor (props) { super(props); this.state = { videos: [], selectedVideo: null }; YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => { console.log(videos); this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render () { return ( <div> <SearchBar /> <VideoDetail video={this.state.selectedVideo} /> <VideoList videos={this.state.videos} onVideoSelect={selectedVideo => this.setState({selectedVideo})} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; // const API_KEY = 'PLACE_YOUR_API_KEY_HERE'; class App extends Component { constructor (props) { super(props); this.state = { videos: [], selectedVideo: null }; YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => { console.log(videos); this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render () { return ( <div> <SearchBar /> <VideoDetail video={this.state.selectedVideo} /> <VideoList videos={this.state.videos} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
Make sure that oathbroken promises trigger the 'Uncaught rejection' error.
var workQueue = require('./workQueue'); var Promise = require('bluebird'); module.exports = function oathbreaker(value) { if (!value || typeof value.then !== 'function') { return null; } if (!value.isRejected) { return value; } if (value.isFulfilled()) { return null; } if (value.isRejected()) { value.caught(function () { // Ignore - already handled }); throw value.reason(); } var onResolve = function () {}; var onReject = function () {}; var evaluated = false; var error; value.then(function () { evaluated = true; onResolve(); }).caught(function (err) { evaluated = true; error = err; onReject(err); }); workQueue.drain(); if (evaluated && error) { throw error; } else if (evaluated) { return null; } return new Promise(function (resolve, reject) { onResolve = resolve; onReject = reject; }); };
var workQueue = require('./workQueue'); module.exports = function oathbreaker(value) { if (!value || typeof value.then !== 'function') { return null; } if (!value.isRejected) { return value; } if (value.isFulfilled()) { return null; } if (value.isRejected()) { value.caught(function () { // Ignore - already handled }); throw value.reason(); } var evaluated = false; var error; value.then(function () { evaluated = true; }).caught(function (err) { evaluated = true; error = err; }); workQueue.drain(); if (evaluated && error) { throw error; } else if (evaluated) { return null; } return value; };
Fix projects search dropdown keyboard navigation
$(function() { var $projects = $('#projects > ul > li').clone() $('#search-form').on('submit', function() { var $sel = $('#projects > ul > li.is-selected') if ($sel.length > 0) { window.location = $sel.find('a').attr('href') return false } }) $('#cerca').on('keydown', function(event) { if (event.which === 9 && $(this).is(':focus')) { $(this).blur() return true } }) $('#cerca').on('keyup', function(event) { var text = event.target.value.toLowerCase() $('#projects > ul').html($projects.filter(function(index, elem) { var project = $(elem).find('span').html().toLowerCase() if (project.indexOf(text) >= 0) { return elem } })) $('#projects > ul > li:first').trigger('mouseenter') }) })
$(document).ready(function() { $(function() { $('#search-form').on('submit', function() { var $sel = $('#projects > ul > li.is-selected') if ($sel.length > 0) { window.location = $sel.find('a').attr('href') return false } }) $('#cerca').on('keydown', function(event) { if (event.which === 9 && $(this).is(':focus')) { $(this).blur() return true } }) $('#cerca').on('keyup', function(event) { var text = event.target.value.toLowerCase() $('#projects > ul > li').each(function(index, elem) { var project = $(elem).find('span').html().toLowerCase() if (project.indexOf(text) < 0) { $(elem) .addClass('u-hiddenVisually') } else { $(elem) .removeClass('u-hiddenVisually') } }) }) }) })
Add return value stating Steam was started
#!venv/bin/python from flask import Flask, render_template from subprocess import Popen, PIPE from flask.ext.script import Manager, Server app = Flask(__name__) manager = Manager(app) manager.add_command("runserver", Server(host='0.0.0.0')) @app.route('/') def index(): return render_template('index.html') @app.route('/launch') def moonlight(): cmd = ['moonlight', 'stream', '-app', 'Steam', '-mapping', '/home/pi/xbox.conf', '-1080', '-30fps'] p = Popen(cmd, stdout=PIPE, stderr=PIPE) err = p.communicate() if p.returncode != 0: print ("moonlight failed %d %s" % (p.returncode, err)) else: return None return 'Steam started' if __name__ == '__main__': manager.run()
#!flask/bin/python from flask import Flask, render_template from subprocess import Popen, PIPE from flask.ext.script import Manager, Server app = Flask(__name__) manager = Manager(app) manager.add_command("runserver", Server(host='0.0.0.0')) @app.route('/') def index(): return render_template('index.html') @app.route('/launch') def moonlight(): cmd = ['moonlight', 'stream', '-app', 'Steam', '-mapping', 'xbox.conf', '-1080', '-30fps'] #cmd = ["ls", "-l"] p = Popen(cmd, stdout=PIPE, stderr=PIPE) output, err = p.communicate() if p.returncode != 0: print ("moonlight failed %d %s" % (p.returncode, err)) else: return output if __name__ == '__main__': manager.run()
Test with a dedicated plugin now
from lisa.server.plugins.PluginManager import PluginManagerSingleton from twisted.trial import unittest import json class LisaClientTestCase_Plugin(unittest.TestCase): def setUp(self): self.pluginManager = PluginManagerSingleton.get() def test_a_install_plugin(self): answer = self.pluginManager.installPlugin(plugin_name="UnitTest", test_mode=True) self.assertEqual(answer['status'], "success") def test_b_disable_plugin(self): answer = self.pluginManager.disablePlugin(plugin_name="UnitTest") self.assertEqual(answer['status'], "success") def test_c_enable_plugin(self): answer = self.pluginManager.enablePlugin(plugin_name="UnitTest") self.assertEqual(answer['status'], "success") def test_d_uninstall_plugin(self): answer = self.pluginManager.uninstallPlugin(plugin_name="UnitTest") self.assertEqual(answer['status'], "success")
from lisa.server.plugins.PluginManager import PluginManagerSingleton from twisted.trial import unittest import json class LisaClientTestCase_Plugin(unittest.TestCase): def setUp(self): self.pluginManager = PluginManagerSingleton.get() def test_a_install_plugin(self): answer = self.pluginManager.installPlugin(plugin_name="ChatterBot", test_mode=True) self.assertEqual(answer['status'], "success") def test_b_disable_plugin(self): answer = self.pluginManager.disablePlugin(plugin_name="ChatterBot") self.assertEqual(answer['status'], "success") def test_c_enable_plugin(self): answer = self.pluginManager.enablePlugin(plugin_name="ChatterBot") self.assertEqual(answer['status'], "success") def test_d_uninstall_plugin(self): answer = self.pluginManager.uninstallPlugin(plugin_name="ChatterBot") self.assertEqual(answer['status'], "success")
Remove useless requirement on Python 3.2+
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages install_requires = [] try: from concurrent import futures except ImportError: futures = None install_requires.append('futures>=2.1.3') setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY.rst', encoding='utf-8').read(), author='Timothée Peignier', author_email='timothee.peignier@tryphon.org', url='https://github.com/cyberdelia/django-pipeline', license='MIT', packages=find_packages(exclude=['tests', 'tests.tests']), zip_safe=False, install_requires=install_requires, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ] )
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY.rst', encoding='utf-8').read(), author='Timothée Peignier', author_email='timothee.peignier@tryphon.org', url='https://github.com/cyberdelia/django-pipeline', license='MIT', packages=find_packages(exclude=['tests', 'tests.tests']), zip_safe=False, install_requires=[ 'futures>=2.1.3', ], include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ] )
Docs: Add comments to Javascript API functions
/* * PSPDFKit.js * * PSPDFKit * * Copyright (c) 2015 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file. */ var exec = require('cordova/exec'); /** * Opens the PSPDFKitActivity to show a document from the local device file system. * * @param uri The local filesystem URI of the document to show. * @param success Success callback function. * @param error Error callback function. */ exports.showDocument = function (uri, success, error) { exec(success, error, "PSPDFKitCordovaPlugin", "showDocument", [uri]); }; /** * Opens the PSPDFKitActivity to show a document from the app's assets folder. This * method copies the file to the internal app directory on the device before showing * it. * * @param assetFile Relative path within the app's assets folder. * @param success Success callback function. * @param error Error callback function. */ exports.showDocumentFromAssets = function (assetFile, success, error) { exec(success, error, "PSPDFKitCordovaPlugin", "showDocumentFromAssets", [assetFile]); };
/* * PSPDFKit.js * * PSPDFKit * * Copyright (c) 2015 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file. */ var exec = require('cordova/exec'); exports.showDocument = function (uri, success, error) { exec(success, error, "PSPDFKitCordovaPlugin", "showDocument", [uri]); }; exports.showDocumentFromAssets = function (assetFile, success, error) { exec(success, error, "PSPDFKitCordovaPlugin", "showDocumentFromAssets", [assetFile]); };
Remove expired hazards from main map
from django.shortcuts import render from mapApp.models import Incident, Theft, Hazard, Official, AlertArea from mapApp.forms import IncidentForm, HazardForm, TheftForm, GeofenceForm, EditForm import datetime def index(request, lat=None, lng=None, zoom=None): incidents = Incident.objects.select_related('point').all() now = datetime.datetime.now() context = { # Model data used by map 'collisions': incidents.filter(p_type__exact="collision"), 'nearmisses': incidents.filter(p_type__exact="nearmiss"), 'hazards': Hazard.objects.select_related('point').exclude(expires_date__lt=now).exclude(hazard_fixed=True), 'thefts': Theft.objects.select_related('point').all(), # 'officials': officialResult, "geofences": AlertArea.objects.filter(user=request.user.id), # Form data used by map "incidentForm": IncidentForm(), "hazardForm": HazardForm(), "theftForm": TheftForm(), "geofenceForm": GeofenceForm(), "editForm": EditForm() } # Add zoom and center data if present if not None in [lat, lng, zoom]: context['lat']= float(lat) context['lng']= float(lng) context['zoom']= int(zoom) return render(request, 'mapApp/index.html', context)
from django.shortcuts import render from mapApp.models import Incident, Theft, Hazard, Official, AlertArea from mapApp.forms import IncidentForm, HazardForm, TheftForm, GeofenceForm, EditForm import datetime def index(request, lat=None, lng=None, zoom=None): incidents = Incident.objects.select_related('point').all() now = datetime.datetime.now() context = { # Model data used by map 'collisions': incidents.filter(p_type__exact="collision"), 'nearmisses': incidents.filter(p_type__exact="nearmiss"), 'hazards': Hazard.objects.select_related('point').exclude(expires_date__lt=now), 'thefts': Theft.objects.select_related('point').all(), # 'officials': officialResult, "geofences": AlertArea.objects.filter(user=request.user.id), # Form data used by map "incidentForm": IncidentForm(), "hazardForm": HazardForm(), "theftForm": TheftForm(), "geofenceForm": GeofenceForm(), "editForm": EditForm() } # Add zoom and center data if present if not None in [lat, lng, zoom]: context['lat']= float(lat) context['lng']= float(lng) context['zoom']= int(zoom) return render(request, 'mapApp/index.html', context)
Use HTTP codes as response. The code "$.ajax" in "contact_me.js" do not understand the "return true" or "return false" from PHP. It only understand the HTTP response code for select between "success" or "error". This is a quick fix, would be better a JSON response.
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { http_response_code(500); exit(); } $name = strip_tags(htmlspecialchars($_POST['name'])); $email = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = "yourname@yourdomain.com"; // Add your email address inbetween the "" replacing yourname@yourdomain.com - This is where the form will send a message to. $subject = "Website Contact Form: $name"; $body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\nPhone: $phone\n\nMessage:\n$message"; $header = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $header .= "Reply-To: $email"; if(!mail($to, $subject, $body, $header)) http_response_code(500); ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; return mail($to, $email_subject, $email_body, $headers); ?>
Remove @NotNull annotation to name field.
package com.zyeeda.framework.entities.base; import javax.validation.constraints.NotNull; @javax.persistence.MappedSuperclass public class SimpleDomainEntity extends DomainEntity { private static final long serialVersionUID = -2200108673372668900L; private String name; private String description; @javax.persistence.Basic @javax.persistence.Column(name = "F_NAME") public String getName() { return this.name; } public void setName(String name) { this.name = name; } @javax.persistence.Basic @javax.persistence.Column(name = "F_DESC", length = 2000) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } }
package com.zyeeda.framework.entities.base; import javax.validation.constraints.NotNull; @javax.persistence.MappedSuperclass public class SimpleDomainEntity extends DomainEntity { private static final long serialVersionUID = -2200108673372668900L; private String name; private String description; @javax.persistence.Basic @javax.persistence.Column(name = "F_NAME") @NotNull public String getName() { return this.name; } public void setName(String name) { this.name = name; } @javax.persistence.Basic @javax.persistence.Column(name = "F_DESC", length = 2000) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } }
dropbox: Fix incorrect placement of notify_bot_owner_on_invalid_json. This was an error I introduced in editing b79213d2602291a4c7ccbafe0f775f77db60665b.
from django.http import HttpRequest, HttpResponse from zerver.lib.response import json_success from zerver.lib.webhooks.common import check_send_webhook_message from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view from zerver.models import UserProfile @api_key_only_webhook_view('Dropbox', notify_bot_owner_on_invalid_json=False) @has_request_variables def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: if request.method == 'GET': return HttpResponse(request.GET['challenge']) elif request.method == 'POST': topic = 'Dropbox' check_send_webhook_message(request, user_profile, topic, "File has been updated on Dropbox!") return json_success()
from django.http import HttpRequest, HttpResponse from zerver.lib.response import json_success from zerver.lib.webhooks.common import check_send_webhook_message from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view from zerver.models import UserProfile @api_key_only_webhook_view('Dropbox') @has_request_variables def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile, notify_bot_owner_on_invalid_json=False) -> HttpResponse: if request.method == 'GET': return HttpResponse(request.GET['challenge']) elif request.method == 'POST': topic = 'Dropbox' check_send_webhook_message(request, user_profile, topic, "File has been updated on Dropbox!") return json_success()
FIX disable mrp auto prod demo data
# -*- coding: utf-8 -*- { 'name': 'MRP auto production', 'version': '0.1', 'author': 'ADHOC', 'category': 'Localization/Argentina', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'description': """ Para probar instalar tambien "sale" y "procurement_jit_stock" """, 'depends': [ 'mrp', 'procurement_jit_stock', ], 'demo': [ # TODO to fix data to pass test # 'mrp_demo.xml', ], 'test': [], 'data': [ 'mrp_view.xml', ], 'active': False, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'MRP auto production', 'version': '0.1', 'author': 'ADHOC', 'category': 'Localization/Argentina', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'description': """ Para probar instalar tambien "sale" y "procurement_jit_stock" """, 'depends': [ 'mrp', 'procurement_jit_stock', ], 'demo_xml': [ 'mrp_demo.xml', ], 'test': [], 'data': [ 'mrp_view.xml', ], 'active': False, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Remove duplicated code from LCM
'use strict'; var gcd = require('./gcd.js'); /** * Calcule the Least Common Multiple with a given Greatest Common Denominator * function * * @param Number * @param Number * @param Function * * @return Number */ var genericLCM = function (gcdFunction, a, b) { if (a === 0 || b === 0) { return 0; } a = Math.abs(a); b = Math.abs(b); return a / gcdFunction(a, b) * b; }; /** * Algorithm to calculate Least Common Multiple based on Euclidean algorithm * calls the generic LCM function passing the division based GCD calculator * * @param Number * @param Number * * @return Number */ var lcmDivisionBased = genericLCM.bind(null, gcd); /** * Algorithm to calculate Least Common Multiple based on Stein's Algorithm * calls the generic LCM function passing the binary interative GCD calculator * * @param Number * @param Number * * @return Number */ var lcmBinaryIterative = genericLCM.bind(null, gcd.binary); var lcm = lcmDivisionBased; lcm.binary = lcmBinaryIterative; module.exports = lcm;
'use strict'; var gcd = require('./gcd.js'); /** * Algorithm to calculate Least Common Multiple based on Euclidean algorithm * * @param Number * @param Number * * @return Number */ var lcmDivisionBased = function (a, b) { if (a === 0 || b === 0) { return 0; } a = Math.abs(a); b = Math.abs(b); return a / gcd(a, b) * b; }; /** * Algorithm to calculate Least Common Multiple based on Stein's Algorithm * * @param Number * @param Number * * @return Number */ var lcmBinaryIterative = function (a, b) { if (a === 0 || b === 0) { return 0; } a = Math.abs(a); b = Math.abs(b); return a / gcd.binary(a, b) * b; }; lcmDivisionBased.binary = lcmBinaryIterative; module.exports = lcmDivisionBased;
Return true when hmac validates
<?php namespace SamIT\Yii2\Filters; use SamIT\Yii2\Components\UrlSigner; use yii\base\ActionFilter; use yii\web\ForbiddenHttpException; use yii\web\Request; use yii\web\UnauthorizedHttpException; /** * Filter that checks for a valid HMAC in the URL. * @inheritdoc */ class HmacFilter extends ActionFilter { /** * @var UrlSigner */ public $signer; /** * @param \yii\base\Action $action * @return bool * @throws \Exception */ public function beforeAction($action) { /** @var Request $request */ $request = $action->controller->module->get('request'); if (!$this->signer->verifyHMAC($request->queryParams, $action->controller->route)) { throw new ForbiddenHttpException("No or invalid HMAC"); } return true; } }
<?php namespace SamIT\Yii2\Filters; use SamIT\Yii2\Components\UrlSigner; use yii\base\ActionFilter; use yii\web\ForbiddenHttpException; use yii\web\Request; use yii\web\UnauthorizedHttpException; /** * Filter that checks for a valid HMAC in the URL. * @inheritdoc */ class HmacFilter extends ActionFilter { /** * @var UrlSigner */ public $signer; /** * @param \yii\base\Action $action * @return bool * @throws \Exception */ public function beforeAction($action) { /** @var Request $request */ $request = $action->controller->module->get('request'); if (!$this->signer->verifyHMAC($request->queryParams, $action->controller->route)) { throw new ForbiddenHttpException("No or invalid HMAC"); } } }
Allow star imports from twine Unicode literals on Python 2 prevent people from being able to use from twine import * Closes gh-209 (cherry picked from commit c2cd72d0f4ff4d380845333fbfaaf2c92d6a5674)
# Copyright 2013 Donald Stufft # # 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 __future__ import absolute_import, division, print_function __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __title__ = "twine" __summary__ = "Collection of utilities for interacting with PyPI" __uri__ = "https://github.com/pypa/twine" __version__ = "1.8.1" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
# Copyright 2013 Donald Stufft # # 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 __future__ import absolute_import, division, print_function from __future__ import unicode_literals __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __title__ = "twine" __summary__ = "Collection of utilities for interacting with PyPI" __uri__ = "https://github.com/pypa/twine" __version__ = "1.8.1" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
Update Netflix example (API request is no longer signed) git-svn-id: 1d5fd79e00fb49afc950abd77d854b8070d085dd@299969 c90b9560-bf6c-de11-be94-00142212c4b1
<?php /* best viewed through an atom viewer, such as http://inforss.mozdev.org/ */ require("config.inc.php"); $o = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION); try { $access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp")); $o->setToken($access_token_info["oauth_token"],$access_token_info["oauth_token_secret"]); $feeds_url = "http://api.netflix.com/users/". oauth_urlencode($access_token_info["user_id"]) ."/feeds"; $o->fetch($feeds_url); $feeds = $o->getLastResponse(); /* we need to pick the rental history feed (returned rentals) */ $feeds_xml = new SimpleXMLElement($feeds); /* if you want to access other feeds, change the following rel attribute */ $feed_rel = "http://schemas.netflix.com/feed.rental_history.returned"; $returned_feed = current($feeds_xml->xpath("/resource/link[@rel=\"{$feed_rel}\"]"))->attributes(); /* don't sign the feed requests */ $curl = curl_init($returned_feed["href"]); curl_exec($curl); } catch(OAuthException $E) { echo "Exception caught!\n"; echo "Response: ". $E->lastResponse . "\n"; var_dump($E); }
<?php /* best viewed through an atom viewer, such as http://inforss.mozdev.org/ */ require("config.inc.php"); $o = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION); try { $access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp")); $o->setToken($access_token_info["oauth_token"],$access_token_info["oauth_token_secret"]); $feeds_url = "http://api.netflix.com/users/". oauth_urlencode($access_token_info["user_id"]) ."/feeds"; $o->fetch($feeds_url); $feeds = $o->getLastResponse(); /* we need to pick the rental history feed (returned rentals) */ $feeds_xml = new SimpleXMLElement($feeds); /* if you want to access other feeds, change the following rel attribute */ $feed_rel = "http://schemas.netflix.com/feed.rental_history.returned"; $returned_feed = current($feeds_xml->xpath("/resource/link[@rel=\"{$feed_rel}\"]"))->attributes(); $o->fetch($returned_feed["href"]); echo $o->getLastResponse(); } catch(OAuthException $E) { echo "Exception caught!\n"; echo "Response: ". $E->lastResponse . "\n"; var_dump($E); }
Allow generating one specific xml file instead of the whole directory.
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' for f in os.listdir(TYPESDIR): basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Add a bit of documentation
// Handles accounting corrections - erroneously printed pages, etc. var Correction = function(baseUrl) { var self = this; this.baseUrl = baseUrl; this.erroneousPages = 0; this.erroneousCents = 0; // Registering deposit without printing is done by submitting a print job with // non-zero depositCount, but not documents. We're using PrintJob as is with // an empty Cart for this. this._printJob = new PrintJob(this.baseUrl, new Cart(baseUrl)); ko.track(this); ko.defineProperty(self, 'erroneousEuros', { get: function() { return self.erroneousCents / 100; }, set: function(value) { this.erroneousCents = value * 100; } }); } Correction.prototype = Object.create(Object.prototype); Correction.prototype._logErroneous = function(centsPrice) { $.ajax({ url: this.baseUrl + '/data/log_erroneous_copies', type: 'POST', contentType: 'application/json; charset=UTF-8', data: JSON.stringify({cents: centsPrice}), error: function(_, _, error) { console.log(error); } }) } Correction.prototype.logErroneousCents = function() { this._logErroneous(this.erroneousCents); } Correction.prototype.logErroneouslyPrintedPages = function() { this._logErroneous(this.erroneousPages * pricePerPage); }
var Correction = function(baseUrl) { var self = this; this.baseUrl = baseUrl; this.erroneousPages = 0; this.erroneousCents = 0; this._printJob = new PrintJob(this.baseUrl, new Cart(baseUrl)); ko.track(this); ko.defineProperty(self, 'erroneousEuros', { get: function() { return self.erroneousCents / 100; }, set: function(value) { this.erroneousCents = value * 100; } }); } Correction.prototype = Object.create(Object.prototype); Correction.prototype._logErroneous = function(centsPrice) { $.ajax({ url: this.baseUrl + '/data/log_erroneous_copies', type: 'POST', contentType: 'application/json; charset=UTF-8', data: JSON.stringify({cents: centsPrice}), error: function(_, _, error) { console.log(error); } }) } Correction.prototype.logErroneousCents = function() { this._logErroneous(this.erroneousCents); } Correction.prototype.logErroneouslyPrintedPages = function() { this._logErroneous(this.erroneousPages * pricePerPage); }
Change serializer field name from ayah to ayah_number
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah', 'text']
Add get retrieval of FormData
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.util.*; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that takes in audio stream and retrieves ** user input string to display. */ @WebServlet("/audio-input") public class AudioInputServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Object formdata = request.getParameter("file"); System.out.println(formdata); System.out.println("Got to servlet"); //response.setContentType("text/html;"); //response.getWriter().println("<h1>Hello world!</h1>"); } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that takes in audio stream and retrieves ** user input string to display. */ @WebServlet("/audio-input") public class AudioInputServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;"); response.getWriter().println("<h1>Hello world!</h1>"); } }
Remove ProviderInstanceBinding as it also captures @Provides methods
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } }); } }
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.ProviderInstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } public String visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", providerInstanceBinding.getSource()); } }); } }
Fix section scrolling inside padding
import React from 'react' import Link from 'gatsby-link' import Section from '../components/Section' import HomeBanner from '../components/HomeBanner' import About from '../components/About' import Skills from '../components/Skills' import Portfolio from '../components/Portfolio' import Contact from '../components/Contact' import { Element } from 'react-scroll' const IndexPage = () => <div className='page-sections'> <Element name="home"> <Section id="home" className="home-banner-section"> <HomeBanner /> </Section> </Element> <Element name="about"> <Section id="about-me" className="about-section"> <About /> </Section> </Element> <Section id="skills" className="skills-section"> <Skills /> </Section> <Element name="portfolio"> <Section id="portfolio" className="portfolio-section"> <Portfolio /> </Section> </Element> <Element name="contact"> <Section id="contact" className="contact-section"> <Contact /> </Section> </Element> </div> export default IndexPage
import React from 'react' import Link from 'gatsby-link' import Section from '../components/Section' import HomeBanner from '../components/HomeBanner' import About from '../components/About' import Skills from '../components/Skills' import Portfolio from '../components/Portfolio' import Contact from '../components/Contact' import { Element } from 'react-scroll' const IndexPage = () => <div className='page-sections'> <Section id="home" className="home-banner-section"> <Element name="home"> <HomeBanner /> </Element> </Section> <Section id="about-me" className="about-section"> <Element name="about"> <About /> </Element> </Section> <Section id="skills" className="skills-section"> <Skills /> </Section> <Section id="portfolio" className="portfolio-section"> <Element name="portfolio"> <Portfolio /> </Element> </Section> <Section id="contact" className="contact-section"> <Element name="contact"> <Contact /> </Element> </Section> </div> export default IndexPage
Remove accidently added error handler from update listener
var browserify = require('browserify'); var cssify = require('cssify'); var watchify = require('watchify'); var through = require('through'); var fs = require('fs'); var path = require('path'); var cp = require('child_process'); function globalOl(file) { var data = ''; function write(buf) { data += buf; } function end() { this.queue(data.replace(/require\(["']openlayers['"]\)/g, 'window.ol')); this.queue(null); } return through(write, end); } var b = browserify({ entries: ['./src/index.js'], debug: true, plugin: [watchify], cache: {}, packageCache: {} }).transform(globalOl).transform(cssify, {global: true}); b.on('update', function() { b.bundle().pipe(fs.createWriteStream('./_index.js')); }); b.bundle(function(err, buf) { if (err) { console.error(err.message); process.exit(1); } else { fs.writeFile('./_index.js', buf, 'utf-8'); cp.fork(path.join(path.dirname(require.resolve('openlayers')), '../tasks/serve-lib.js'), []); } });
var browserify = require('browserify'); var cssify = require('cssify'); var watchify = require('watchify'); var through = require('through'); var fs = require('fs'); var path = require('path'); var cp = require('child_process'); function globalOl(file) { var data = ''; function write(buf) { data += buf; } function end() { this.queue(data.replace(/require\(["']openlayers['"]\)/g, 'window.ol')); this.queue(null); } return through(write, end); } var b = browserify({ entries: ['./src/index.js'], debug: true, plugin: [watchify], cache: {}, packageCache: {} }).transform(globalOl).transform(cssify, {global: true}); b.on('update', function bundle(onError) { var stream = b.bundle(); if (onError) { stream.on('error', function(err) { console.log(err.message); process.exit(1); }); } stream.pipe(fs.createWriteStream('./_index.js')); }); b.bundle(function(err, buf) { if (err) { console.error(err.message); process.exit(1); } else { fs.writeFile('./_index.js', buf, 'utf-8'); cp.fork(path.join(path.dirname(require.resolve('openlayers')), '../tasks/serve-lib.js'), []); } });
Fix export of force resize method
import { state } from './../store/index.js'; import external from './../externalModules.js'; const enable = function () { disable(); // Clean up any lingering listeners window.addEventListener('resize', resizeThrottler, false); }; const disable = function () { window.removeEventListener('resize', resizeThrottler, false); }; let resizeTimeout; function resizeThrottler () { // Ignore resize events as long as an actualResizeHandler execution is in the queue if (!resizeTimeout) { resizeTimeout = setTimeout(function () { resizeTimeout = null; forceEnabledElementResize(); // The actualResizeHandler will execute at a rate of 15fps }, 66); } } export const forceEnabledElementResize = function () { state.enabledElements.forEach((element) => { external.cornerstone.resize(element); }); }; export default { enable, disable };
import { state } from './../store/index.js'; import external from './../externalModules.js'; const enable = function () { disable(); // Clean up any lingering listeners window.addEventListener('resize', resizeThrottler, false); }; const disable = function () { window.removeEventListener('resize', resizeThrottler, false); }; let resizeTimeout; function resizeThrottler () { // Ignore resize events as long as an actualResizeHandler execution is in the queue if (!resizeTimeout) { resizeTimeout = setTimeout(function () { resizeTimeout = null; actualResizeHandler(); // The actualResizeHandler will execute at a rate of 15fps }, 66); } } function actualResizeHandler () { state.enabledElements.forEach((element) => { external.cornerstone.resize(element); }); } export default { enable, disable, forceEnabledElementResize: actualResizeHandler };
Fix chapter links in scrolled navigation REDMINE-17300
import React from 'react'; import classNames from 'classnames'; import styles from "./ChapterLink.module.css"; import AppHeaderTooltip from "./AppHeaderTooltip"; export default function ChapterLink(props) { return ( <div> <a className={classNames(styles.chapterLink, {[styles.chapterLinkActive]: props.active})} href={`#chapter-${props.permaId}`} onClick={() => props.handleMenuClick(props.chapterLinkId)} data-tip data-for={props.chapterLinkId}> {props.title} </a> <AppHeaderTooltip chapterIndex={props.chapterIndex} chapterLinkId={props.chapterLinkId} {...props} /> </div> ) }
import React from 'react'; import classNames from 'classnames'; import styles from "./ChapterLink.module.css"; import AppHeaderTooltip from "./AppHeaderTooltip"; export default function ChapterLink(props) { return ( <div> <a className={classNames(styles.chapterLink, {[styles.chapterLinkActive]: props.active})} href={`chapter-${props.permaId}`} onClick={() => props.handleMenuClick(props.chapterLinkId)} data-tip data-for={props.chapterLinkId}> {props.title} </a> <AppHeaderTooltip chapterIndex={props.chapterIndex} chapterLinkId={props.chapterLinkId} {...props} /> </div> ) }
Fix Guzzle message factory improper usage
<?php namespace Slack\Tests; use GuzzleHttp\Client; use GuzzleHttp\Subscriber\Mock; use GuzzleHttp\Message\MessageFactory; use GuzzleHttp\Subscriber\History; use Slack\ApiClient; class ApiClientTest extends \PHPUnit_Framework_TestCase { public function testApiCall() { $httpClient = new Client(); $messageFactory = new MessageFactory(); // add history subscriber to the client $history = new History(); $httpClient->getEmitter()->attach($history); // ddd the mock subscriber to the client $httpClient->getEmitter()->attach(new Mock([ $messageFactory->createResponse(200, [], '{"ok": true}'), ])); // create the API client $client = new ApiClient($httpClient); $client->apiCall('api.test'); // exactly one request should have been sent $this->assertCount(1, $history); // verify the sent URL $this->assertEquals(ApiClient::BASE_URL.'api.test', $history->getLastRequest()->getUrl()); } }
<?php namespace Slack\Tests; use GuzzleHttp\Client; use GuzzleHttp\Subscriber\Mock; use GuzzleHttp\Message\MessageFactory; use GuzzleHttp\Subscriber\History; use Slack\ApiClient; class ApiClientTest extends \PHPUnit_Framework_TestCase { public function testApiCall() { $httpClient = new Client(); // add history subscriber to the client $history = new History(); $httpClient->getEmitter()->attach($history); // ddd the mock subscriber to the client $httpClient->getEmitter()->attach(new Mock([ MessageFactory::createResponse(200, [], '{"ok": true}'), ])); // create the API client $client = new ApiClient($httpClient); $client->apiCall('api.test'); // exactly one request should have been sent $this->assertCount(1, $history); // verify the sent URL $this->assertEquals(ApiClient::BASE_URL.'api.test', $history->getLastRequest()->getUrl()); } }
Change subject to every mail to was sent
# Copyright 2013 Rooter Analysis S.L. # # 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 datetime import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): """send mail test """ def message(self, message): self.stdout.write("%s\n" % message.encode("ascii", "replace")) def handle(self, *args, **options): now = datetime.now() body=""" Hi, this is the testing message send on %s """ % str(now) self.message(body) send_mail('Testing mail - %s' % str(now), body, settings.DEFAULT_FROM_EMAIL, args)
# Copyright 2013 Rooter Analysis S.L. # # 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 django.conf import settings from django.core.management.base import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): """send mail test """ def handle(self, *args, **options): send_mail('Testing mail', 'Here is the message.', settings.DEFAULT_FROM_EMAIL, args)
Update CORS origin to localhost
package com.awesometickets.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Cross-Origin Resource Sharing filter. */ public class CORSFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; res.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", "x-requested-with"); res.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } public void destroy() {} }
package com.awesometickets.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Cross-Origin Resource Sharing filter. */ public class CORSFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; res.setHeader("Access-Control-Allow-Origin", "http://119.29.152.169"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", "x-requested-with"); res.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } public void destroy() {} }
Update code as commented, update readme.
# -*- coding:utf-8 -*- ############################################################################## # # Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>. # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api class hr_contract(models.Model): _inherit = 'hr.contract' name = fields.Char('Contract Reference', required=False, readonly=True, copy=False, default='/') @api.model def create(self, vals): if vals.get('number', '/') == '/': vals['name'] = self.env['ir.sequence'].next_by_code('contract.ref') return super(hr_contract, self).create(vals)
# -*- coding:utf-8 -*- ############################################################################## # # Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>. # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api class hr_contract(models.Model): _inherit = 'hr.contract' name = fields.Char('Contract Reference', required=False, readonly=True, copy=False) @api.model def create(self, vals): contract = super(hr_contract, self).create(vals) if contract: contract[0].name = self.env['ir.sequence'].next_by_code( 'contract.ref') return contract
Move OPML importing beyond a non-default flag. Now that persisting the OPML data is done, no need to clobber it every time.
package main import ( "encoding/json" "flag" log "github.com/golang/glog" "github.com/jrupac/goliath/opml" "github.com/jrupac/goliath/storage" ) const VERSION = "0.01" var ( dbPath = flag.String("dbPath", "", "The address of the database.") opmlPath = flag.String("opmlPath", "", "Path of OPML file to import.") ) func main() { flag.Parse() defer log.Flush() log.Infof("Goliath %s.", VERSION) d, err := storage.Open(*dbPath) if err != nil { log.Fatalf("Unable to open DB: %s", err) } defer d.Close() if *opmlPath != "" { p, err := opml.ParseOpml(*opmlPath) if err != nil { log.Warningf("Error while parsing OPML: %s", err) } b, err := json.MarshalIndent(*p, "", " ") log.Infof("Parsed OPML file: %s\n", string(b)) err = d.ImportOpml(p) if err != nil { log.Warningf("Error while importing OPML: %s", err) } } }
package main import ( "encoding/json" "flag" log "github.com/golang/glog" "github.com/jrupac/goliath/opml" "github.com/jrupac/goliath/storage" ) const VERSION = "0.01" var ( dbPath = flag.String("dbPath", "", "The address of the database.") ) func main() { flag.Parse() defer log.Flush() log.Infof("Goliath %s.", VERSION) d, err := storage.Open(*dbPath) if err != nil { log.Fatalf("Unable to open DB: %s", err) } defer d.Close() p, err := opml.ParseOpml("testdata/opml2.xml") if err != nil { log.Warningf("Error while parsing OPML: %s", err) } b, err := json.MarshalIndent(*p, "", " ") log.Infof("Parsed OPML file: %s\n", string(b)) err = d.ImportOpml(p) if err != nil { log.Warningf("Error while importing OPML: %s", err) } }
Select a task when it's been created
var View = require('./View'), Button = require('../Button'), List = require('../lists/List'), TextView = require('../TextView') module.exports = Class(View, function(supr) { this._createHeader = function() { new Button('New Task') .appendTo(this._header) .subscribe('Click', this, '_createTask') } this._createBody = function() { new List(function (task) { return new TextView(task.title) }) .reflect(global.user.tasks) .appendTo(this._body) .subscribe('Select', this, function(task) { models.local.currentTaskID.set(task._id) }) } this._createTask = function() { var task = new models.Task({ title:"I need to...", owner:global.user }) global.user.tasks.add(task) task.create(function(taskID) { models.local.currentTaskID.set(taskID) }) } })
var View = require('./View'), Button = require('../Button'), List = require('../lists/List'), TextView = require('../TextView') module.exports = Class(View, function(supr) { this._createHeader = function() { new Button('New Task') .appendTo(this._header) .subscribe('Click', this, '_createTask') } this._createBody = function() { new List(function (task) { return new TextView(task.title) }) .reflect(global.user.tasks) .appendTo(this._body) .subscribe('Select', this, function(task) { models.local.currentTaskID.set(task._id) }) } this._createTask = function() { var task = new models.Task({ title:"I need to...", owner:global.user }).create() global.user.tasks.add(task) } })
fix(react-wildcat-handoff): Add data-react-available hook on callback
"use strict"; var ReactDOM = require("react-dom"); var Router = require("react-router"); var clientContext = require("./clientContext.js"); var match = Router.match; var __REACT_ROOT_ID__ = "__REACT_ROOT_ID__"; module.exports = function clientRender(cfg) { var component = clientContext(cfg); return new Promise(function clientRenderPromise(resolve) { match(cfg, function clientRenderMatch() { var reactRootElementID = window[__REACT_ROOT_ID__]; var reactRootElement = document.getElementById(reactRootElementID); ReactDOM.render(component, reactRootElement, function addReactHook() { // Flag react as available // This is a helpful hook for running tests reactRootElement.setAttribute("data-react-available", true); resolve([reactRootElement, component]); }); }); }); };
"use strict"; var ReactDOM = require("react-dom"); var Router = require("react-router"); var clientContext = require("./clientContext.js"); var match = Router.match; var __REACT_ROOT_ID__ = "__REACT_ROOT_ID__"; module.exports = function clientRender(cfg) { var component = clientContext(cfg); return new Promise(function clientRenderPromise(resolve) { match(cfg, function clientRenderMatch() { var reactRootElementID = window[__REACT_ROOT_ID__]; var reactRootElement = document.getElementById(reactRootElementID); ReactDOM.render(component, reactRootElement); // Flag react as available // This is a helpful hook for running tests reactRootElement.setAttribute("data-react-available", true); resolve([reactRootElement, component]); }); }); };
Refactor CaretakerRolesGateway to use factory pattern
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ const createCaretakerRolesGateway = () => { let allRoles = null; return { getAll: () => { if(allRoles === null) { //api call to get roles allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return allRoles; } } } export default createCaretakerRolesGateway();
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ export default class CaretakerRolesGateway { static allRoles = null; static getAll() { if(this.allRoles === null) { //api call to get roles this.allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return this.allRoles; } }
Fix bug of invoking /bin/sh on several OSs
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
Fix metadata update on instance.remove Omit non-removed check when search for instance nic (nic can be already removed by the time config item post handler runs for the instance)
package io.cattle.platform.agent.instance.service.impl; import static io.cattle.platform.core.model.tables.NicTable.*; import io.cattle.platform.agent.instance.service.InstanceNicLookup; import io.cattle.platform.core.dao.GenericMapDao; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.Nic; import io.cattle.platform.object.ObjectManager; import java.util.List; import javax.inject.Inject; /** * This class is invoked on instance healthcheck changes * * */ public class ContainerNicLookup extends NicPerVnetNicLookup implements InstanceNicLookup { @Inject ObjectManager objectManager; @Inject GenericMapDao mapDao; @Override public List<? extends Nic> getNics(Object obj) { if (!(obj instanceof Instance)) { return null; } Instance container = (Instance) obj; return create().selectFrom(NIC) .where(NIC.INSTANCE_ID.eq(container.getId())) .fetch(); } }
package io.cattle.platform.agent.instance.service.impl; import static io.cattle.platform.core.model.tables.NicTable.*; import io.cattle.platform.agent.instance.service.InstanceNicLookup; import io.cattle.platform.core.dao.GenericMapDao; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.Nic; import io.cattle.platform.object.ObjectManager; import java.util.List; import javax.inject.Inject; /** * This class is invoked on instance healthcheck changes * * */ public class ContainerNicLookup extends NicPerVnetNicLookup implements InstanceNicLookup { @Inject ObjectManager objectManager; @Inject GenericMapDao mapDao; @Override public List<? extends Nic> getNics(Object obj) { if (!(obj instanceof Instance)) { return null; } Instance container = (Instance) obj; return create().selectFrom(NIC) .where(NIC.INSTANCE_ID.eq(container.getId()) .and(NIC.REMOVED.isNull())) .fetch(); } }
Change type-hint of getDecodedData to mixed
<?php namespace RIPS\Connector\Entities; use Psr\Http\Message\ResponseInterface; class Response { /** @var ResponseInterface */ private $response; /** * @param ResponseInterface $response */ public function __construct(ResponseInterface $response) { $this->response = $response; } /** * Get original Guzzle response. * @return ResponseInterface */ public function getResponse() { return $this->response; } /** * @return \Psr\Http\Message\StreamInterface */ public function getRawData() { return $this->response->getBody(); } /** * @return mixed */ public function getDecodedData() { return json_decode($this->response->getBody()); } }
<?php namespace RIPS\Connector\Entities; use Psr\Http\Message\ResponseInterface; class Response { /** @var ResponseInterface */ private $response; /** * @param ResponseInterface $response */ public function __construct(ResponseInterface $response) { $this->response = $response; } /** * Get original Guzzle response. * @return ResponseInterface */ public function getResponse() { return $this->response; } /** * @return \Psr\Http\Message\StreamInterface */ public function getRawData() { return $this->response->getBody(); } /** * @return \stdClass[]|\stdClass */ public function getDecodedData() { return json_decode($this->response->getBody()); } }
Remove duplicate dependency specifications from install_requires
from setuptools import setup setup( name='djangorestframework-httpsignature', version='0.2.1', url='https://github.com/etoccalino/django-rest-framework-httpsignature', license='LICENSE.txt', description='HTTP Signature support for Django REST framework', long_description=open('README.rst').read(), install_requires=[ 'Django>=1.6.2,<1.8', 'djangorestframework>=2.3.14,<2.4', 'pycrypto>=2.6.1', 'httpsig', ], author='Elvio Toccalino', author_email='me@etoccalino.com', packages=['rest_framework_httpsignature'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', ] )
from setuptools import setup setup( name='djangorestframework-httpsignature', version='0.2.1', url='https://github.com/etoccalino/django-rest-framework-httpsignature', license='LICENSE.txt', description='HTTP Signature support for Django REST framework', long_description=open('README.rst').read(), install_requires=[ 'Django>=1.6.2,<1.8', 'djangorestframework>=2.3.14,<2.4', 'Django>=1.6.2', 'djangorestframework>=2.3.12', 'pycrypto>=2.6.1', 'httpsig', ], author='Elvio Toccalino', author_email='me@etoccalino.com', packages=['rest_framework_httpsignature'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', ] )
Insert to collection - sample comment object
import { Meteor } from 'meteor/meteor'; Meteor.startup(() => { // code to run on server at startup // Creating comment schema CommentSchema = new SimpleSchema({ email: { type: String, unique: true }, text: { type: String } }); // Creating comments collection Comments = new Mongo.Collection('Comments'); // Attaching CommentSchema to Comments collection Comments.attachSchema(CommentSchema); var commentObj = { "email": "a@a.com", "text": "test" } // Validating sample object var isValid = Comments.simpleSchema().namedContext().validate(commentObj, { modifier: false }); console.log(isValid); if(isValid) { Comments.insert(commentObj); } console.log(Comments.find().fetch()); });
import { Meteor } from 'meteor/meteor'; Meteor.startup(() => { // code to run on server at startup // Creating comment schema CommentSchema = new SimpleSchema({ email: { type: String, unique: true }, text: { type: String } }); // Creating comments collection Comments = new Mongo.Collection('Comments'); // Attaching CommentSchema to Comments collection Comments.attachSchema(CommentSchema); var obj = { "email": "a@a.com", "text": "test" } // Validating sample object var isValid = Comments.simpleSchema().namedContext().validate(obj, { modifier: false }); console.log(isValid); });
Fix to collapse navbar on page reloads
/*! * Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ function hideOnRefresh() { console.log($(".navbar").offset().top); if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("navbar-collapse navbar-shrink"); } else { $(".navbar-fixed-top").removeClass("navbar-collapse navbar-shrink"); } } // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); $(document).ready(function() { hideOnRefresh(); }); $(window).scroll(function() { hideOnRefresh(); });
/*! * Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
Fix assertion for not existing files
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('hubot:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'bin/hubot', 'bin/hubot.cmd', 'Procfile', 'README.md', 'external-scripts.json', 'hubot-scripts.json', '.gitignore', 'package.json', 'scripts/example.coffee', '.editorconfig', ]); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('hubot:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'bower.json', 'package.json', '.editorconfig', '.jshintrc' ]); }); });
:new: Add an emitter to Editor class
'use babel' /* @flow */ import { CompositeDisposable, Emitter } from 'atom' import type { Disposable, TextEditor, TextBuffer, TextEditorGutter } from 'atom' export class Editor { gutter: ?TextEditorGutter; emitter: Emitter; textEditor: TextEditor; subscriptions: CompositeDisposable; constructor(textEditor: TextEditor) { this.emitter = new Emitter() this.textEditor = textEditor this.subscriptions = new CompositeDisposable() const visibility = atom.config.get('linter-ui-default.highlightIssues') if (visibility) { const position = atom.config.get('linter-ui-default.gutterPosition') this.gutter = this.textEditor.addGutter({ name: 'linter-ui-default', priority: position === 'Left' ? -100 : 100 }) } else this.gutter = null this.subscriptions.add(this.emitter) this.subscriptions.add(textEditor.onDidDestroy(() => { this.dispose() })) } onDidDestroy(callback: Function): Disposable { return this.emitter.on('did-destroy') } dispose() { this.emitter.emit('did-destroy') this.subscriptions.dispose() if (this.gutter) { this.gutter.destroy() } } }
'use babel' /* @flow */ import {CompositeDisposable} from 'atom' import type {Disposable, TextEditor, TextBuffer, TextEditorGutter} from 'atom' export class Editor { gutter: ?TextEditorGutter; textEditor: TextEditor; subscriptions: CompositeDisposable; constructor(textEditor: TextEditor) { this.textEditor = textEditor this.subscriptions = new CompositeDisposable() const visibility = atom.config.get('linter-ui-default.highlightIssues') if (visibility) { const position = atom.config.get('linter-ui-default.gutterPosition') this.gutter = this.textEditor.addGutter({ name: 'linter-ui-default', priority: position === 'Left' ? -100 : 100 }) } else this.gutter = null } getPath(): string { return this.textEditor.getPath() } getBuffer(): TextBuffer { return this.textEditor.getBuffer() } onDidDestroy(callback: Function): Disposable { const subscription = this.textEditor.onDidDestroy(callback) this.subscriptions.add(subscription) return subscription } dispose() { this.subscriptions.dispose() if (this.gutter) { this.gutter.destroy() } } }
Fix variadic syntax in func argument
<?php namespace Swaggest\GoCodeBuilder\Templates\Func; use Swaggest\GoCodeBuilder\Templates\GoTemplate; use Swaggest\GoCodeBuilder\Templates\Type\AnyType; use Swaggest\GoCodeBuilder\Templates\Type\Type; class Argument extends GoTemplate { /** @var string */ public $name; /** @var AnyType */ public $type; /** @var boolean */ public $isVariadic; /** * Argument constructor. * @param string $name * @param AnyType $type * @param bool $isVariadic */ public function __construct($name, AnyType $type, $isVariadic = false) { $this->name = $name; $this->type = $type; $this->isVariadic = $isVariadic; } protected function toString() { if ($this->name === null) { return $this->type->render(); } else { return $this->name . ' ' . ($this->isVariadic ? '...' : '') . $this->type->render(); } } public function getType() { return $this->type; } }
<?php namespace Swaggest\GoCodeBuilder\Templates\Func; use Swaggest\GoCodeBuilder\Templates\GoTemplate; use Swaggest\GoCodeBuilder\Templates\Type\AnyType; use Swaggest\GoCodeBuilder\Templates\Type\Type; class Argument extends GoTemplate { /** @var string */ public $name; /** @var AnyType */ public $type; /** @var boolean */ public $isVariadic; /** * Argument constructor. * @param string $name * @param AnyType $type * @param bool $isVariadic */ public function __construct($name, AnyType $type, $isVariadic = false) { $this->name = $name; $this->type = $type; $this->isVariadic = $isVariadic; } protected function toString() { if ($this->name === null) { return $this->type->render(); } else { return $this->name . ' ' . $this->type->render() . ($this->isVariadic ? '...' : ''); } } public function getType() { return $this->type; } }
Use composer autoload file when available Fix task symfony generate:project with sfDoctrinePlugin (GH-10)
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ // Try autoloading using composer if available. if (!file_exists($autoload = dirname(__FILE__).'/../../../../autoload.php')) { $autoload = dirname(__FILE__).'/../../autoload.php'; } require_once $autoload; try { $dispatcher = new sfEventDispatcher(); $logger = new sfCommandLogger($dispatcher); $application = new sfSymfonyCommandApplication($dispatcher, null, array('symfony_lib_dir' => realpath(dirname(__FILE__).'/..'))); $statusCode = $application->run(); } catch (Exception $e) { if (!isset($application)) { throw $e; } $application->renderException($e); $statusCode = $e->getCode(); exit(is_numeric($statusCode) && $statusCode ? $statusCode : 1); } exit(is_numeric($statusCode) ? $statusCode : 0);
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once(dirname(__FILE__).'/../autoload/sfCoreAutoload.class.php'); sfCoreAutoload::register(); try { $dispatcher = new sfEventDispatcher(); $logger = new sfCommandLogger($dispatcher); $application = new sfSymfonyCommandApplication($dispatcher, null, array('symfony_lib_dir' => realpath(dirname(__FILE__).'/..'))); $statusCode = $application->run(); } catch (Exception $e) { if (!isset($application)) { throw $e; } $application->renderException($e); $statusCode = $e->getCode(); exit(is_numeric($statusCode) && $statusCode ? $statusCode : 1); } exit(is_numeric($statusCode) ? $statusCode : 0);
Create postit, not linking to board_id yet
package main import ( "io" "io/ioutil" "net/http" "time" "fmt" "encoding/json" "strconv" ) type Postit struct { Id string Title string Coords [2]int Board_id string //FIXME : corners } var Postits []Postit func ListPostits(w http.ResponseWriter, req *http.Request) { board_id := req.URL.Query().Get("Board_id") if board_id != "" { //FIXME: return JSON array io.WriteString(w, "Listing postits: "+board_id+"\n") } fmt.Printf("Available postits=%v\n", Postits) } func ShowPostit(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Showing postit # "+req.URL.Query().Get(":Id")+"!\n") // FIXME : return postit attributes } func CreatePostit(w http.ResponseWriter, req *http.Request) { postit := &Postit{} defer req.Body.Close() body, err := ioutil.ReadAll(req.Body) if err != nil { fmt.Printf("%s", err) } erru := json.Unmarshal(body, &postit) if erru != nil { fmt.Println("Cannot unmarshal to postit: %s", err) } // FIXME : move that somewhere else, with a decent UID postit.Id = strconv.FormatInt(time.Now().UnixNano(), 10) postit.Coords = [2]int{1,1} // FIXME : add postit to relevant board postits list Postits = append(Postits, *postit) }
package main import ( "io" "net/http" ) type Postit struct { Id string Title string Coords [2]int Board_id string //FIXME : corners } func ListPostits(w http.ResponseWriter, req *http.Request) { board_id := req.URL.Query().Get("Board_id") io.WriteString(w, "Listing postits: "+board_id+"\n") // FIXME : without parameters, return nothing // with a valid board_d, return the list } func ShowPostit(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Showing postit # "+req.URL.Query().Get(":Id")+"!\n") // FIXME : return postit attributes } func CreatePostit(w http.ResponseWriter, req *http.Request) { //FIXME : refuse without a valid board id io.WriteString(w, "Creating postit for board #"+req.URL.Query().Get("board_id")+"!\n") }
Handle device_id set as commandline argument.
package net.siciarz.openlaundryapi.client; import java.net.URL; import org.codehaus.jackson.map.ObjectMapper; /** * Entry point to the application. * */ public class App { public static void main(String[] args) { System.out.println("Open Laundry API Java client"); String deviceId = "666"; if (args.length > 0) { deviceId = args[0]; } try { URL apiUrl = new URL("http://openlaundryapi.org/api/device/" + deviceId + "/"); ObjectMapper mapper = new ObjectMapper(); Device device = mapper.readValue(apiUrl, Device.class); System.out.println(device.getName()); } catch (Exception e) { e.printStackTrace(); } } }
package net.siciarz.openlaundryapi.client; import java.net.URL; import org.codehaus.jackson.map.ObjectMapper; /** * Entry point to the application. * */ public class App { public static void main(String[] args) { System.out.println("Open Laundry API Java client"); URL apiUrl; try { apiUrl = new URL("http://openlaundryapi.org/api/device/666/"); ObjectMapper mapper = new ObjectMapper(); Device device = mapper.readValue(apiUrl, Device.class); System.out.println(device.getName()); } catch (Exception e) { e.printStackTrace(); } } }
Add comments to the Map handler.
package handler import ( "github.com/materials-commons/config/cfg" ) type mapHandler struct { values map[string]interface{} } // Map creates a handler that stores all values in a hashmap. It is commonly used // as a component to build more complex handlers. func Map() cfg.Handler { return &mapHandler{values: make(map[string]interface{})} } // Init initializes the handler. func (h *mapHandler) Init() error { return nil } // Get retrieves a keys value. func (h *mapHandler) Get(key string, args ...interface{}) (interface{}, error) { if len(args) != 0 { return nil, cfg.ErrArgsNotSupported } val, found := h.values[key] if !found { return val, cfg.ErrKeyNotFound } return val, nil } // Set sets the value of keys. You can create new keys, or modify existing ones. // Values are not persisted across runs. func (h *mapHandler) Set(key string, value interface{}, args ...interface{}) error { if len(args) != 0 { return cfg.ErrArgsNotSupported } h.values[key] = value return nil } // Args returns false. This handler doesn't accept additional arguments. func (h *mapHandler) Args() bool { return false }
package handler import ( "github.com/materials-commons/config/cfg" ) type mapHandler struct { values map[string]interface{} } func Map() cfg.Handler { return &mapHandler{values: make(map[string]interface{})} } func (h *mapHandler) Init() error { return nil } func (h *mapHandler) Get(key string, args ...interface{}) (interface{}, error) { if len(args) != 0 { return nil, cfg.ErrArgsNotSupported } val, found := h.values[key] if !found { return val, cfg.ErrKeyNotFound } return val, nil } // Set sets the value of keys. You can create new keys, or modify existing ones. // Values are not persisted across runs. func (h *mapHandler) Set(key string, value interface{}, args ...interface{}) error { if len(args) != 0 { return cfg.ErrArgsNotSupported } h.values[key] = value return nil } // Args returns false. This handler doesn't accept additional arguments. func (h *mapHandler) Args() bool { return false }
Use Drupal's content language detection instead of interface detection.
<?php namespace Prophets\DrupalJsonApi\Scopes; use Prophets\DrupalJsonApi\Contracts\DrupalScope; use Prophets\DrupalJsonApi\Request\DrupalJsonApiRequestBuilder; class LanguageScope implements DrupalScope { /** * @var null */ protected $locale; /** * LanguageScope constructor. * @param null $locale */ public function __construct($locale = null) { $this->locale = $locale ?: config('app.locale'); } /** * Localize the request to the Drupal JSON API. * Note: this will not limit resources to the locale, if no resource was found, * the API will return the resource in it's "original" language. * To limit resources to a specific language add a filter on the resources' field * which represents it's locale. For example, for resources based on a Drupal Node resource, * use the NodeLangcodeScope. * @param DrupalJsonApiRequestBuilder $requestBuilder */ public function apply(DrupalJsonApiRequestBuilder $requestBuilder) { $requestBuilder->setUriQueryParam('language_content_entity', $this->locale); } }
<?php namespace Prophets\DrupalJsonApi\Scopes; use Prophets\DrupalJsonApi\Contracts\DrupalScope; use Prophets\DrupalJsonApi\Request\DrupalJsonApiRequestBuilder; class LanguageScope implements DrupalScope { /** * @var null */ protected $locale; /** * LanguageScope constructor. * @param null $locale */ public function __construct($locale = null) { $this->locale = $locale ?: config('app.locale'); } /** * Localize the request to the Drupal JSON API. * Note: this will not limit resources to the locale, if no resource was found, * the API will return the resource in it's "original" language. * To limit resources to a specific language add a filter on the resources' field * which represents it's locale. For example, for resources based on a Drupal Node resource, * use the NodeLangcodeScope. * @param DrupalJsonApiRequestBuilder $requestBuilder */ public function apply(DrupalJsonApiRequestBuilder $requestBuilder) { $requestBuilder->setUriQueryParam('language', $this->locale); } }
Remove the scope and use the closure
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { const ctx = {}; const context = { _id: '__cC' + i++, _defaultValue: defaultValue, Consumer(props, context) { this.shouldComponentUpdate = function (_props, _state, _context) { return _context !== context || props.children !== _props.children; }; return props.children(context); }, Provider(props) { if (!this.getChildContext) { const subs = []; this.getChildContext = () => { ctx[context._id] = this; return ctx; }; this.shouldComponentUpdate = props => { subs.some(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; this.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old.call(c); }; }; } return props.children; } }; context.Consumer.contextType = context; return context; }
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { const ctx = {}; const context = { _id: '__cC' + i++, _defaultValue: defaultValue, Consumer(props, context) { this.shouldComponentUpdate = function (_props, _state, _context) { return _context !== context || this.props.children !== _props.children; }; return props.children(context); }, Provider(props) { if (!this.getChildContext) { const subs = []; this.getChildContext = () => { ctx[context._id] = this; return ctx; }; this.shouldComponentUpdate = props => { subs.some(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; this.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old.call(c); }; }; } return props.children; } }; context.Consumer.contextType = context; return context; }
Clean up method names and internals
var Keen = require('keen-tracking'); var extend = require('keen-tracking/lib/utils/extend'); // Accessor methods function readKey(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = str ? String(str) : null; return this; } function queryPath(str){ if (!arguments.length) return this.config.queryPath; if (!this.projectId()) { this.emit('error', 'Keen is missing a projectId property'); return; } this.config.queryPath = str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries'); return this; } // Query method function query(){} // HTTP methods function get(){} function post(){} function put(){} function del(){} // Extend client instance extend(Keen.prototype, { 'readKey' : readKey, 'queryPath' : queryPath, 'query' : query, 'get' : get, 'post' : post, 'put' : put, 'del' : del }); // console.log(new Keen({ projectId: '123' }).queryPath('test').queryPath()); module.exports = Keen;
var Keen = require('keen-tracking'); var extend = require('keen-tracking/lib/utils/extend'); // Accessor methods function readKey(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = (str ? String(str) : null); return this; } function queryPath(str){ if (!arguments.length) return this.config.readPath; if (!this.projectId()) { this.emit('error', 'Keen is missing a projectId property'); return; } this.config.readPath = (str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries')); return this; } // Query method function query(){} // HTTP methods function get(){} function post(){} function put(){} function del(){} // Extend client instance extend(Keen.prototype, { 'readKey' : readKey, 'queryPath' : queryPath, 'query' : query, 'get' : get, 'post' : post, 'put' : put, 'del' : del }); module.exports = Keen;
Add `commands` property to `CommandManager` to allow retrieving the command table
class CommandRegistrar(): """A singleton to manage the command table and command execution""" _instance = None def __init__(self): self.command_table = {} @staticmethod def instance(): """Get the singleton, create an instance if needed""" if not CommandRegistrar._instance: CommandRegistrar._instance = CommandRegistrar() return CommandRegistrar._instance @staticmethod async def execute_command(shards, shard, msg): # !roll 100 -> 'roll' instance = CommandRegistrar.instance() command = msg.content[1:].split(' ')[0].lower() if command in instance.command_table.keys(): await instance.command_table[command].execute(shards, shard, msg) @property def commands(self): return self.command_table @property def loaded_commands(self): return [command.name for command in set(self.command_table.values())] @property def loaded_aliases(self): return list(self.command_table.keys())
class CommandRegistrar(): """A singleton to manage the command table and command execution""" _instance = None def __init__(self): self.command_table = {} @staticmethod def instance(): """Get the singleton, create an instance if needed""" if not CommandRegistrar._instance: CommandRegistrar._instance = CommandRegistrar() return CommandRegistrar._instance @staticmethod async def execute_command(shards, shard, msg): # !roll 100 -> 'roll' instance = CommandRegistrar.instance() command = msg.content[1:].split(' ')[0].lower() if command in instance.command_table.keys(): await instance.command_table[command].execute(shards, shard, msg) @property def loaded_commands(self): return [command.name for command in set(self.command_table.values())] @property def loaded_aliases(self): return list(self.command_table.keys())
Fix template to remind about Main filename
package dgcj; public class TemplateDgcjMain { // RENAME to Main static final Object PROBLEM = new TemplateDgcjProblem(); // PROBLEM NAME goes here public String run() { // long n = ; // long from = 1L * n * ID / NODES; // long to = 1L * n * (ID + 1) / NODES; return null; } static int NODES; static int ID; /** * Arguments: * "" = as for submit * "0" = run multi node infrastructure * "1" = run single node */ public static void main(String[] args) { PROBLEM.equals(args); // Local testing framework invocation boolean single = args != null && args.length == 1 && "1".equals(args[0]); NODES = single ? 1 : message.NumberOfNodes(); ID = single ? 0 : message.MyNodeId(); String ans = new TemplateDgcjMain().run(); if (ans != null) { System.out.println(ans); } } public void log(String msg) { PROBLEM.equals(ID + ": " + msg); // Local testing framework log } }
package dgcj; public class TemplateDgcjMain { static final Object PROBLEM = new TemplateDgcjProblem(); // PROBLEM NAME goes here public String run() { // long n = ; // long from = 1L * n * ID / NODES; // long to = 1L * n * (ID + 1) / NODES; return null; } static int NODES; static int ID; /** * Arguments: * "" = as for submit * "0" = run multi node infrastructure * "1" = run single node */ public static void main(String[] args) { PROBLEM.equals(args); // Local testing framework invocation boolean single = args != null && args.length == 1 && "1".equals(args[0]); NODES = single ? 1 : message.NumberOfNodes(); ID = single ? 0 : message.MyNodeId(); String ans = new TemplateDgcjMain().run(); if (ans != null) { System.out.println(ans); } } public void log(String msg) { PROBLEM.equals(ID + ": " + msg); // Local testing framework log } }
Add new dump public method
import logging import pkg_resources import sys from types import ModuleType # allow high-level functions to be accessed directly from the mappyfile module from mappyfile.utils import load, loads, find, findall, dumps, write __version__ = "0.6.2" __all__ = ['load', 'loads', 'find', 'findall', 'dumps', 'dump', 'write'] plugins = ModuleType('mappyfile.plugins') sys.modules['mappyfile.plugins'] = plugins for ep in pkg_resources.iter_entry_points(group='mappyfile.plugins'): setattr(plugins, ep.name, ep.load()) # Set default logging handler to avoid "No handler found" warnings. try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger("mappyfile").addHandler(NullHandler())
import logging import pkg_resources import sys from types import ModuleType # allow high-level functions to be accessed directly from the mappyfile module from mappyfile.utils import load, loads, find, findall, dumps, write __version__ = "0.6.2" __all__ = ['load', 'loads', 'find', 'findall', 'dumps', 'write'] plugins = ModuleType('mappyfile.plugins') sys.modules['mappyfile.plugins'] = plugins for ep in pkg_resources.iter_entry_points(group='mappyfile.plugins'): setattr(plugins, ep.name, ep.load()) # Set default logging handler to avoid "No handler found" warnings. try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger("mappyfile").addHandler(NullHandler())
Fix command line options for join group.
/* Copyright 2017 Streampunk Media Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var dgram = require('dgram'); var argv = require('yargs') .default('p', 6789) .default('a', '234.5.6.7') .number('p') .usage('Join a multicast group. Useful for wireshark testing.\n' + 'Usage: $0 ') .help() .describe('a', 'Address of multicast group to join.') .describe('p', 'Port of multicast group to join.') .describe('i', 'Multicast interface.') .argv; var socket = dgram.createSocket('udp4'); socket.addMembership(argv.a, argv.i); socket.on('listening', () => { console.log('Multicast group subscribed and listening.'); }); socket.on('error', console.error); socket.bind(argv.p);
/* Copyright 2017 Streampunk Media Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var dgram = require('dgram'); var argv = require('yargs') .default('p', 6789) .default('a', '234.5.6.7') .demandOption(['i']) .number('p') .usage('Join a multicast group. Useful for wireshark testing.\n' + 'Usage: $0 ') .help() .describe('a', 'Address of multicast group to join.') .describe('g', 'Port of multicast group to join.') .describe('i', 'Multicast interface.') .argv; var socket = dgram.createSocket('udp4'); var addr = process.argv[2]; var port = +process.argv[3]; socket.addMembership(argv.a, argv.i); socket.on('listening', () => { console.log('Multicast group subscribed and listening.'); }); socket.on('error', console.error); socket.bind(argv.p);
Set default language for model/form translation strings. Have to changed for English installation! (Template strings are translated automatically by selected browser language)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ openslides.default.settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Global Django settings file for OpenSlides. :copyright: 2011, 2012 by OpenSlides team, see AUTHORS. :license: GNU GPL, see LICENSE for more details. """ from openslides_settings import * # Use 'DEBUG = True' to get more details for server errors (Default for relaeses: 'False') DEBUG = True TEMPLATE_DEBUG = DEBUG TIME_ZONE = 'Europe/Berlin' # Default language for model/form translation strings LANGUAGE_CODE = 'de' # Make this unique, and don't share it with anybody. SECRET_KEY = '=(v@$58k$fcl4y8t2#q15y-9p=^45y&!$!ap$7xo6ub$akg-!5' # Add OpenSlides plugins to this list (see example entry in comment) INSTALLED_PLUGINS = ( # 'pluginname', ) INSTALLED_APPS += INSTALLED_PLUGINS
#!/usr/bin/env python # -*- coding: utf-8 -*- """ openslides.default.settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Global settings file. :copyright: 2011, 2012 by OpenSlides team, see AUTHORS. :license: GNU GPL, see LICENSE for more details. """ # Django settings for openslides project. from openslides_settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG TIME_ZONE = 'Europe/Berlin' # Make this unique, and don't share it with anybody. SECRET_KEY = '=(v@$58k$fcl4y8t2#q15y-9p=^45y&!$!ap$7xo6ub$akg-!5' # Add OpenSlides plugins to this list (see example entry in comment) INSTALLED_PLUGINS = ( # 'pluginname', ) INSTALLED_APPS += INSTALLED_PLUGINS
Make every plugin receive a bound version of the lifecycle
const Hooter = require('hooter') const EVENTS = [ ['init', 'sync'], ['start', 'sync'], ['execute', 'async'], ['execute.batch', 'async'], ['execute.one', 'async'], ['execute.handle', 'async'], ['error', 'sync'], ] module.exports = function comanche(args, plugins) { let lifecycle = new Hooter() if (!Array.isArray(plugins)) { throw new Error('Plugins must be an array of functions') } EVENTS.forEach(([event, mode]) => { lifecycle.register(event, mode) }) plugins.forEach((plugin) => { plugin(lifecycle.bind(plugin)) }) return lifecycle.tootWith('init', (Class) => { if (!Class) { throw new Error( 'No interface has been defined. At least one plugin must define ' + 'an interface during the "init" event' ) } return new Class(...args) }) }
const Hooter = require('hooter') const EVENTS = [ ['init', 'sync'], ['start', 'sync'], ['execute', 'async'], ['execute.batch', 'async'], ['execute.one', 'async'], ['execute.handle', 'async'], ['error', 'sync'], ] module.exports = function comanche(args, plugins) { let lifecycle = new Hooter() if (!Array.isArray(plugins)) { throw new Error('Plugins must be an array of functions') } EVENTS.forEach(([event, mode]) => { lifecycle.register(event, mode) }) plugins.forEach((plugin) => plugin(lifecycle)) return lifecycle.tootWith('init', (Class) => { if (!Class) { throw new Error( 'No interface has been defined. At least one plugin must define ' + 'an interface during the "init" event' ) } return new Class(...args) }) }
Remove another reference to filter
from functools import partial class Library: ''' Container for registering tags and helpers ''' def __init__(self): self.tags = {} self.helpers = {} def tag(self, func=None, name=None): if func is None: return partial(self.tag, name=name) if name is None: name = func.__name__ self.tags[name] = func return func def helper(self, func=None, name=None): if func is None: return partial(self.helper, name=name) if name is None: name = func.__name__ self.helpers[name] = func return func
from functools import partial class Library: ''' Container for registering tags and filters ''' def __init__(self): self.tags = {} self.filters = {} self.helpers = {} def tag(self, func=None, name=None): if func is None: return partial(self.tag, name=name) if name is None: name = func.__name__ self.tags[name] = func return func def helper(self, func=None, name=None): if func is None: return partial(self.helper, name=name) if name is None: name = func.__name__ self.helpers[name] = func return func
Make DictFile remove its meta data file when calling clear()
import os import json import logging LOGGER = logging.getLogger(__name__) class DictFile(dict): """A ``dict``, storable as a JSON file. """ def __init__(self, file_path): super(DictFile, self).__init__() self.__file_path = file_path self.reload() def reload(self): if os.path.isfile(self.__file_path): LOGGER.debug('Loading %s', self.__file_path) with open(self.__file_path) as f: self.update(json.load(f)) def clear(self): """Force the dictionary to be empty. """ if os.path.isfile(self.__file_path): os.unlink(self.__file_path) super(DictFile, self).clear() def save(self): LOGGER.debug('Writing %s', self.__file_path) with open(self.__file_path, 'w') as f: json.dump(self, f, indent=4)
import os import json import logging LOGGER = logging.getLogger(__name__) class DictFile(dict): """A ``dict``, storable as a JSON file. """ def __init__(self, file_path): super(DictFile, self).__init__() self.__file_path = file_path self.reload() def reload(self): if os.path.isfile(self.__file_path): LOGGER.debug('Loading %s', self.__file_path) with open(self.__file_path) as f: self.update(json.load(f)) def save(self): LOGGER.debug('Writing %s', self.__file_path) with open(self.__file_path, 'w') as f: json.dump(self, f, indent=4)
Remove dead code from SNMP event processing
/** * */ package com.boundary.sdk; import java.util.Date; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.boundary.sdk.RawEvent; import com.boundary.sdk.Severity; /** * @author davidg * */ public class SNMPToEventProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(SNMPToEventProcessor.class); public SNMPToEventProcessor() { } @Override public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); LOG.debug("class: {}",message.getBody().getClass().toString()); // Create our event so that we can populate with the Syslog data RawEvent event = new RawEvent(); Date dt = new java.util.Date(); event.setTitle("SNMP TRAP " + dt); event.setStatus(Status.OPEN); event.setSeverity(Severity.WARN); event.getSource().setRef("localhost"); event.getSource().setType("host"); // event.setMessage(message.getBody().toString()); // event.putProperty("message",message.getBody().toString()); event.putFingerprintField("@title"); message.setBody(event, RawEvent.class); } }
/** * */ package com.boundary.sdk; import java.util.Date; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.syslog.SyslogMessage; import org.apache.camel.component.syslog.SyslogSeverity; import com.boundary.sdk.RawEvent; import com.boundary.sdk.Severity; /** * @author davidg * */ public class SNMPToEventProcessor implements Processor { private boolean debug = false; /** * */ public SNMPToEventProcessor() { this(false); } public SNMPToEventProcessor(boolean debug) { // TODO Auto-generated constructor stub } private final String CAMEL_SYSLOG_HOSTNAME = "CamelSyslogHostname"; private final String CAMEL_SYSLOG_SEVERITY = "CamelSyslogSeverity"; @Override public void process(Exchange exchange) throws Exception { // Get the CamelContext and Message CamelContext context = exchange.getContext(); Message message = exchange.getIn(); // Create our event so that we can populate with the Syslog data RawEvent event = new RawEvent(); event = event.getDefaultEvent(); Date dt = new java.util.Date(); event.setTitle("SNMP TRAP " + dt); event.setSeverity(Severity.CRITICAL); // Delegate to member method call to perform the translation //this.translateSyslogMessage(message, event); message.setBody(event, RawEvent.class); } }
Allow not to specify sender tab id. Detect it implicitly
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId || port.sender.tab.id] = port; if (tab && message.tabId !== tab.id) { error(port); return; } port.postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId] = port; if (tab && message.tabId !== tab.id) { error(port); return; } connections[message.tabId].postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
Fix nasty bug with calculating bytes in patterns
export const dataFactory = buffer => { const data = new DataView(buffer); let offset = 0; return { hasNext() { return offset < data.byteLength; }, nextString() { let str = ''; for (let i = 0; i < 4; i++) { str += String.fromCharCode(data.getUint8(offset, true)); offset += 1; } return str; }, nextInt() { const int = data.getUint32(offset, true); offset += 4; return int; }, nextFloat() { const float = data.getFloat32(offset, true); offset += 4; return float; }, nextPattern(pattern, bytes) { return pattern.reduce((obj, key) => { obj[key] = data[`getUint${bytes * 8}`](offset, true); offset += bytes; return obj; }, {}); }, }; };
export const dataFactory = buffer => { const data = new DataView(buffer); let offset = 0; return { hasNext() { return offset < data.byteLength; }, nextString() { let str = ''; for (let i = 0; i < 4; i++) { str += String.fromCharCode(data.getUint8(offset, true)); offset += 1; } return str; }, nextInt() { const int = data.getUint32(offset, true); offset += 4; return int; }, nextFloat() { const float = data.getFloat32(offset, true); offset += 4; return float; }, nextPattern(pattern, bytes) { return pattern.reduce((obj, key) => { obj[key] = data[`getUint${bytes * 4}`](offset, true); offset += bytes; return obj; }, {}); }, }; };
Enforce consistent artisan command tag namespacing
<?php declare(strict_types=1); namespace Rinvex\Auth\Console\Commands; use Illuminate\Console\Command; class PublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=all}'; /** * The console command description. * * @var string */ protected $description = 'Publish Rinvex Auth Resources.'; /** * Execute the console command. * * @return void */ public function handle(): void { $this->alert($this->description); $this->call('vendor:publish', ['--tag' => 'rinvex/auth::config', '--force' => $this->option('force')]); $this->line(''); } }
<?php declare(strict_types=1); namespace Rinvex\Auth\Console\Commands; use Illuminate\Console\Command; class PublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=all}'; /** * The console command description. * * @var string */ protected $description = 'Publish Rinvex Auth Resources.'; /** * Execute the console command. * * @return void */ public function handle(): void { $this->alert($this->description); $this->call('vendor:publish', ['--tag' => 'rinvex-auth-config', '--force' => $this->option('force')]); $this->line(''); } }
Use new AuthMethod configuration for Heroku
#!/usr/bin/env python from evesrp import create_app from evesrp.killmail import CRESTMail, ShipURLMixin from evesrp.auth.testauth import TestAuth from os import environ as env from binascii import unhexlify skel_url = 'https://wiki.eveonline.com/en/wiki/{name}' class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): pass app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = env['DATABASE_URL'] app.config['SECRET_KEY'] = unhexlify(env['SECRET_KEY']) app.config['USER_AGENT_EMAIL'] = 'paxswill@paxswill.com' app.config['AUTH_METHODS'] = [TestAuth()] app.config['CORE_AUTH_PRIVATE_KEY'] = env.get('CORE_PRIVATE_KEY') app.config['CORE_AUTH_PUBLIC_KEY'] = env.get('CORE_PUBLIC_KEY') app.config['CORE_AUTH_IDENTIFIER'] = env.get('CORE_IDENTIFIER') app.config['KILLMAIL_SOURCES'] = [EOWikiCREST] if env.get('DEBUG') is not None: app.debug = True if __name__ == '__main__': # So we get the database tables for these from evesrp.auth.testauth import TestUser, TestGroup print("Creating databases...") app.extensions['sqlalchemy'].db.create_all(app=app)
#!/usr/bin/env python from evesrp import create_app from evesrp.killmail import CRESTMail, ShipURLMixin import evesrp.auth.testauth from os import environ as env from binascii import unhexlify skel_url = 'https://wiki.eveonline.com/en/wiki/{name}' class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): pass app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = env['DATABASE_URL'] app.config['SECRET_KEY'] = unhexlify(env['SECRET_KEY']) app.config['USER_AGENT_EMAIL'] = 'paxswill@paxswill.com' app.config['AUTH_METHODS'] = ['evesrp.auth.testauth.TestAuth'] app.config['CORE_AUTH_PRIVATE_KEY'] = env.get('CORE_PRIVATE_KEY') app.config['CORE_AUTH_PUBLIC_KEY'] = env.get('CORE_PUBLIC_KEY') app.config['CORE_AUTH_IDENTIFIER'] = env.get('CORE_IDENTIFIER') app.config['KILLMAIL_SOURCES'] = [EOWikiCREST] if env.get('DEBUG') is not None: app.debug = True if __name__ == '__main__': print("Creating databases...") app.extensions['sqlalchemy'].db.create_all(app=app)
Update to work with current-content key This key is populated by ember deploy by default now and is a simpler way to get the current revision's content.
'use strict'; const redis = require('redis'), co = require('co'), coRedis = require('co-redis'), Koa = require('koa'); const app = exports.app = new Koa(), client = redis.createClient( process.env.REDIS_PORT, process.env.REDIS_HOST ), dbCo = coRedis(client); if (process.env.REDIS_SECRET) { client.auth(process.env.REDIS_SECRET); } client.on('error', function (err) { console.log('Redis client error: ' + err); }); app.use(co.wrap(function* (ctx) { var indexkey; if (ctx.request.query.index_key) { indexkey = process.env.APP_NAME +':'+ ctx.request.query.index_key; } else { indexkey = process.env.APP_NAME +':current-content'; } var index = yield dbCo.get(indexkey); if (index) { ctx.body = index; } else { ctx.status = 404; } })); app.listen(process.env.PORT || 3000);
'use strict'; const redis = require('redis'), co = require('co'), coRedis = require('co-redis'), Koa = require('koa'); const app = exports.app = new Koa(), client = redis.createClient( process.env.REDIS_PORT, process.env.REDIS_HOST ), dbCo = coRedis(client); if (process.env.REDIS_SECRET) { client.auth(process.env.REDIS_SECRET); } client.on('error', function (err) { console.log('Redis client error: ' + err); }); app.use(co.wrap(function* (ctx) { var indexkey; if (ctx.request.query.index_key) { indexkey = process.env.APP_NAME +':'+ ctx.request.query.index_key; } else { indexkey = yield dbCo.get(process.env.APP_NAME +':current'); indexkey = process.env.APP_NAME + ':' + indexkey; } var index = yield dbCo.get(indexkey); if (index) { ctx.body = index; } else { ctx.status = 404; } })); app.listen(process.env.PORT || 3000);
Move db fixture to the inside of the method
import pytest __version__ = '0.1.1' def pytest_configure(config): # Register the marks config.addinivalue_line( 'markers', 'haystack: Mark the test as using the django-haystack search engine, ' 'rebuilding the index for each test.') @pytest.fixture(autouse=True) def _haystack_marker(request): """ Implement the 'haystack' marker. This rebuilds the index at the start of each test and clears it at the end. """ marker = request.keywords.get('haystack', None) if marker: from pytest_django.lazy_django import skip_if_no_django from django.core.management import call_command request.getfuncargvalue('db') def clear_index(): call_command('clear_index', interactive=False) # Skip if Django is not configured skip_if_no_django() request.addfinalizer(clear_index) call_command('rebuild_index', interactive=False)
import pytest __version__ = '0.1.1' def pytest_configure(config): # Register the marks config.addinivalue_line( 'markers', 'haystack: Mark the test as using the django-haystack search engine, ' 'rebuilding the index for each test.') @pytest.fixture(autouse=True) def _haystack_marker(request, db): """ Implement the 'haystack' marker. This rebuilds the index at the start of each test and clears it at the end. """ marker = request.keywords.get('haystack', None) if marker: from pytest_django.lazy_django import skip_if_no_django from django.core.management import call_command def clear_index(): call_command('clear_index', interactive=False) # Skip if Django is not configured skip_if_no_django() request.addfinalizer(clear_index) call_command('rebuild_index', interactive=False)
Fix typos in Hungarian translation Some words in the translation were mistyped like "vasámap" which should be "vasárnap" (means Sunday).
// Hungarian jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december' ], monthsShort: [ 'jan', 'febr', 'márc', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat' ], weekdaysShort: [ 'V', 'H', 'K', 'SZe', 'CS', 'P', 'SZo' ], today: 'Ma', clear: 'Törlés', firstDay: 1, format: 'yyyy. mmmm dd.', formatSubmit: 'yyyy/mm/dd' });
// Hungarian jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'január', 'február', 'március', 'aprilis', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december' ], monthsShort: [ 'jan', 'febr', 'márc', 'apr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'vasámap', 'hétfö', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat' ], weekdaysShort: [ 'V', 'H', 'K', 'SZ', 'CS', 'P', 'SZ' ], today: 'ma', clear: 'töröl', firstDay: 1, format: 'yyyy. mmmm dd.', formatSubmit: 'yyyy/mm/dd' });
Change the default Pull policy to PullIfNotPresent. Kubernetes-commit: 81107c3e986956601869c687a17ba690bb551fa9
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api import ( "strings" ) func IsPullAlways(p PullPolicy) bool { return pullPoliciesEqual(p, PullAlways) } func IsPullNever(p PullPolicy) bool { return pullPoliciesEqual(p, PullNever) } func IsPullIfNotPresent(p PullPolicy) bool { // Default to pull if not present if len(p) == 0 { return true } return pullPoliciesEqual(p, PullIfNotPresent) } func pullPoliciesEqual(p1, p2 PullPolicy) bool { return strings.ToLower(string(p1)) == strings.ToLower(string(p2)) }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api import ( "strings" ) func IsPullAlways(p PullPolicy) bool { // Default to pull always if len(p) == 0 { return true } return pullPoliciesEqual(p, PullAlways) } func IsPullNever(p PullPolicy) bool { return pullPoliciesEqual(p, PullNever) } func IsPullIfNotPresent(p PullPolicy) bool { return pullPoliciesEqual(p, PullIfNotPresent) } func pullPoliciesEqual(p1, p2 PullPolicy) bool { return strings.ToLower(string(p1)) == strings.ToLower(string(p2)) }
Print ancestors of a node completed
package GeeksforGeeksPractice; import java.util.Arrays; public class _0016PrintAncestorsOfANode { static int[] path; public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static void main(String args[]){ path=new int[1000]; TreeNode tn=new TreeNode(50); tn.left=new TreeNode(8); tn.right=new TreeNode(2); tn.left.left=new TreeNode(3); tn.left.right=new TreeNode(5); tn.right.left=new TreeNode(1); tn.right.right=new TreeNode(30); getAncestorsOfANode(tn,path,0,30); } public static void getAncestorsOfANode(TreeNode tn,int[] path,int pathLen,int val) { if(tn!=null) { path[pathLen]=tn.val; pathLen++; if(tn.val==val) { System.out.println(Arrays.toString(Arrays.copyOf(path, pathLen))); } getAncestorsOfANode(tn.left, path, pathLen, val); getAncestorsOfANode(tn.right, path, pathLen, val); } } }
package GeeksforGeeksPractice; public class _0016PrintAncestorsOfANode { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static void main(String args[]){ TreeNode tn=new TreeNode(50); tn.left=new TreeNode(8); tn.right=new TreeNode(2); tn.left.left=new TreeNode(3); //tn.left.right=new TreeNode(5); //tn.right.left=new TreeNode(1); tn.right.right=new TreeNode(30); //getAncestorsOfANode(tn,8,0); } public static boolean getAncestorsOfANode(TreeNode tn,int val) { if(tn!=null) { return false; } return true; } }
Move the action to the outer question object This is a bit more question independant, and more expressive.
importScripts("/app/bower_components/videogular-questions/questions-worker.js"); loadAnnotations({ "first-question": { time: 4, questions: [ { id: "first-question", type: "single", question: "What is the moon made of?", options: [ { name: "cheese" }, { name: "cheeese" }, { name: "cheeeeeese" } ] }, { id: "check-question", type: "single", question: "Answer incorrect, do you want to review the video", options: [ { name: "Yes" }, { name: "No" } ], action: function(result, video) { if (result === "Yes") { video.setTime(0); } }, condition: function(questions, result) { // show if the answer to the previous question is not "cheese" return result !== "cheese"; } } ] } });
importScripts("/app/bower_components/videogular-questions/questions-worker.js"); loadAnnotations({ "first-question": { time: 4, questions: [ { id: "first-question", type: "single", question: "What is the moon made of?", options: [ { name: "cheese" }, { name: "cheeese" }, { name: "cheeeeeese" } ] }, { id: "check-question", type: "single", question: "Answer incorrect, do you want to review the video", options: [ { name: "Yes", action: function(video) { video.setTime(0); } }, { name: "No" } ], condition: function(questions, result) { // show if the answer to the previous question is not "cheese" return result !== "cheese"; } } ] } });
Remove alias from service provider Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Asset; use Illuminate\Support\ServiceProvider; class AssetServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var boolean */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->app['orchestra.asset'] = $this->app->share(function ($app) { return new Environment($app); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('orchestra.asset'); } }
<?php namespace Orchestra\Asset; use Illuminate\Support\ServiceProvider; use Illuminate\Foundation\AliasLoader; class AssetServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var boolean */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->app['orchestra.asset'] = $this->app->share(function ($app) { return new Environment($app); }); $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Orchestra\Asset', 'Orchestra\Support\Facades\Asset'); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('orchestra.asset'); } }
Fix tweet formatting issues when streaming from twitter
import sys from itertools import ifilter from requests_oauthlib import OAuth1Session import json class TwitterDataIngestSource: """Ingest data from Twitter""" def __init__(self, config): self.config = config def __iter__(self): if 'track' in self.config: self.track = self.config['track'] else: self.track = 'ski,surf,board' auth = OAuth1Session( self.config['consumer_key'], client_secret = self.config['consumer_secret'], resource_owner_key = self.config['access_token'], resource_owner_secret = self.config['access_token_secret'] ) request = auth.post( 'https://stream.twitter.com/1.1/statuses/filter.json', data = 'track=' + self.track, stream = True ) # filter out empty lines sent to keep the stream alive self.source_iterator = ifilter(lambda x: x, request.iter_lines()) return self def next(self): return { 'tweet' : json.loads(self.source_iterator.next()) }
import sys from itertools import ifilter from requests_oauthlib import OAuth1Session class TwitterDataIngestSource: """Ingest data from Twitter""" def __init__(self, config): self.config = config def __iter__(self): if 'track' in self.config: self.track = self.config['track'] else: self.track = 'ski,surf,board' auth = OAuth1Session( self.config['consumer_key'], client_secret = self.config['consumer_secret'], resource_owner_key = self.config['access_token'], resource_owner_secret = self.config['access_token_secret'] ) request = auth.post( 'https://stream.twitter.com/1.1/statuses/filter.json', data = 'track=' + self.track, stream = True ) # filter out empty lines sent to keep the stream alive self.source_iterator = ifilter(lambda x: x, request.iter_lines()) return self def next(self): return self.source_iterator.next()
Use oneline phpdocs for property type info
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Inventory\Model; class InventoryUnit implements InventoryUnitInterface { /** @var mixed */ protected $id; /** @var StockableInterface */ protected $stockable; /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getStockable(): ?StockableInterface { return $this->stockable; } public function setStockable(StockableInterface $stockable): void { $this->stockable = $stockable; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Inventory\Model; class InventoryUnit implements InventoryUnitInterface { /** * @var mixed */ protected $id; /** * @var StockableInterface */ protected $stockable; /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getStockable(): ?StockableInterface { return $this->stockable; } public function setStockable(StockableInterface $stockable): void { $this->stockable = $stockable; } }
Fix native strategy resolution path
function nativeStrategy(data) { const { origin, destination, mode } = data; let originLocation; let destinationLocation; if (typeof origin === 'object' && origin.lat && origin.lng) { originLocation = new google.maps.LatLng(origin); } else { originLocation = origin; } if (typeof destination === 'object' && destination.lat && destination.lng) { destinationLocation = new google.maps.LatLng(destination); } else { destinationLocation = destination; } const DirectionsService = new google.maps.DirectionsService(); return new Promise((resolve, reject) => { DirectionsService.route( { origin: originLocation, destination: destinationLocation, travelMode: mode.toUpperCase(), }, (result, status) => { if (status === google.maps.DirectionsStatus.OK) { resolve(result.routes[0].overview_polyline); } reject(status); } ); }); } export default nativeStrategy;
function nativeStrategy(data) { const { origin, destination, mode } = data; let originLocation; let destinationLocation; if (typeof origin === 'object' && origin.lat && origin.lng) { originLocation = new google.maps.LatLng(origin); } else { originLocation = origin; } if (typeof destination === 'object' && destination.lat && destination.lng) { destinationLocation = new google.maps.LatLng(destination); } else { destinationLocation = destination; } const DirectionsService = new google.maps.DirectionsService(); return new Promise((resolve, reject) => { DirectionsService.route( { origin: originLocation, destination: destinationLocation, travelMode: mode, }, (result, status) => { if (status === google.maps.DirectionsStatus.OK) { resolve(result.routes[0].overview_polyline.points); } reject(status); } ); }); } export default nativeStrategy;
Add comment to solutions sub-tags test
from __future__ import absolute_import, unicode_literals from corehq import toggles from corehq.toggles import ALL_TAGS def test_toggle_properties(): """ Check toggle properties """ for toggle in toggles.all_toggles(): assert toggle.slug assert toggle.label, 'Toggle "{}" label missing'.format(toggle.slug) assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug) assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag) assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug) def test_solutions_sub_tags(): """ Check Solutions sub-tags begin with 'Solutions - ' Client side toggle filtering logic currently depends on "Solutions" being in these tag names. For context, see https://github.com/dimagi/commcare-hq/pull/24575#discussion_r293995391 """ solutions_tags = [toggles.TAG_SOLUTIONS_OPEN, toggles.TAG_SOLUTIONS_CONDITIONAL, toggles.TAG_SOLUTIONS_LIMITED] for tag in solutions_tags: assert tag.name.startswith('Solutions - ')
from __future__ import absolute_import, unicode_literals from corehq import toggles from corehq.toggles import ALL_TAGS def test_toggle_properties(): """ Check toggle properties """ for toggle in toggles.all_toggles(): assert toggle.slug assert toggle.label, 'Toggle "{}" label missing'.format(toggle.slug) assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug) assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag) assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug) def test_solutions_sub_tags(): """ Check Solutions sub-tags begin with 'Solutions - ' """ solutions_tags = [toggles.TAG_SOLUTIONS_OPEN, toggles.TAG_SOLUTIONS_CONDITIONAL, toggles.TAG_SOLUTIONS_LIMITED] for tag in solutions_tags: assert tag.name.startswith('Solutions - ')
Allow query functions to return null when no query needed
/** * Utilities for interacting with the Router and getting location data * @module routeUtils */ import Rx from 'rxjs'; import match from 'react-router/lib/match'; // Create observable from callback-based `match` const match$ = Rx.Observable.bindNodeCallback(match); /** * From the renderProps provided by React Router's `match`, collect the results * of the query properties associated with currently-active routes * * @param matchCallbackArgs {Array} redirectLocation(ignored) and renderProps * @return {Array} The return values of each active route's query function */ function getActiveRouteQueries([ , { routes, location, params }]) { const queries = routes .filter(({ query }) => query) // only get routes with queries .reduce((queries, { query }) => { // assemble into one array of queries const routeQueries = query instanceof Array ? query : [query]; return queries.concat(routeQueries); }, []) .map(queryFn => queryFn({ location, params })) // call the query function .filter(query => query); // empty return values should not be sent return queries; } export const activeRouteQueries$ = routes => location => match$({ routes, location }) .map(getActiveRouteQueries) .filter(queries => queries.length);
/** * Utilities for interacting with the Router and getting location data * @module routeUtils */ import Rx from 'rxjs'; import match from 'react-router/lib/match'; // Create observable from callback-based `match` const match$ = Rx.Observable.bindNodeCallback(match); /** * From the renderProps provided by React Router's `match`, collect the results * of the query properties associated with currently-active routes * * @param matchCallbackArgs {Array} redirectLocation(ignored) and renderProps * @return {Array} The return values of each active route's query function */ function getActiveRouteQueries([ , { routes, location, params }]) { const queries = routes .filter(({ query }) => query) // only get routes with queries .reduce((queries, { query }) => { // assemble into one array of queries const routeQueries = query instanceof Array ? query : [query]; return queries.concat(routeQueries); }, []) .map(query => query({ location, params })); // call the query function return queries; } export const activeRouteQueries$ = routes => location => match$({ routes, location }) .map(getActiveRouteQueries) .filter(queries => queries.length);
Make pynpact tests use GeventExecutor We've almost completely deprecated taskqueue at this point; lets test the new pieces instead of th old.
import pytest def taskqueue_executor(): import taskqueue taskqueue.LISTEN_ADDRESS = ('127.0.1.1', 57129) sm = taskqueue.get_ServerManager(make_server=True) sm.start() request.addfinalizer(sm.shutdown) return sm.Server() @pytest.fixture(scope="session") def async_executor(request): from pynpact.executors import GeventExecutor return GeventExecutor() class NullExecutor(object): "An executor that doens't actually execute anything, just keeps track" tasks = None def __init__(self): self.tasks = {} def enqueue(self, callable, tid=None, after=None): if tid is None: tid = randomid() if after is not None: for aid in after: assert aid in self.tasks, \ "The NullExecutor can't be after a task that doesn't exist yet" if tid not in self.tasks: self.tasks[tid] = callable return tid @pytest.fixture def null_executor(request): return NullExecutor()
import pytest import taskqueue @pytest.fixture(scope="session") def async_executor(request): taskqueue.LISTEN_ADDRESS = ('127.0.1.1', 57129) sm = taskqueue.get_ServerManager(make_server=True) sm.start() request.addfinalizer(sm.shutdown) return sm.Server() class NullExecutor(object): "An executor that doens't actually execute anything, just keeps track" tasks = None def __init__(self): self.tasks = {} def enqueue(self, callable, tid=None, after=None): if tid is None: tid = randomid() if after is not None: for aid in after: assert aid in self.tasks, \ "The NullExecutor can't be after a task that doesn't exist yet" if tid not in self.tasks: self.tasks[tid] = callable return tid @pytest.fixture def null_executor(request): return NullExecutor()
Add shebang for direct execution
#!/usr/bin/php <?php $stdin = file_get_contents('php://stdin'); // remove ANSI escape $stdin = preg_replace('/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/', '', $stdin); $stdin = preg_replace('/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/', '', $stdin); $stdin = preg_replace('/[\x03|\x1a]/', '', $stdin); $config = [ 'api_url' => 'https://api.pushbullet.com/v2/pushes', 'access_token' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'type' => 'note', ]; $ch = curl_init(); $options = [ CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_URL => $config['api_url'], CURLOPT_HTTPHEADER => ['Access-Token:' . $config['access_token']], CURLOPT_POSTFIELDS => [ 'type' => $config['type'], 'title' => '['. gethostname() .'] Script finished', 'body' => 'Output:' . PHP_EOL . $stdin, ], ]; curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch);
<?php $stdin = file_get_contents('php://stdin'); // remove ANSI escape $stdin = preg_replace('/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/', '', $stdin); $stdin = preg_replace('/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/', '', $stdin); $stdin = preg_replace('/[\x03|\x1a]/', '', $stdin); $config = [ 'api_url' => 'https://api.pushbullet.com/v2/pushes', 'access_token' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'type' => 'note', ]; $ch = curl_init(); $options = [ CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_URL => $config['api_url'], CURLOPT_HTTPHEADER => ['Access-Token:' . $config['access_token']], CURLOPT_POSTFIELDS => [ 'type' => $config['type'], 'title' => '['. gethostname() .'] Script finished', 'body' => 'Output:' . PHP_EOL . $stdin, ], ]; curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch);
Move source mapping after async support.
Error.stackTraceLimit = 100 // Async stacks. try { require('trace') } catch (_) {} // Source maps. try { require('source-map-support-2/register') } catch (_) {} // Removes node_modules and internal modules. try { var sep = require('path').sep var path = __dirname + sep + 'node_modules' + sep require('stack-chain').filter.attach(function (_, frames) { var filtered = frames.filter(function (frame) { var name = frame && frame.getFileName() return ( // has a filename name && // contains a separator (no internal modules) name.indexOf(sep) !== -1 && // does not start with the current path followed by node_modules. name.lastIndexOf(path, 0) !== 0 ) }) // depd (used amongst other by express requires at least 3 frames // in the stack. return filtered.length > 2 ? filtered : frames }) } catch (_) {}
Error.stackTraceLimit = 100 try { require('source-map-support-2/register') } catch (_) {} // Async stacks. try { require('trace') } catch (_) {} // Removes node_modules and internal modules. try { var sep = require('path').sep var path = __dirname + sep + 'node_modules' + sep require('stack-chain').filter.attach(function (_, frames) { var filtered = frames.filter(function (frame) { var name = frame && frame.getFileName() return ( // has a filename name && // contains a separator (no internal modules) name.indexOf(sep) !== -1 && // does not start with the current path followed by node_modules. name.lastIndexOf(path, 0) !== 0 ) }) // depd (used amongst other by express requires at least 3 frames // in the stack. return filtered.length > 2 ? filtered : frames }) } catch (_) {}
Update HomeController -- renamed Home -> HomeController
<?php /** * Class Home * * Please note: * Don't use the same name for class and method, as this might trigger an (unintended) __construct of the class. * This is really weird behaviour, but documented here: http://php.net/manual/en/language.oop5.decon.php * */ class HomeController extends Controller { function __construct(){ /** This is an example for loading models and entities for the controller to use. * The name in the array should be the same as the file name. **/ // Model // $models = array('modelexample'); // $this->_loadModel($models); // Entity // $entities = array('entityexample'); // $this->_loadEntity($entities); } /** * PAGE: index * This method handles what happens when you move to http://yourproject/home/index (which is the default page btw) */ public function index() { // load view require APP . 'view/home/index.php'; } }
<?php /** * Class Home * * Please note: * Don't use the same name for class and method, as this might trigger an (unintended) __construct of the class. * This is really weird behaviour, but documented here: http://php.net/manual/en/language.oop5.decon.php * */ class Home extends Controller { function __construct(){ /** This is an example for loading models and entities for the controller to use. * The name in the array should be the same as the file name. **/ // Model // $models = array('modelexample'); // $this->_loadModel($models); // Entity // $entities = array('entityexample'); // $this->_loadEntity($entities); } /** * PAGE: index * This method handles what happens when you move to http://yourproject/home/index (which is the default page btw) */ public function index() { // load view require APP . 'view/home/index.php'; } }
Allow script to take multiple paths, and adjust to standard __main__ idiom for cmdline scripts. * tools/dev/wc-format.py: (usage): remove. all paths are allowed. (print_format): move guts of format fetching and printing into this function. print 'not under version control' for such a path, rather than bailing with USAGE. expand sqlite stuff to use normal pydb idioms (eg. execute is not supposed to return anything) (__main__): invoke print_format for each path provided
#!/usr/bin/env python import os import sqlite3 import sys def print_format(wc_path): entries = os.path.join(wc_path, '.svn', 'entries') wc_db = os.path.join(wc_path, '.svn', 'wc.db') if os.path.exists(entries): formatno = int(open(entries).readline()) elif os.path.exists(wc_db): conn = sqlite3.connect(wc_db) curs = conn.cursor() curs.execute('pragma user_version;') formatno = curs.fetchone()[0] else: formatno = 'not under version control' # see subversion/libsvn_wc/wc.h for format values and information # 1.0.x -> 1.3.x: format 4 # 1.4.x: format 8 # 1.5.x: format 9 # 1.6.x: format 10 # 1.7.x: format XXX print '%s: %s' % (wc_path, formatno) if __name__ == '__main__': paths = sys.argv[1:] if not paths: paths = ['.'] for wc_path in paths: print_format(wc_path)
#!/usr/bin/env python import os import sqlite3 import sys # helper def usage(): sys.stderr.write("USAGE: %s [PATH]\n" + \ "\n" + \ "Prints to stdout the format of the working copy at PATH.\n") # parse argv wc = (sys.argv[1:] + ['.'])[0] # main() entries = os.path.join(wc, '.svn', 'entries') wc_db = os.path.join(wc, '.svn', 'wc.db') if os.path.exists(entries): formatno = int(open(entries).readline()) elif os.path.exists(wc_db): formatno = sqlite3.connect(wc_db).execute('pragma user_version;').fetchone()[0] else: usage() sys.exit(1) # 1.0.x -> 1.3.x: format 4 # 1.4.x: format 8 # 1.5.x: format 9 # 1.6.x: format 10 # 1.7.x: format XXX print("%s: %d" % (wc, formatno))
Edit Profile feature is removed in demo status.
@extends('panelViews::mainTemplate') @section('page-wrapper') @if (!empty($message)) <div class="alert-box success"> <h2>{{ $message }}</h2> </div> @endif @if ($demo_status == true) <h4>You are not allowed to edit the profile in demo version of panel.</h4> @else <div class="row"> <div class="col-xs-4" > {!! Form::model($admin, array( $admin->id)) !!} {!! Form::label('first_name', \Lang::get('panel::fields.FirstName')) !!} {!! Form::text('first_name', $admin->first_name, array('class' => 'form-control')) !!} <br /> {!! Form::label('last_name', \Lang::get('panel::fields.LastName')) !!} {!! Form::text('last_name', $admin->last_name, array('class' => 'form-control')) !!} <br /> <!-- email --> {!! Form::label('email', 'Email') !!} {!! Form::email('email', $admin->email, array('class' => 'form-control')) !!} <br /> {!! Form::submit(\Lang::get('panel::fields.updateProfile'), array('class' => 'btn btn-primary')) !!} {!! Form::close() !!} @endif </div> </div> @stop
@extends('panelViews::mainTemplate') @section('page-wrapper') @if (!empty($message)) <div class="alert-box success"> <h2>{{ $message }}</h2> </div> @endif <div class="row"> <div class="col-xs-4" > {!! Form::model($admin, array( $admin->id)) !!} {!! Form::label('first_name', \Lang::get('panel::fields.FirstName')) !!} {!! Form::text('first_name', $admin->first_name, array('class' => 'form-control')) !!} <br /> {!! Form::label('last_name', \Lang::get('panel::fields.LastName')) !!} {!! Form::text('last_name', $admin->last_name, array('class' => 'form-control')) !!} <br /> <!-- email --> {!! Form::label('email', 'Email') !!} {!! Form::email('email', $admin->email, array('class' => 'form-control')) !!} <br /> {!! Form::submit(\Lang::get('panel::fields.updateProfile'), array('class' => 'btn btn-primary')) !!} {!! Form::close() !!} </div> </div> @stop
Add +calendar to the home page
import React from 'react' import PersonGroup from '../../../../components/person-group' import RSVPIcon from '../../../../components/rsvp-icon' import {sortPeople} from '../../../../../shared/utils' export default Episode function Episode({episodeData}) { const { date, title, time, dateDisplay, guests = [], descriptionHTML, hangoutUrl, } = episodeData const sortedGuests = sortPeople(guests) return ( <div className="episode"> <h3> <a href={`/episodes/${date}`}>{title}</a> <br /> <small> <RSVPIcon hangoutUrl={hangoutUrl} /> {' ' + dateDisplay} at {time} </small> </h3> <PersonGroup people={sortedGuests} /> <div className="description"> <p dangerouslySetInnerHTML={descriptionHTML}></p> </div> </div> ) }
import React from 'react' import PersonGroup from '../../../../components/person-group' import {sortPeople} from '../../../../../shared/utils' export default Episode function Episode({episodeData}) { const { date, title, time, dateDisplay, guests = [], descriptionHTML, } = episodeData const sortedGuests = sortPeople(guests) return ( <div className="episode"> <h3> <a href={`/episodes/${date}`}>{title}</a> <br /> <small>{dateDisplay} at {time}</small> </h3> <PersonGroup people={sortedGuests} /> <div className="description"> <p dangerouslySetInnerHTML={descriptionHTML}></p> </div> </div> ) }
Fix bootstraping in console controller
<?php namespace haqqi\storm; use yii\base\Application; use yii\base\BootstrapInterface; use yii\base\Event; use yii\web\View; class Bootstrap implements BootstrapInterface { public function bootstrap($app) { $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) { /** * @var $event Event */ /* * Setup the config of asset bundles */ if(!$event->action->controller instanceof Controller) { $bundles =& $event->sender->assetManager->bundles; $bundles['yii\web\JqueryAsset']['js'] = ['jquery.min.js']; $bundles['yii\web\JqueryAsset']['jsOptions'] = ['position' => View::POS_HEAD]; $bundles['yii\bootstrap\BootstrapAsset']['css'] = ['css/bootstrap.min.css']; $bundles['yii\bootstrap\BootstrapPluginAsset']['js'] = ['js/bootstrap.min.js']; $bundles['yii\bootstrap\BootstrapPluginAsset']['jsOptions'] = ['position' => View::POS_HEAD]; $bundles['mimicreative\assets\MetisMenuAsset']['css'] = []; // \FB::log($event->sender->assetManager->bundles); } }); } }
<?php namespace haqqi\storm; use yii\base\Application; use yii\base\BootstrapInterface; use yii\base\Event; use yii\web\View; class Bootstrap implements BootstrapInterface { public function bootstrap($app) { $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) { /** * @var $event Event */ /* * Setup the config of asset bundles */ $bundles =& $event->sender->assetManager->bundles; $bundles['yii\web\JqueryAsset']['js'] = ['jquery.min.js']; $bundles['yii\web\JqueryAsset']['jsOptions'] = ['position' => View::POS_HEAD]; $bundles['yii\bootstrap\BootstrapAsset']['css'] = ['css/bootstrap.min.css']; $bundles['yii\bootstrap\BootstrapPluginAsset']['js'] = ['js/bootstrap.min.js']; $bundles['yii\bootstrap\BootstrapPluginAsset']['jsOptions'] = ['position' => \yii\web\View::POS_HEAD]; $bundles['mimicreative\assets\MetisMenuAsset']['css'] = []; \FB::log($event->sender->assetManager->bundles); }); } }
Correct the order of arguments to Object.assign()
const axios = require('axios') let params = { type: 'movie', tomatoes: 'true', plot: 'short', t: 'la la land', y: '2016', } params = Object.assign(params, {t: 'silence', y: '2016'}) // If year is not specified, will pick the 2008 movie. // params = Object.assign(params, {t: 'passengers', y: '2016'}) let url = 'http://www.omdbapi.com/' axios.get(url, {params}) .then(res => { let data = res.data if (data.Error !== undefined) { console.log('Status: %s, Error: %s', res.status, data.Error) return } let movie = data // console.log(movie) console.log(movie.Title) console.log(movie.Year) console.log('Directed by', movie.Director) console.log('Poster:', movie.Poster) console.log('Metascore:', movie.Metascore) console.log('IMDB rating:', movie.imdbRating) console.log('Tomato rating:', movie.tomatoRating) })
const axios = require('axios') let params = { type: 'movie', tomatoes: 'true', title: 'la la land', year: '2016' } // params = Object.assign({title: 'jackie', year: '2016'}, params) // If year is not specified, will pick the 2008 movie. // params = Object.assign({title: 'passengers', year: '2016'}, params) let url = 'http://omdbapi.com/' axios.get(url, {params}) .then(res => { let data = res.data if (data.Error !== undefined) { console.log('Status: %s, Error: %s', res.status, data.Error) return } let movie = data // console.log(movie) console.log(movie.Title) console.log(movie.Year) console.log('Directed by', movie.Director) console.log('Metascore:', movie.Metascore) console.log('IMDB rating:', movie.imdbRating) console.log('Tomato rating:', movie.tomatoRating) })
Remove the use of Exception
<?php namespace PhpDDD\Notification; /** * This class aims to stores all the validation errors you will find. */ class Notification { /** * @var Error[] */ private $errors = array(); /** * @param string $message */ public function addError($message) { $this->errors[] = new Error($message); } /** * @return bool */ public function hasErrors() { return !empty($this->errors); } /** * @return string[] */ public function errorMessages() { return $this->extractMessage(); } /** * @return string|null */ public function firstErrorMessage() { if (!$this->hasErrors()) { return; } $error = reset($this->errors); return $error->getMessage(); } /** * @return string[] */ private function extractMessage() { return array_map( function (Error $error) { return $error->getMessage(); }, $this->errors ); } }
<?php namespace PhpDDD\Notification; use Exception; class Notification { /** * @var Error[] */ private $errors = array(); /** * @param string $message * @param Exception $exception */ public function addError($message, Exception $exception = null) { $this->errors[] = new Error($message, $exception); } /** * @return bool */ public function hasErrors() { return !empty($this->errors); } /** * @return string[] */ public function errorMessages() { return $this->extractMessage(); } /** * @return string|null */ public function firstErrorMessage() { if (!$this->hasErrors()) { return; } $error = reset($this->errors); return $error->getMessage(); } /** * @return string[] */ private function extractMessage() { return array_map( function (Error $error) { return $error->getMessage(); }, $this->errors ); } }
Add a test for the bug occuring when no restaurants exist
from django.test import TestCase from randomizer.models import Restaurant class RandomizerTest(TestCase): """tests for the randomizer""" def test_homepage(self): """tests the homepage""" restaurant1 = Restaurant.objects.create(name='1') restaurant2 = Restaurant.objects.create(name='2') response = self.client.get('/') self.assertIn(response.context['restaurant'], [restaurant1, restaurant2]) def test_deleted_restaurant_bug(self): """tests a bug that occurs when you delete a restaurant from the DB""" restaurant1 = Restaurant.objects.create(name='A terrible place!') restaurant2 = Restaurant.objects.create(name='Foodie Heaven') restaurant1.delete() response = self.client.get('/') self.assertEqual(response.context['restaurant'], restaurant2) def test_no_restaurants_bug(self): """tests a bug occuring when no record exits in the restaurants DB""" response = self.client.get('/') self.assertTrue('restaurant' not in response.context)
from django.test import TestCase from randomizer.models import Restaurant class RandomizerTest(TestCase): """tests for the randomizer""" def test_homepage(self): """tests the homepage""" restaurant1 = Restaurant.objects.create(name='1') restaurant2 = Restaurant.objects.create(name='2') response = self.client.get('/') self.assertIn(response.context['restaurant'], [restaurant1, restaurant2]) def test_deleted_restaurant_bug(self): """tests a bug that occurs when you delete a restaurant from the DB""" restaurant1 = Restaurant.objects.create(name='A terrible place!') restaurant2 = Restaurant.objects.create(name='Foodie Heaven') restaurant1.delete() response = self.client.get('/') self.assertEqual(response.context['restaurant'], restaurant2)
Change tweet post message: post url instead
'use strict' const config = require(__dirname + '/config.js'); const Twit = require('twit'); const HC = require('node-hipchat'); let twitter = new Twit({ consumer_key: config['twitter_consumer_key'], consumer_secret: config['twitter_consumer_secret'], access_token: config['twitter_access_token'], access_token_secret: config['twitter_access_token_secret'], timeout_ms: 60*1000 // optional HTTP request timeout to apply to all requests. }); let hipchat = new HC(config['hipchat_key']); const params = { 'room': config['hipchat_room'], 'from': config['hipchat_bot'], 'color': 'gray', 'notify': 0 }; // Listen to TEA twitter accounts let stream = twitter.stream('statuses/filter', { track: config['twitter_keywords'] }); console.log('Listening to Twitter, tracking ' + config['twitter_keywords'].join(', ') + '.'); stream.on('tweet', function (tweet) { // posting to HipChat let content = params; const url = `http://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`; content.message = `<a href="${url}">${url}</a>`; hipchat.postMessage(params, null); });
'use strict' const config = require(__dirname + '/config.js'); const Twit = require('twit'); const HC = require('node-hipchat'); let twitter = new Twit({ consumer_key: config['twitter_consumer_key'], consumer_secret: config['twitter_consumer_secret'], access_token: config['twitter_access_token'], access_token_secret: config['twitter_access_token_secret'], timeout_ms: 60*1000 // optional HTTP request timeout to apply to all requests. }); let hipchat = new HC(config['hipchat_key']); const params = { 'room': config['hipchat_room'], 'from': config['hipchat_bot'], 'color': 'gray', 'notify': 0 }; // Listen to TEA twitter accounts let stream = twitter.stream('statuses/filter', { track: config['twitter_keywords'] }); console.log('Listening to Twitter, tracking ' + config['twitter_keywords'].join(', ') + '.'); stream.on('tweet', function (tweet) { // posting to HipChat let content = params; content.message = tweet.text; hipchat.postMessage(params, null); });
Fix compatibility with JBZoo/PHPUnit 1.2.x
<?php /** * JBZoo SimpleTypes * * This file is part of the JBZoo CCK package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @package SimpleTypes * @license MIT * @copyright Copyright (C) JBZoo.com, All rights reserved. * @link https://github.com/JBZoo/SimpleTypes * @author Denis Smetannikov <denis@jbzoo.com> */ namespace JBZoo\PHPUnit; /** * Class CodeStyleTest * @package JBZoo\SimpleTypes */ class CodeStyleTest extends Codestyle { protected $_packageName = 'SimpleTypes'; protected $_packageAuthor = 'Denis Smetannikov <denis@jbzoo.com>'; public function testCyrillic() { $GLOBALS['_jbzoo_fileExcludes'][] = 'outputTest.php'; $GLOBALS['_jbzoo_fileExcludes'][] = 'Money.php'; parent::testCyrillic(); } }
<?php /** * JBZoo SimpleTypes * * This file is part of the JBZoo CCK package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @package SimpleTypes * @license MIT * @copyright Copyright (C) JBZoo.com, All rights reserved. * @link https://github.com/JBZoo/SimpleTypes * @author Denis Smetannikov <denis@jbzoo.com> */ namespace JBZoo\PHPUnit; /** * Class CodeStyleTest * @package JBZoo\SimpleTypes */ class CodeStyleTest extends Codestyle { protected $_packageName = 'SimpleTypes'; protected $_packageAuthor = 'Denis Smetannikov <denis@jbzoo.com>'; public function testCyrillic() { $this->_excludeFiles[] = 'outputTest.php'; $this->_excludeFiles[] = 'Money.php'; parent::testCyrillic(); } }
Add reason why abernix/meteord:base is needed
const mailUser = 'postmaster@blah.mailgun.org'; const mailPass = 'b4da55'; const mailServer = 'smtp.mailgun.org'; const mailPort = '587'; module.exports = { servers: { one: { host: '1.2.3.4', username: 'root', // pem: '/home/user/.ssh/id_rsa', // mup doesn't support '~' alias for home directory // password: 'password', // or leave blank for authenticate from ssh-agent }, }, meteor: { name: 'spaicheck', // You should set path to the root path of the spaicheck app path: '../', servers: { one: {}, }, buildOptions: { serverOnly: true, }, env: { ROOT_URL: 'http://1.2.3.4/', MONGO_URL: 'mongodb://localhost/meteor', METEOR_ENV: 'production', MAIL_URL: `smtp://${mailUser}:${mailPass}@${mailServer}:${mailPort}`, }, // Use abernix's docker image for Meteor 1.4 compatiblity // https://github.com/kadirahq/meteor-up/issues/172#issuecomment-235569968 dockerImage: 'abernix/meteord:base', deployCheckWaitTime: 60, }, mongo: { oplog: true, port: 27017, servers: { one: {}, }, }, };
const mailUser = 'postmaster@blah.mailgun.org'; const mailPass = 'b4da55'; const mailServer = 'smtp.mailgun.org'; const mailPort = '587'; module.exports = { servers: { one: { host: '1.2.3.4', username: 'root', // pem: '/home/user/.ssh/id_rsa', // mup doesn't support '~' alias for home directory // password: 'password', // or leave blank for authenticate from ssh-agent }, }, meteor: { name: 'spaicheck', // You should set path to the root path of the spaicheck app path: '../', servers: { one: {}, }, buildOptions: { serverOnly: true, }, env: { ROOT_URL: 'http://1.2.3.4/', MONGO_URL: 'mongodb://localhost/meteor', METEOR_ENV: 'production', MAIL_URL: `smtp://${mailUser}:${mailPass}@${mailServer}:${mailPort}`, }, // Use abernix's docker image for Meteor 1.4 compatiblity dockerImage: 'abernix/meteord:base', deployCheckWaitTime: 60, }, mongo: { oplog: true, port: 27017, servers: { one: {}, }, }, };
Fix phone number formatting in emails
import i18naddress from django import template from django.utils.translation import pgettext register = template.Library() @register.inclusion_tag("formatted_address.html") def format_address(address, include_phone=True, inline=False, latin=False): address_data = address.as_data() address_data["name"] = ( pgettext("Address data", "%(first_name)s %(last_name)s") % address_data ) address_data["country_code"] = address_data["country"] address_data["street_address"] = pgettext( "Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data ) address_lines = i18naddress.format_address(address_data, latin).split("\n") if include_phone and address.phone: address_lines.append(str(address.phone)) return {"address_lines": address_lines, "inline": inline}
import i18naddress from django import template from django.utils.translation import pgettext register = template.Library() @register.inclusion_tag("formatted_address.html") def format_address(address, include_phone=True, inline=False, latin=False): address_data = address.as_data() address_data["name"] = ( pgettext("Address data", "%(first_name)s %(last_name)s") % address_data ) address_data["country_code"] = address_data["country"] address_data["street_address"] = pgettext( "Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data ) address_lines = i18naddress.format_address(address_data, latin).split("\n") if include_phone and address.phone: address_lines.append(address.phone) return {"address_lines": address_lines, "inline": inline}
fix: Check if boot obj exists
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt // for translation frappe._messages = {}; frappe._ = function(txt, replace, context = null) { if ($.isEmptyObject(frappe._messages) && frappe.boot) { $.extend(frappe._messages, frappe.boot.__messages); } if (!txt) return txt; if (typeof txt != "string") return txt; let translated_text = ''; let key = txt.replace(/\n/g, ""); if (context) { translated_text = frappe._messages[`${key}:${context}`]; } if (!translated_text) { translated_text = frappe._messages[key] || txt; } if (replace && typeof replace === "object") { translated_text = $.format(translated_text, replace); } return translated_text; }; window.__ = frappe._; frappe.get_languages = function() { if (!frappe.languages) { frappe.languages = []; $.each(frappe.boot.lang_dict, function(lang, value) { frappe.languages.push({ label: lang, value: value }); }); frappe.languages = frappe.languages.sort(function(a, b) { return a.value < b.value ? -1 : 1; }); } return frappe.languages; };
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt // for translation frappe._messages = {}; frappe._ = function(txt, replace, context = null) { if ($.isEmptyObject(frappe._messages)) { $.extend(frappe._messages, frappe.boot.__messages); } if (!txt) return txt; if (typeof txt != "string") return txt; let translated_text = ''; let key = txt.replace(/\n/g, ""); if (context) { translated_text = frappe._messages[`${key}:${context}`]; } if (!translated_text) { translated_text = frappe._messages[key] || txt; } if (replace && typeof replace === "object") { translated_text = $.format(translated_text, replace); } return translated_text; }; window.__ = frappe._; frappe.get_languages = function() { if (!frappe.languages) { frappe.languages = []; $.each(frappe.boot.lang_dict, function(lang, value) { frappe.languages.push({ label: lang, value: value }); }); frappe.languages = frappe.languages.sort(function(a, b) { return a.value < b.value ? -1 : 1; }); } return frappe.languages; };
:bug: Update the correct S3 path
<?php loadlib("s3"); ######################################################################## function wof_s3_put_file($rel, $path, $args=array(), $more=array()) { $bucket = array( 'id' => $GLOBALS['cfg']['aws']['s3_bucket'], 'key' => $GLOBALS['cfg']['aws']['access_key'], 'secret' => $GLOBALS['cfg']['aws']['access_secret'], ); if (! file_exists("{$rel}{$path}")) { return array( 'ok' => 0, 'error' => "'{$rel}{$path}' not found." ); } $data = file_get_contents("{$rel}{$path}"); $args = array_merge(array( 'id' => "data/$path", 'data' => $data ), $args); $rsp = s3_put($bucket, $args, $more); return $rsp; } # the end
<?php loadlib("s3"); ######################################################################## function wof_s3_put_file($rel, $path, $args=array(), $more=array()) { $bucket = array( 'id' => $GLOBALS['cfg']['aws']['s3_bucket'], 'key' => $GLOBALS['cfg']['aws']['access_key'], 'secret' => $GLOBALS['cfg']['aws']['access_secret'], ); if (! file_exists("{$rel}{$path}")) { return array( 'ok' => 0, 'error' => "'{$rel}{$path}' not found." ); } $data = file_get_contents("{$rel}{$path}"); $args = array_merge(array( 'id' => $path, 'data' => $data ), $args); $rsp = s3_put($bucket, $args, $more); return $rsp; } # the end
Convert institutions detail to pytest
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name)
Add basic security annotations to the CRUD service
package de.terrestris.shogun2.service; import java.util.List; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import de.terrestris.shogun2.model.PersistentObject; /** * This abstract service class provides basic CRUD functionality. * * @author Nils Bühner * @see AbstractDaoService * */ public abstract class AbstractCrudService<E extends PersistentObject> extends AbstractDaoService<E> { /** * * @param e * @return */ @Transactional(readOnly = false) @PreAuthorize("isAuthenticated()") public E saveOrUpdate(E e) { dao.saveOrUpdate(e); return e; } /** * * @param id * @return */ @PostAuthorize("hasPermission(returnObject, 'READ')") public E findById(Integer id) { return dao.findById(id); } /** * * @return */ @PostFilter("hasPermission(filterObject, 'READ')") public List<E> findAll() { return dao.findAll(); } /** * * @param e */ @PreAuthorize("hasPermission(#e, 'DELETE')") @Transactional(readOnly = false) public void delete(E e) { dao.delete(e); } }
package de.terrestris.shogun2.service; import java.util.List; import org.springframework.transaction.annotation.Transactional; import de.terrestris.shogun2.model.PersistentObject; /** * This abstract service class provides basic CRUD functionality. * * @author Nils Bühner * @see AbstractDaoService * */ public abstract class AbstractCrudService<E extends PersistentObject> extends AbstractDaoService<E> { /** * * @param e * @return */ @Transactional(readOnly = false) public E saveOrUpdate(E e) { dao.saveOrUpdate(e); return e; } /** * * @param id * @return */ public E findById(Integer id) { return dao.findById(id); } /** * * @return */ public List<E> findAll() { return dao.findAll(); } /** * * @param e */ @Transactional(readOnly = false) public void delete(E e) { dao.delete(e); } }
Enable mongoDB test cases to run on CI
package com.codingchili.core.storage; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import com.codingchili.core.testing.MapTestCases; /** * @author Robin Duda * <p> * Tests for the storage providers in core. Reuse these tests when new * storage subsystems are implemented using the StorageLoader. */ @RunWith(VertxUnitRunner.class) public class MongoDBMapIT extends MapTestCases { @Before public void setUp(TestContext test) { super.setUp(test, MongoDBMap.class); } @After public void tearDown(TestContext test) { super.tearDown(test); } }
package com.codingchili.core.storage; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import com.codingchili.core.testing.MapTestCases; /** * @author Robin Duda * <p> * Tests for the storage providers in core. Reuse these tests when new * storage subsystems are implemented using the StorageLoader. */ @Ignore("Requires running mongodb server.") @RunWith(VertxUnitRunner.class) public class MongoDBMapIT extends MapTestCases { @Before public void setUp(TestContext test) { super.setUp(test, MongoDBMap.class); } @After public void tearDown(TestContext test) { super.tearDown(test); } }
Fix deployment script to use env. port
require('shelljs/global'); const platform = { path: 'sashimi-platform', buildPath: 'public' }; const webapp = { path: 'sashimi-webapp', buildPath: 'dist' }; let statusBuild = -1; let statusStart = -1; printTitle('Build web application'); cd(`./${webapp.path}`); exec('yarn'); statusBuild = exec('yarn run build').code; throwErrorIfFailedToExec(statusBuild, 'build failed') printTitle('Copy webapp to server folder'); rm('-rf', `../${platform.path}/${platform.buildPath}/*`); cp('-R', `${webapp.buildPath}/*`, `../${platform.path}/${platform.buildPath}/`); cd(`..`); printTitle('Run web server') cd(`./${platform.path}`); exec('yarn') let envPort = process.env.PORT || '9010'; let envNode = process.env.NODE_ENV || 'production'; statusStart = exec(`set NODE_ENV=${envNode}&&set PORT=${envPort}&&yarn start`).code; throwErrorIfFailedToExec(statusStart, 'run failed') function throwErrorIfFailedToExec(statusCode, message) { if (statusCode !== 0) { printTitle(`Error: ${message}`); printMessage(`Script exit(${statusCode})`); exit(1); } } function printMessage(message) { let echoMsg = message || ''; echo(` [Deploy] > ${echoMsg}`); } function printTitle(message) { let echoMsg = message || '----------------'; echo(''); echo(` [Deploy] ${echoMsg}`); echo(''); }
require('shelljs/global'); const platform = { path: 'sashimi-platform', buildPath: 'public' }; const webapp = { path: 'sashimi-webapp', buildPath: 'dist' }; let statusBuild = -1; let statusStart = -1; printTitle('Build web application'); cd(`./${webapp.path}`); exec('yarn'); statusBuild = exec('yarn run build').code; throwErrorIfFailedToExec(statusBuild, 'build failed') printTitle('Copy webapp to server folder'); rm('-rf', `../${platform.path}/${platform.buildPath}/*`); cp('-R', `${webapp.buildPath}/*`, `../${platform.path}/${platform.buildPath}/`); cd(`..`); printTitle('Run web server') cd(`./${platform.path}`); exec('yarn') statusStart = exec('yarn start').code; throwErrorIfFailedToExec(statusStart, 'run failed') function throwErrorIfFailedToExec(statusCode, message) { if (statusCode !== 0) { printTitle(`Error: ${message}`); printMessage(`Script exit(${statusCode})`); exit(1); } } function printMessage(message) { let echoMsg = message || ''; echo(` [Deploy] > ${echoMsg}`); } function printTitle(message) { let echoMsg = message || '----------------'; echo(''); echo(` [Deploy] ${echoMsg}`); echo(''); }
Remove youtube.com and craiglist from showcase
package besticon // PopularSites we might use for examples and testing. var PopularSites []string func init() { PopularSites = []string{ "apple.com", "bbc.co.uk", "bing.com", "booking.com", "dropbox.com", "espn.go.com", "etsy.com", "facebook.com", "flickr.com", "github.com", "imgur.com", "instagram.com", "live.com", "mail.ru", "msn.com", "nytimes.com", "outbrain.com", "pinterest.com", "reddit.com", "stackoverflow.com", "t.co", "tumblr.com", "vimeo.com", "walmart.com", "wikipedia.org", "wordpress.com", "yahoo.com", "yelp.com", } }
package besticon // PopularSites we might use for examples and testing. var PopularSites []string func init() { PopularSites = []string{ "apple.com", "bbc.co.uk", "bing.com", "booking.com", "craigslist.org", "dropbox.com", "espn.go.com", "etsy.com", "facebook.com", "flickr.com", "github.com", "imgur.com", "instagram.com", "live.com", "mail.ru", "msn.com", "nytimes.com", "outbrain.com", "pinterest.com", "reddit.com", "stackoverflow.com", "t.co", "tumblr.com", "vimeo.com", "walmart.com", "wikipedia.org", "wordpress.com", "yahoo.com", "yelp.com", "youtube.com", } }