text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add extra endpoint for posts?
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.CommentView.as_view(), name='comments'), url(r'^author/posts/$', views.PostView.as_view(), name='authorpost'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(), name='author'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$', views.AuthorFriendsView.as_view(), name='friends') ]
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.CommentView.as_view(), name='comments'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(), name='author'), url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$', views.AuthorFriendsView.as_view(), name='friends') ]
Add namespace for test autoloader Useful to allow loading of classes in test package that are not test cases (mocks, dummy implementations, etc.).
<?php /* * Copyright (c) 2014-2016 Nicolas Braquart * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ $autoloader = require dirname(__DIR__) . '/vendor/autoload.php'; $autoloader->add('Ngames\\', __DIR__); return $autoloader;
<?php /* * Copyright (c) 2014-2016 Nicolas Braquart * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ $autoloader = require dirname(__DIR__) . '/vendor/autoload.php'; return $autoloader;
Stop using patterns() in the test URLs.
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/bar/$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/bar/baz/$', TemplateView.as_view( template_name='soapboxtest/test_context_processor.html')), url(r'^fail/$', TemplateView.as_view( template_name='soapboxtest/test_fail_syntax.html')), url(r'^bad-url-var/$', TemplateView.as_view( template_name='soapboxtest/test_bad_variable.html')), ]
from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( '', url(r'^$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/bar/$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/bar/baz/$', TemplateView.as_view( template_name='soapboxtest/test_context_processor.html')), url(r'^fail/$', TemplateView.as_view( template_name='soapboxtest/test_fail_syntax.html')), url(r'^bad-url-var/$', TemplateView.as_view( template_name='soapboxtest/test_bad_variable.html')), )
Add standard bootstrap styling to the contact form
@extends('app') @section('content') <h1>Contact</h1> @if(Session::has('message')) <div class="alert alert-info"> {{{ Session::get('message') }}} </div> @endif <ul> @foreach($errors->all() as $error) <li>{{{ $error }}}</li> @endforeach </ul> {!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!} <div class="form-group"> {!! Form::label('Name') !!} {!! Form::text('name', null, array('required', 'class'=>'form-control', 'placeholder'=>'eg. Slim Shady')) !!} </div> <div class="form-group"> {!! Form::label('E-mail') !!} {!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'eg. slim@shady.com')) !!} </div> <div class="form-group"> {!! Form::label('Message') !!} {!! Form::textarea('message', null, array('required', 'class'=>'form-control', 'placeholder'=>'What would you like to say?')) !!} </div> <div class="form-group"> {!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!} </div> {!! Form::close() !!} @endsection
<h1>Contact</h1> @if(Session::has('message')) <div class="alert alert-info"> {{{ Session::get('message') }}} </div> @endif <ul> @foreach($errors->all() as $error) <li>{{{ $error }}}</li> @endforeach </ul> {!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!} <div class="form-group"> {!! Form::label('Name') !!} {!! Form::text('name', null, array('required', 'class'=>'form-control', 'placeholder'=>'eg. Slim Shady')) !!} </div> <div class="form-group"> {!! Form::label('E-mail') !!} {!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'eg. slim@shady.com')) !!} </div> <div class="form-group"> {!! Form::label('Message') !!} {!! Form::textarea('message', null, array('required', 'class'=>'form-control', 'placeholder'=>'What would you like to say?')) !!} </div> <div class="form-group"> {!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!} </div> {!! Form::close() !!}
:sparkles: Apply refractor also in routes
<?php /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::group(['middleware' => 'auth:api', 'namespace' => 'Api'], function () { Route::any('', 'HomeController@index'); Route::get('user', 'UserController@index'); Route::get('user/orgs', 'UserController@orgs'); Route::get('org', 'HomeController@org'); Route::get('org/{org?}', 'OrgController@index'); Route::post('org/{org?}', 'OrgController@password'); Route::put('org/{org?}', 'OrgController@update'); Route::delete('org/{org?}', 'OrgController@delete'); Route::post('join/{org?}', 'OrgController@join'); Route::get('stats', 'HomeController@stats'); });
<?php /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::group(['middleware' => 'auth:api', 'namespace' => 'Api'], function () { Route::any('', 'HomeController@index'); Route::get('user', 'UserController@index'); Route::get('user/orgs', 'UserController@orgs'); Route::get('org', 'HomeController@org'); Route::get('org/{id?}', 'OrgController@index'); Route::post('org/{id?}', 'OrgController@password'); Route::put('org/{id?}', 'OrgController@update'); Route::delete('org/{id?}', 'OrgController@delete'); Route::post('join/{id?}', 'OrgController@join'); Route::get('stats', 'HomeController@stats'); });
Fix some issues exposed when making function statics sealed Reviewed By: SamChou19815 Differential Revision: D40736389 fbshipit-source-id: a3e1c3f5723081bf76e2dbdb637b4deb7a54e180
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format * @oncall relay */ 'use strict'; import type {UserConstantDependentResolver$key} from './__generated__/UserConstantDependentResolver.graphql'; const {graphql} = require('relay-runtime'); const {readFragment} = require('relay-runtime/store/ResolverFragments'); /** * @RelayResolver * @fieldName constant_dependent * @rootFragment UserConstantDependentResolver * @onType User */ function constant_dependent( rootKey: UserConstantDependentResolver$key, ): number { const user = readFragment( graphql` fragment UserConstantDependentResolver on User { constant } `, rootKey, ); constant_dependent._relayResolverTestCallCount = (constant_dependent._relayResolverTestCallCount ?? 0) + 1; return (user.constant ?? NaN) + 1; } constant_dependent._relayResolverTestCallCount = (undefined: number | void); module.exports = { constant_dependent, };
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format * @oncall relay */ 'use strict'; import type {UserConstantDependentResolver$key} from './__generated__/UserConstantDependentResolver.graphql'; const {graphql} = require('relay-runtime'); const {readFragment} = require('relay-runtime/store/ResolverFragments'); /** * @RelayResolver * @fieldName constant_dependent * @rootFragment UserConstantDependentResolver * @onType User */ function constant_dependent( rootKey: UserConstantDependentResolver$key, ): number { const user = readFragment( graphql` fragment UserConstantDependentResolver on User { constant } `, rootKey, ); // $FlowFixMe[prop-missing] constant_dependent._relayResolverTestCallCount = // $FlowFixMe[prop-missing] (constant_dependent._relayResolverTestCallCount ?? 0) + 1; return (user.constant ?? NaN) + 1; } module.exports = { constant_dependent, };
Remove debug flag from tests
import unittest from knights import compiler class Mock(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class TemplateTestCase(unittest.TestCase): def assertRendered(self, source, expected, context=None): try: tmpl = compiler.kompile(source) rendered = tmpl({} if context is None else context) self.assertEqual(rendered, expected) except Exception as e: if hasattr(e, 'message'): standardMsg = e.message elif hasattr(e, 'args') and len(e.args) > 0: standardMsg = e.args[0] else: standardMsg = '' msg = 'Failed rendering template %s:\n%s: %s' % ( source, e.__class__.__name__, standardMsg) self.fail(msg)
import unittest from knights import compiler class Mock(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class TemplateTestCase(unittest.TestCase): def assertRendered(self, source, expected, context=None, debug=False): try: tmpl = compiler.kompile(source, debug=debug) rendered = tmpl({} if context is None else context) self.assertEqual(rendered, expected) except Exception as e: if hasattr(e, 'message'): standardMsg = e.message elif hasattr(e, 'args') and len(e.args) > 0: standardMsg = e.args[0] else: standardMsg = '' msg = 'Failed rendering template %s:\n%s: %s' % ( source, e.__class__.__name__, standardMsg) self.fail(msg)
[core] Use ESM default export for dataset prompt
import debug from '../../debug' import promptForDatasetName from './datasetNamePrompt' export default async (context, options = {}) => { const {apiClient, prompt} = context const {message, allowCreation} = options const client = apiClient() const datasets = await client.datasets.list() const hasProduction = datasets.find(dataset => dataset.name === 'production') const datasetChoices = datasets.map(dataset => ({value: dataset.name})) const selected = await prompt.single({ message: message || 'Select dataset to use', type: 'list', choices: allowCreation ? [{value: 'new', name: 'Create new dataset'}, new prompt.Separator(), ...datasetChoices] : datasetChoices }) if (selected === 'new') { debug('User wants to create a new dataset, prompting for name') const newDatasetName = await promptForDatasetName(prompt, { message: 'Name your dataset:', default: hasProduction ? undefined : 'production' }) await client.datasets.create(newDatasetName) return newDatasetName } return selected }
import debug from '../../debug' import promptForDatasetName from './datasetNamePrompt' module.exports = async (context, options = {}) => { const {apiClient, prompt} = context const {message, allowCreation} = options const client = apiClient() const datasets = await client.datasets.list() const hasProduction = datasets.find(dataset => dataset.name === 'production') const datasetChoices = datasets.map(dataset => ({value: dataset.name})) const selected = await prompt.single({ message: message || 'Select dataset to use', type: 'list', choices: allowCreation ? [{value: 'new', name: 'Create new dataset'}, new prompt.Separator(), ...datasetChoices] : datasetChoices }) if (selected === 'new') { debug('User wants to create a new dataset, prompting for name') const newDatasetName = await promptForDatasetName(prompt, { message: 'Name your dataset:', default: hasProduction ? undefined : 'production' }) await client.datasets.create(newDatasetName) return newDatasetName } return selected }
Make TestingFrontend not blow up from info and move select to TestingSelector.
""" A frontend for use when testing. """ import contextlib from twisted.python import log from zope.interface import implements from cardboard.frontend import FrontendMixin, IFrontend def mock_selector(name): selections = [()] @contextlib.contextmanager def will_return(*selection): selections.append(selection) yield selections.pop() def select(self, *args, **kwargs): return selections[-1] select.__name__ = name select.will_return = will_return return select class TestingSelector(object): choice = mock_selector("choice") cards = mock_selector("cards") players = mock_selector("players") combined = mock_selector("combined") range = mock_selector("range") def __init__(self, frontend): super(TestingSelector, self).__init__() class TestingFrontend(FrontendMixin): implements(IFrontend) info = lambda _, __ : None select = TestingSelector def prompt(self, msg): log.msg(msg) def priority_granted(self): pass
""" A frontend for use when testing. """ import contextlib from twisted.python import log from zope.interface import implements from cardboard.frontend import FrontendMixin, IFrontend def mock_selector(name): selections = [()] @contextlib.contextmanager def will_return(*selection): selections.append(selection) yield selections.pop() def select(self, *args, **kwargs): return selections[-1] select.__name__ = name select.will_return = will_return return select class TestingFrontend(FrontendMixin): implements(IFrontend) select = mock_selector("select") select_cards = mock_selector("select_cards") select_players = mock_selector("select_players") select_combined = mock_selector("select_combined") select_range = mock_selector("select_range") def prompt(self, msg): log.msg(msg) def priority_granted(self): pass
Enable debug log on non production env
package logger import ( "io" "os" "github.com/oinume/lekcije/server/config" "github.com/uber-go/zap" ) var ( AccessLogger = zap.New(zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(os.Stdout)) AppLogger = zap.New(zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(os.Stderr)) ) func init() { if !config.IsProductionEnv() { AppLogger.SetLevel(zap.DebugLevel) } } func InitializeAccessLogger(writer io.Writer) { AccessLogger = zap.New( zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(zap.AddSync(writer)), ) } func InitializeAppLogger(writer io.Writer) { AppLogger = zap.New( zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(zap.AddSync(writer)), ) }
package logger import ( "io" "os" "github.com/uber-go/zap" ) var ( AccessLogger = zap.New(zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(os.Stdout)) AppLogger = zap.New(zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(os.Stderr)) ) func InitializeAccessLogger(writer io.Writer) { AccessLogger = zap.New( zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(zap.AddSync(writer)), ) } func InitializeAppLogger(writer io.Writer) { AppLogger = zap.New( zap.NewJSONEncoder(zap.RFC3339Formatter("ts")), zap.Output(zap.AddSync(writer)), ) }
Comment all view return a json of all comments
from flask import jsonify from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() comment.query.add_filter('post_id', '=', int(post_id)) return jsonify(comment.fetch()) @login_required def post(self, post_id): form = CommentForm() if form.validate_on_submit(): post = PostModel().get(post_id) post = PostModel(**post) comment = CommentModel(user=current_user.username, **form.data) comment.put() post.add_comment(comment.id) return "ALEYUYA" return "form.errors"
from flask_classy import FlaskView from flask_user import current_user, login_required from ..models import CommentModel, PostModel from ..forms import CommentForm class Comment(FlaskView): def get(self): pass def all(self, post_id): comment = CommentModel() comment.query.add_filter('post_id', '=', int(post_id)) print(comment.fetch()) return "comment.fetch()" @login_required def post(self, post_id): form = CommentForm() if form.validate_on_submit(): post = PostModel().get(post_id) post = PostModel(**post) comment = CommentModel(user=current_user.username, **form.data) comment.put() post.add_comment(comment.id) return "ALEYUYA" return "form.errors"
Fix the disconnect after 8 hours bug.
import os from flask import render_template, jsonify, request from app import app import pymysql as mdb @app.route('/') @app.route('/index') def index(): con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1') with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Auctions LIMIT 12") rows = cur.fetchall() for key in rows: key['thumb'] = key['image'].split(".")[2] + "-thumb.jpg" return render_template('destination2.html', auctions=rows) @app.route('/slides') def cities_page(): return render_template('slides_wide.html') @app.route("/slides_wide", methods=["GET"]) def slides_wide(): title="HammerPricer Slides" return render_template("slides_wide.html", title=title)
import os from flask import render_template, jsonify, request from app import app import pymysql as mdb con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1') @app.route('/') @app.route('/index') def index(): with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Auctions LIMIT 12") rows = cur.fetchall() for key in rows: key['thumb'] = key['image'].split(".")[2] + "-thumb.jpg" return render_template('destination2.html', auctions=rows) @app.route('/slides') def cities_page(): return render_template('slides_wide.html') @app.route("/slides_wide", methods=["GET"]) def slides_wide(): title="HammerPricer Slides" return render_template("slides_wide.html", title=title)
Add commented-out sealed and permits clause
package com.github.sormuras.bach.project; import java.util.List; import java.util.Map; /** A nominal space for modules. */ public /*sealed*/ interface Space /*permits MainSpace, TestSpace, PreviewSpace*/ { /** * Returns the list of module names in this space. * * @return the list of module names */ List<String> modules(); /** * Returns the list of module source paths. * * @return the list of module source paths */ List<String> moduleSourcePaths(); /** * Returns the possibly empty name of this space. * * @return an empty string for the main space, else a non-empty name * @see #title() */ String name(); /** * Returns the additional arguments to be passed on a per-tool basis. * * @return the additional arguments to be passed on a per-tool basis */ Map<String, List<String>> tweaks(); /** * Returns the title of this space. * * @return The string {@code "main"} for the main space, else the non-empty name * @see #name() */ default String title() { return name().isEmpty() ? "main" : name(); } /** @return {@code true} if at least one module name is present in this space */ default boolean isPresent() { return modules().size() >= 1; } }
package com.github.sormuras.bach.project; import java.util.List; import java.util.Map; /** A nominal space for modules. */ public interface Space { /** * Returns the list of module names in this space. * * @return the list of module names */ List<String> modules(); /** * Returns the list of module source paths. * * @return the list of module source paths */ List<String> moduleSourcePaths(); /** * Returns the possibly empty name of this space. * * @return an empty string for the main space, else a non-empty name * @see #title() */ String name(); /** * Returns the additional arguments to be passed on a per-tool basis. * * @return the additional arguments to be passed on a per-tool basis */ Map<String, List<String>> tweaks(); /** * Returns the title of this space. * * @return The string {@code "main"} for the main space, else the non-empty name * @see #name() */ default String title() { return name().isEmpty() ? "main" : name(); } /** @return {@code true} if at least one module name is present in this space */ default boolean isPresent() { return modules().size() >= 1; } }
Use Django's Atomic decorator logic We now keep Autocommit on it’s new default of True, as we only need the ability to rollback the contents of a queue job. By setting savepoint=False, the whole job will roll back if anything fails, rather than just up to the containing savepoint.
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): transaction.atomic(savepoint=False).__enter__() def process_result(self, job, result, duration): transaction.atomic(savepoint=False).__exit__(None, None, None) def process_exception(self, job, time_taken, *exc_info): transaction.atomic(savepoint=False).__exit__(*exc_info) # Legacy if not hasattr(connection, 'in_atomic_block'): class TransactionMiddleware(object): def process_job(self, job): transaction.enter_transaction_management() transaction.managed(True) def process_result(self, job, result, duration): if not transaction.is_managed(): return if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() def process_exception(self, job, time_taken, *exc_info): if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management()
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transaction.commit() def process_exception(self, job, time_taken, *exc_info): if not connection.in_atomic_block: transaction.rollback() # Legacy if not hasattr(connection, 'in_atomic_block'): class TransactionMiddleware(object): def process_job(self, job): transaction.enter_transaction_management() transaction.managed(True) def process_result(self, job, result, duration): if not transaction.is_managed(): return if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() def process_exception(self, job, time_taken, *exc_info): if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management()
Fix Python packaging to use correct git log for package time/version stamps.
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): gitinfo = subprocess.check_output( ['git', 'log', '--first-parent', '--max-count=1', '--format=format:%ct', '..']).strip() return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo))) def tags(self): if self.tag_build is None: self.tag_build = self.git_timestamp_tag() return egg_info.tags(self)
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): gitinfo = subprocess.check_output( ['git', 'log', '--first-parent', '--max-count=1', '--format=format:%ct', '.']).strip() return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo))) def tags(self): if self.tag_build is None: self.tag_build = self.git_timestamp_tag() return egg_info.tags(self)
Use a simple foor loop instead of .find to avoid using a polyfill
/** * Export javascript style and css style vendor prefixes. * Based on "transform" support test. */ import isBrowser from 'is-browser' let js = '' let css = '' // We should not do anything if required serverside. if (isBrowser) { const jsCssMap = { Webkit: '-webkit-', Moz: '-moz-', // IE did it wrong again ... ms: '-ms-', O: '-o-' } // Order matters. We need to check Webkit the last one because // other vendors use to add Webkit prefixes to some properties const prefixes = ['Moz', 'ms', 'O', 'Webkit'] const style = document.createElement('p').style const testProp = 'Transform' for (let i = 0; i < prefixes.length; i++) { const prefix = prefixes[i]; if ((prefix + testProp) in style) { js = prefix css = jsCssMap[prefix] break } } } /** * Vendor prefix string for the current browser. * * @type {{js: String, css: String}} * @api public */ export default {js, css}
/** * Export javascript style and css style vendor prefixes. * Based on "transform" support test. */ import isBrowser from 'is-browser' let js = '' let css = '' // We should not do anything if required serverside. if (isBrowser) { const jsCssMap = { Webkit: '-webkit-', Moz: '-moz-', // IE did it wrong again ... ms: '-ms-', O: '-o-' } const prefixes = ['Moz', 'Webkit', 'ms', 'O'] const style = document.createElement('p').style const testProp = 'Transform' const vendor = prefixes.find(prefix => (prefix + testProp) in style) if (vendor) { js = vendor css = jsCssMap[vendor] } } /** * Vendor prefix string for the current browser. * * @type {{js: String, css: String}} * @api public */ export default {js, css}
Upgrade to Flask 0.12.3 to fix CVE-2018-1000656
from setuptools import setup, find_packages with open('README.rst') as file: long_description = file.read() setup( name="frijoles", version="0.1.0", author="Pablo SEMINARIO", author_email="pablo@seminar.io", description="Simple notifications powered by jumping beans", long_description=long_description, license="GNU Affero General Public License v3", url="http://frijoles.antojitos.io/", download_url="https://github.com/Antojitos/frijoles/archive/0.1.0.tar.gz", keywords=["frijoles", "notifications", "api"], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], package_dir={'': 'src'}, packages=find_packages('src'), install_requires=[ 'Flask==0.12.3', 'Flask-PyMongo==0.4.0' ], )
from setuptools import setup, find_packages with open('README.rst') as file: long_description = file.read() setup( name="frijoles", version="0.1.0", author="Pablo SEMINARIO", author_email="pablo@seminar.io", description="Simple notifications powered by jumping beans", long_description=long_description, license="GNU Affero General Public License v3", url="http://frijoles.antojitos.io/", download_url="https://github.com/Antojitos/frijoles/archive/0.1.0.tar.gz", keywords=["frijoles", "notifications", "api"], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], package_dir={'': 'src'}, packages=find_packages('src'), install_requires=[ 'Flask==0.10.1', 'Flask-PyMongo==0.4.0' ], )
Remove TokuTransaction in migrate function
import logging import sys from modularodm import Q from framework.transactions.context import TokuTransaction from website.app import init_app from website.models import NodeLog from scripts import utils as script_utils logger = logging.getLogger(__name__) def get_targets(): return NodeLog.find(Q('action', 'eq', NodeLog.WIKI_DELETED)) def migrate(targets, dry_run=True): # iterate over targets for log in targets: node = log.node versions = node.wiki_pages_versions current = node.wiki_pages_current updated_versions = {} for wiki in versions: if wiki in current: updated_versions[wiki] = versions[wiki] node.wiki_pages_versions = updated_versions node.save() def main(): dry_run = False if '--dry' in sys.argv: dry_run = True if not dry_run: script_utils.add_file_logger(logger, __file__) init_app(set_backends=True, routes=False) with TokuTransaction(): migrate(targets=get_targets(), dry_run=dry_run) if dry_run: raise RuntimeError('Dry run, transaction rolled back.') if __name__ == "__main__": main()
import logging import sys from modularodm import Q from framework.transactions.context import TokuTransaction from website.app import init_app from website.models import NodeLog from scripts import utils as script_utils logger = logging.getLogger(__name__) def get_targets(): return NodeLog.find(Q('action', 'eq', NodeLog.WIKI_DELETED)) def migrate(targets, dry_run=True): # iterate over targets for log in targets: node = log.node versions = node.wiki_pages_versions current = node.wiki_pages_current updated_versions = {} for wiki in versions: if wiki in current: updated_versions[wiki] = versions[wiki] with TokuTransaction(): node.wiki_pages_versions = updated_versions node.save() if dry_run: raise RuntimeError('Dry run, transaction rolled back.') def main(): dry_run = False if '--dry' in sys.argv: dry_run = True if not dry_run: script_utils.add_file_logger(logger, __file__) init_app(set_backends=True, routes=False) with TokuTransaction(): migrate(targets=get_targets(), dry_run=dry_run) if __name__ == "__main__": main()
Add compatibility with Python 3.3.
from __future__ import print_function import pynmea2 from tempfile import TemporaryFile def test_stream(): data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n" sr = pynmea2.NMEAStreamReader() assert len(sr.next('')) == 0 assert len(sr.next(data)) == 1 assert len(sr.next(data)) == 1 sr = pynmea2.NMEAStreamReader() assert len(sr.next(data)) == 1 assert len(sr.next(data[:10])) == 0 assert len(sr.next(data[10:])) == 1 sr = pynmea2.NMEAStreamReader() assert sr.next() == [] t = TemporaryFile() print(data,end='',file=t) t.seek(0) sr = pynmea2.NMEAStreamReader(t) assert len(sr.next()) == 1 assert len(sr.next()) == 0 sr = pynmea2.NMEAStreamReader(data) assert sr.stream == None
import pynmea2 from tempfile import TemporaryFile def test_stream(): data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n" sr = pynmea2.NMEAStreamReader() assert len(sr.next('')) == 0 assert len(sr.next(data)) == 1 assert len(sr.next(data)) == 1 sr = pynmea2.NMEAStreamReader() assert len(sr.next(data)) == 1 assert len(sr.next(data[:10])) == 0 assert len(sr.next(data[10:])) == 1 sr = pynmea2.NMEAStreamReader() assert sr.next() == [] t = TemporaryFile() t.write(data) t.seek(0) sr = pynmea2.NMEAStreamReader(t) assert len(sr.next()) == 1 assert len(sr.next()) == 0 sr = pynmea2.NMEAStreamReader(data) assert sr.stream == None
Fix bogus Javadoc comment that referred to TraceWriter. Change-Id: I8c956fa7d32fa1ace147493e20c4a0f26d970dee
// 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 com.google.cloud.trace.sdk; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * Common reflection utilities. */ public class ReflectionUtils { private static final Logger logger = Logger.getLogger(ReflectionUtils.class.getName()); /** * Reflectively instantiates and initializes a class using a Properties file. */ public static Object createFromProperties(String className, Properties props) { Object obj = null; try { obj = Class.forName(className).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { logger.log(Level.WARNING, "Error creating " + className, e); } if (obj != null && obj instanceof CanInitFromProperties) { ((CanInitFromProperties) obj).initFromProperties(props); } return obj; } }
// 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 com.google.cloud.trace.sdk; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * Common reflection utilities. */ public class ReflectionUtils { private static final Logger logger = Logger.getLogger(ReflectionUtils.class.getName()); /** * Reflectively instantiates and initializes a TraceWriter using a Properties file. */ public static Object createFromProperties(String className, Properties props) { Object obj = null; try { obj = Class.forName(className).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { logger.log(Level.WARNING, "Error creating " + className, e); } if (obj != null && obj instanceof CanInitFromProperties) { ((CanInitFromProperties) obj).initFromProperties(props); } return obj; } }
Fix a few imports missing, and errors
import uuid from 'node-uuid'; import express from 'express'; import OrientDB from 'orientjs'; import {BinaryServer} from 'binaryjs'; import {setupInitQueue, setupNextSong, setupTrackListUpdate} from './lib/server-helper'; import {setupClients, setupStreamers} from './lib/server-setup'; import setupStreamHandler from './lib/setup-stream-handler'; import setupRoutes from './routes/routes-setup'; import config from './config'; const clients = setupClients(); const streamers = setupStreamers(); const app = express(); const server = OrientDB({ host: config.databaseHost, port: config.databasePort, username: config.username, password: config.password }); const db = server.use('music'); const populateQueue = setupInitQueue(db, streamers); const nextSongInQueue = setupNextSong(db, streamers); const updateTrackListing = setupTrackListUpdate(db); setupRoutes(app, db, clients, populateQueue); app.use(express.static('public')); const appServer = app.listen(config.webPort, function () { const host = appServer.address().address; const port = appServer.address().port; console.log('Example app listening at http://%s:%s', host, port); }); const streamerServer = BinaryServer({port: config.streamPort}); streamerServer.on('connection', function(streamer) { console.log('stream connected'); streamer.on('stream', setupStreamHandler(clients, streamers, updateTrackListing, nextSongInQueue)); });
import uuid from 'node-uuid'; import express from 'express'; import OrientDB from 'orientjs'; import {BinaryServer} from 'binaryjs'; import setupStreamServer from './lib/setup-stream-server'; import {setupInitQueue, setupNextSong} from './lib/server-helper'; import { setupClients, setupStreamers } from './lib/server-setup'; import setupRoutes from './routes/routes-setup'; import config from './config'; const clients = setupClients(); const streamers = setupStreamers(); const app = express(); const server = OrientDB({ host: config.databaseHost, port: config.databasePort, username: config.username, password: config.password }); const db = server.use('music'); const populateQueue = setupInitQueue(db, streamers); const nextSongInQueue = setupNextSong(db, streamers); const updateTrackListing = setupTrackListUpdate(db); setupRoutes(app, db, clients, populateQueue); app.use(express.static('public')); const appServer = app.listen(config.webPort, function () { const host = appServer.address().address; const port = appServer.address().port; console.log('Example app listening at http://%s:%s', host, port); }); const streamerServer = BinaryServer({port: config.streamPort}); streamerServer.on('connection', function(streamer) { console.log('stream connected'); streamer.on('stream', setupStreamHandler(clients, streamers, updateTrackListing, nextSongInQueue)); };);
Update position only when latest
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar; import org.traccar.helper.Log; import org.traccar.model.Position; public class DefaultDataHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { try { Context.getDataManager().addPosition(position); Position lastPosition = Context.getConnectionManager().getLastPosition(position.getDeviceId()); if (position.getFixTime().compareTo(lastPosition.getFixTime()) > 0) { Context.getDataManager().updateLatestPosition(position); } } catch (Exception error) { Log.warning(error); } return position; } }
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar; import org.traccar.helper.Log; import org.traccar.model.Position; public class DefaultDataHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { try { Context.getDataManager().addPosition(position); Context.getDataManager().updateLatestPosition(position); } catch (Exception error) { Log.warning(error); } return position; } }
Use the official Facebook SDK instead of our own. More information on the official Facebook PHP SDK can be found on (https://developers.facebook.com/docs/reference/php).
<?php /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ /** * This class defines the frontend, it is the core. Everything starts here. * We create all needed instances. * * @author Tijs Verkoyen <tijs@sumocoders.be> */ class Frontend { public function __construct() { $this->initializeFacebook(); new FrontendURL(); new FrontendTemplate(); new FrontendPage(); } /** * Initialize Facebook */ private function initializeFacebook() { // get settings $facebookApplicationId = FrontendModel::getModuleSetting('core', 'facebook_app_id'); $facebookApplicationSecret = FrontendModel::getModuleSetting('core', 'facebook_app_secret'); // needed data available? if($facebookApplicationId != '' && $facebookApplicationSecret != '') { $config = array( 'appId' => $facebookApplicationId, 'secret' => $facebookApplicationSecret, ); // create instance $facebook = new Facebook($config); // grab the signed request, if a user is logged in the access token will be set $facebook->getSignedRequest(); // store in reference Spoon::set('facebook', $facebook); // trigger event FrontendModel::triggerEvent('core', 'after_facebook_initialization'); } } }
<?php /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ /** * This class defines the frontend, it is the core. Everything starts here. * We create all needed instances. * * @author Tijs Verkoyen <tijs@sumocoders.be> */ class Frontend { public function __construct() { $this->initializeFacebook(); new FrontendURL(); new FrontendTemplate(); new FrontendPage(); } /** * Initialize Facebook */ private function initializeFacebook() { // get settings $facebookApplicationId = FrontendModel::getModuleSetting('core', 'facebook_app_id'); $facebookApplicationSecret = FrontendModel::getModuleSetting('core', 'facebook_app_secret'); // needed data available? if($facebookApplicationId != '' && $facebookApplicationSecret != '') { // require require_once 'external/facebook.php'; // create instance $facebook = new Facebook($facebookApplicationSecret, $facebookApplicationId); // get the cookie, this will set the access token. $facebook->getCookie(); // store in reference Spoon::set('facebook', $facebook); // trigger event FrontendModel::triggerEvent('core', 'after_facebook_initialization'); } } }
Fix a bug in the mega-drop that prevented it opening.
Teikei.module("User", function(User, App, Backbone, Marionette, $, _) { User.MegaDropView = Marionette.View.extend({ el: "#mega-drop", ui: { toggle: ".toggle-button", slider: ".slider", toggleText: ".toggle-button b" }, isOpen: false, events: { "click .toggle-button": "toggleDropdown", "click #start-for-consumers": "onStartForConsumers", "click #start-for-farmers": "onStartForFarmers" }, initialize: function(controller) { this.bindUIElements(); }, toggleDropdown: function(controller) { this.isOpen = !this.isOpen; this.ui.slider.animate({ height: "toggle", opacity: "toggle"}, 200 ); this.ui.toggle.toggleClass("open"); if (this.isOpen) { this.ui.toggleText.text("ausblenden"); } else { this.ui.toggleText.text("mehr erfahren"); } }, onStartForConsumers: function() { App.vent.trigger("show:consumer:infos"); }, onStartForFarmers: function() { App.vent.trigger("show:farmer:infos"); } }); });
Teikei.module("User", function(User, App, Backbone, Marionette, $, _) { User.MegaDropView = Marionette.View.extend({ el: "#mega-drop", ui: { toggle: ".toggle", slider: ".slider", toggleText: ".toggle b" }, isOpen: false, events: { "click .toggle": "toggleDropdown", "click #start-for-consumers": "onStartForConsumers", "click #start-for-farmers": "onStartForFarmers" }, initialize: function(controller) { this.bindUIElements(); }, toggleDropdown: function(controller) { this.isOpen = !this.isOpen; this.ui.slider.animate({ height: "toggle", opacity: "toggle"}, 200 ); this.ui.toggle.toggleClass("open"); if (this.isOpen) { this.ui.toggleText.text("ausblenden"); } else { this.ui.toggleText.text("mehr erfahren"); } }, onStartForConsumers: function() { App.vent.trigger("show:consumer:infos"); }, onStartForFarmers: function() { App.vent.trigger("show:farmer:infos"); } }); });
Determine response time for messages
# XML Parsing import xml.etree.ElementTree as ET # HTML output import dominate as dom from dominate.tags import * # Interact with user machine import datetime from sys import argv import os import time import webbrowser second = 1000 minute = 60000 hour = 3600000 class SMS: '''base SMS class to store a single message''' def __init__(self, date, party, message): self.date = date self.message = message self.party = party self.responseTime = 0 def transcribe(root, party1, party2): '''simplify the extracted SMS XML tree''' SMSlist = [] for sms in root.findall('sms'): newSMS = SMS(sms.attrib['date'], sms.attrib['type'], sms.attrib['body']) SMSlist.append(newSMS) # Traverse the list backwards to find out when the sms was responded to for prompt in reversed(SMSlist): if prompt.party == sms.party: break else: sms.responseTime = sms.date - prompt.date return SMSlist def main(party1, party2): '''main function that executes program function''' messages = transcribe(ET.parse('sms.xml').getroot(), party1, party2) if __name__ == '__main__': if (len(argv) < 3): raise Exception('Please enter your name and then your friend\'s name') main(argv[1], argv[2])
# XML Parsing import xml.etree.ElementTree as ET # HTML output import dominate as dom from dominate.tags import * # Interact with user machine import datetime from sys import argv import os import time import webbrowser second = 1000 minute = 60000 hour = 3600000 class SMS: '''base SMS class to store a single message''' def __init__(self, date, party, message): self.date = date self.message = message self.party = party self.responseTime = 0 def transcribe(root, party1, party2): '''simplify the extracted SMS XML tree''' SMSlist = [] for sms in root.findall('sms'): newSMS = SMS(sms.attrib['date'], sms.attrib['type'], sms.attrib['body']) SMSlist.append(newSMS) return SMSlist def main(party1, party2): '''main function that executes program function''' messages = transcribe(ET.parse('sms.xml').getroot(), party1, party2) if __name__ == '__main__': if (len(argv) < 3): raise Exception('Please enter your name and then your friend\'s name') main(argv[1], argv[2])
Add the local node_modules/.bin to the path This happens prior to executing tasks in the glueyfile
#!/usr/bin/env node 'use strict'; const Liftoff = require('liftoff'); const argv = require('minimist')(process.argv.slice(2)); const chalk = require('chalk'); const glueyCli = new Liftoff({ name: 'gluey', processTitle: 'gluey', moduleName: 'gluey', configName: 'glueyfile', }); glueyCli.launch({ cwd: argv.cwd, configPath: argv.myappfile, require: argv.require, completion: argv.completion }, invoke); function invoke(env) { if (!env.configPath) { console.log(chalk.red('No gulpfile found')); process.exit(1); } // add node_modules/.bin to the path. // this should be relative to the project root // if liftoff is working correctly. :) process.env.PATH = env.configBase + '/node_modules/.bin:' + process.env.PATH; require(env.configPath); const glueInst = require(env.modulePath); const actions = argv._; const actionList = actions.length ? actions : ['default']; const availableTasks = glueInst.taskList(); if (argv.l) { console.log(availableTasks.join('\n')); process.exit(0); } // Now lets make do stuff glueInst.start(actionList); } //
#!/usr/bin/env node 'use strict'; const Liftoff = require('liftoff'); const argv = require('minimist')(process.argv.slice(2)); const chalk = require('chalk'); const glueyCli = new Liftoff({ name: 'gluey', processTitle: 'gluey', moduleName: 'gluey', configName: 'glueyfile', }); glueyCli.launch({ cwd: argv.cwd, configPath: argv.myappfile, require: argv.require, completion: argv.completion }, invoke); function invoke(env) { if (!env.configPath) { console.log(chalk.red('No gulpfile found')); process.exit(1); } require(env.configPath); const glueInst = require(env.modulePath); const actions = argv._; const actionList = actions.length ? actions : ['default']; const availableTasks = glueInst.taskList(); if (argv.l) { console.log(availableTasks.join('\n')); process.exit(0); } // Now lets make do stuff glueInst.start(actionList); } //
Refactor home class method to bring photos (getPhotosByTag)
<?php namespace App\Controllers; use App\Framework\Mvc\Controller\BasicController; use App\Services\Instagram\InstagramService; class HomeController extends BasicController { /** * Request photos based on hashtag * * @param string $hashtag * @return array */ public function indexAction($hashtag) { // If there is no hashtag parameter, $tag is assigned as "Salvador" $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"]; $this->app->container->singleton('InstagramService', function () { return new InstagramService(); }); $instagram = $this->app->InstagramService; $result = $instagram->getPhotosByTag($hashtag); // Show hashtag name echo "<b>Hashtag:</b> #" . $hashtag . "<br />"; $result = json_decode($result, true); // Show 20 photos foreach ($result["data"] as $data) { echo "<img src=".$data["images"]["low_resolution"]["url"]." alt=".$data["caption"]["text"].">"; } } }
<?php namespace App\Controllers; use App\Framework\Mvc\Controller\BasicController; use App\Services\Instagram\InstagramService; class HomeController extends BasicController { /** * Request photos based on hashtag * * @param string $hashtag * @return array */ public function indexAction($hashtag) { // If there is no hashtag parameter, $tag is assigned as "Salvador" $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"]; $this->app->container->singleton('InstagramService', function () { return new InstagramService(); }); $instagram = $this->app->InstagramService; $result = $instagram->getPhotosBasedOnTag($hashtag); // Show hashtag name echo "<b>Hashtag:</b> #" . $hashtag . "<br />"; $result = json_decode($result, true); // Show 20 photos foreach ($result["data"] as $data) { echo "<img src=".$data["images"]["low_resolution"]["url"]." alt=".$data["caption"]["text"].">"; } } }
Rename common chunk "manifest" to "runtime"
const { optimize: { CommonsChunkPlugin }, } = require('webpack'); function isCss({ resource }) { return resource && resource.match(/\.(css|sss)$/); } function isVendor({ resource }) { return resource && resource.indexOf('node_modules') >= 0 && resource.match(/\.js$/); } module.exports = (config) => { config.plugins = [ ...config.plugins, new CommonsChunkPlugin({ name: 'vendor', minChunks: (module) => { if (isCss(module)) return false; return isVendor(module); }, }), new CommonsChunkPlugin({ name: 'runtime', minChunks: Infinity, }), ]; return config; };
const { optimize: { CommonsChunkPlugin }, } = require('webpack'); function isCss({ resource }) { return resource && resource.match(/\.(css|sss)$/); } function isVendor({ resource }) { return resource && resource.indexOf('node_modules') >= 0 && resource.match(/\.js$/); } module.exports = (config) => { config.plugins = [ ...config.plugins, new CommonsChunkPlugin({ name: 'vendor', minChunks: (module) => { if (isCss(module)) return false; return isVendor(module); }, }), new CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, }), ]; return config; };
Change the smoke test imports to a relative import for consistency.
# -*- coding: utf-8 -*- import unittest import sys sys.path.insert(0, '../') from mafia.game import Game from mafia.game import Player from testclient.testmessenger import TestMessenger class SmokeTest(unittest.TestCase): def setUp(self): self.messenger = TestMessenger() def test_smoke_test(self): game = Game('t,c,c,m', self.messenger) player_one = Player('one', 'one') player_two = Player('two', 'two') player_three = Player('three', 'three') player_four = Player('four', 'four') game.join(player_one) game.join(player_two) game.join(player_three) game.join(player_four) game.vote('one', 'three') game.vote('three', 'one') game.vote('two', 'three') game.vote('four', 'three') game.target('one', 'two') game.target('two', 'one') game.target('four', 'one') if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import unittest import sys sys.path.insert(0, '../mafia') from game import Game from game import Player from testclient.testmessenger import TestMessenger class SmokeTest(unittest.TestCase): def setUp(self): self.messenger = TestMessenger() def test_smoke_test(self): game = Game('t,c,c,m', self.messenger) player_one = Player('one', 'one') player_two = Player('two', 'two') player_three = Player('three', 'three') player_four = Player('four', 'four') game.join(player_one) game.join(player_two) game.join(player_three) game.join(player_four) game.vote('one', 'three') game.vote('three', 'one') game.vote('two', 'three') game.vote('four', 'three') game.target('one', 'two') game.target('two', 'one') game.target('four', 'one') if __name__ == '__main__': unittest.main()
Remove Http() baseURL and Router() onlyHash arguments
import 'todomvc-common/base.css'; import 'todomvc-app-css/index.css'; import './styles.css'; import 'file?name=[name].[ext]!./index.html'; import React from 'react'; import ReactDOM from 'react-dom'; import Controller from 'cerebral'; import Model from 'cerebral-model-baobab'; import Http from 'cerebral-module-http'; import {Container} from 'cerebral-view-react'; import App from './modules/App/components/App'; import AppModule from './modules/App'; import Refs from './modules/Refs'; import Devtools from 'cerebral-module-devtools'; import Router from 'cerebral-module-router'; const controller = Controller(Model({})); controller.addModules({ app: AppModule(), refs: Refs(), http: Http(), devtools: Devtools(), router: Router({ '/': 'app.footer.filterClicked', }, { mapper: {query: true}, }), }); // RENDER ReactDOM.render( <Container controller={controller}> <App /> </Container>, document.querySelector('#app'));
import 'todomvc-common/base.css'; import 'todomvc-app-css/index.css'; import './styles.css'; import 'file?name=[name].[ext]!./index.html'; import React from 'react'; import ReactDOM from 'react-dom'; import Controller from 'cerebral'; import Model from 'cerebral-model-baobab'; import Http from 'cerebral-module-http'; import {Container} from 'cerebral-view-react'; import App from './modules/App/components/App'; import AppModule from './modules/App'; import Refs from './modules/Refs'; import Devtools from 'cerebral-module-devtools'; import Router from 'cerebral-module-router'; const controller = Controller(Model({})); controller.addModules({ app: AppModule(), refs: Refs(), http: Http({ baseUrl: '/api', }), devtools: Devtools(), router: Router({ '/': 'app.footer.filterClicked', }, { onlyHash: true, mapper: {query: true}, }), }); // RENDER ReactDOM.render( <Container controller={controller}> <App /> </Container>, document.querySelector('#app'));
Put Image and Entity into __all__
# imports for Pyrge package __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World', 'Image', 'Entity'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
# imports for Pyrge package __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
Add fields to the public API.
""" Eliot: Logging as Storytelling Suppose we turn from outside estimates of a man, to wonder, with keener interest, what is the report of his own consciousness about his doings or capacity: with what hindrances he is carrying on his daily labors; what fading of hopes, or what deeper fixity of self-delusion the years are marking off within him; and with what spirit he wrestles against universal pressure, which will one day be too heavy for him, and bring his heart to its final pause. -- George Eliot, "Middlemarch" """ from ._version import __version__ # Expose the public API: from ._message import Message from ._action import startAction, startTask, Action from ._output import ILogger, Logger, MemoryLogger from ._validation import Field, fields, MessageType, ActionType from ._traceback import writeTraceback, writeFailure addDestination = Logger._destinations.add removeDestination = Logger._destinations.remove __all__ = ["Message", "writeTraceback", "writeFailure", "startAction", "startTask", "Action", "Field", "fields", "MessageType", "ActionType", "ILogger", "Logger", "MemoryLogger", "addDestination", "removeDestination", "__version__", ]
""" Eliot: Logging as Storytelling Suppose we turn from outside estimates of a man, to wonder, with keener interest, what is the report of his own consciousness about his doings or capacity: with what hindrances he is carrying on his daily labors; what fading of hopes, or what deeper fixity of self-delusion the years are marking off within him; and with what spirit he wrestles against universal pressure, which will one day be too heavy for him, and bring his heart to its final pause. -- George Eliot, "Middlemarch" """ from ._version import __version__ # Expose the public API: from ._message import Message from ._action import startAction, startTask, Action from ._output import ILogger, Logger, MemoryLogger from ._validation import Field, MessageType, ActionType from ._traceback import writeTraceback, writeFailure addDestination = Logger._destinations.add removeDestination = Logger._destinations.remove __all__ = ["Message", "writeTraceback", "writeFailure", "startAction", "startTask", "Action", "Field", "MessageType", "ActionType", "ILogger", "Logger", "MemoryLogger", "addDestination", "removeDestination", "__version__", ]
Use outcome for activity title in said activity
package br.odb.menu; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.widget.TextView; import br.odb.knights.R; public class ShowOutcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.outcome_layout); boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY; String text = getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad ); setTitle( text ); ((TextView) findViewById(R.id.tvOutcome)).setText( text ); ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MedievalSharp.ttf"); ( (TextView)findViewById(R.id.tvOutcome) ).setTypeface( font ); } }
package br.odb.menu; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.widget.TextView; import br.odb.knights.R; public class ShowOutcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.outcome_layout); boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY; ((TextView) findViewById(R.id.tvOutcome)).setText( getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad ) ); ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MedievalSharp.ttf"); ( (TextView)findViewById(R.id.tvOutcome) ).setTypeface( font ); } }
Add a test for asv machine --yes using defaults values
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import join import six from asv import machine def test_machine(tmpdir): tmpdir = six.text_type(tmpdir) m = machine.Machine.load( interactive=False, machine="orangutan", os="BeOS", arch="MIPS", cpu="10 MHz", ram="640k", _path=join(tmpdir, 'asv-machine.json')) m = machine.Machine.load( _path=join(tmpdir, 'asv-machine.json'), interactive=False) assert m.machine == 'orangutan' assert m.os == 'BeOS' assert m.arch == 'MIPS' assert m.cpu == '10 MHz' assert m.ram == '640k' def test_machine_defaults(tmpdir): tmpdir = six.text_type(tmpdir) m = machine.Machine.load( interactive=True, use_defaults=True, _path=join(tmpdir, 'asv-machine.json')) assert m.__dict__ == m.get_defaults()
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import join import six from asv import machine def test_machine(tmpdir): tmpdir = six.text_type(tmpdir) m = machine.Machine.load( interactive=False, machine="orangutan", os="BeOS", arch="MIPS", cpu="10 MHz", ram="640k", _path=join(tmpdir, 'asv-machine.json')) m = machine.Machine.load( _path=join(tmpdir, 'asv-machine.json'), interactive=False) assert m.machine == 'orangutan' assert m.os == 'BeOS' assert m.arch == 'MIPS' assert m.cpu == '10 MHz' assert m.ram == '640k'
Raise exception for unexpected status
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical
Revert "Revert "add line separator"" This reverts commit 41e1b3ffd43fd15eba9aff564e90abc91dc5f49d.
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; /** * Created by gis on 09.11.2016. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification() { app.getNavigationHelper().gotoHome(); app.getContactHelper().initContactModification(); ContactData contactData = new ContactData(); contactData .setFirstname("Lee") .setLastname("Chan") .setTitle("Mr.") .setAddress("Flat D, 6/F, Golden Industrial Center, Block 4, 182-190 Tai Lin Pai Road, Kwai Chung") .setHomePhone("(852) 2877-8933") .setEmail("hongkong@ihg.com"); app.getContactHelper().fillContactForm(contactData); app.getContactHelper().submitContactModification(); app.getNavigationHelper().gotoHomePage(); } }
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; /** * Created by gis on 09.11.2016. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification() { app.getNavigationHelper().gotoHome(); app.getContactHelper().initContactModification(); ContactData contactData = new ContactData(); contactData .setFirstname("Lee") .setLastname("Chan") .setTitle("Mr.") .setAddress("Flat D, 6/F, Golden Industrial Center, Block 4, 182-190 Tai Lin Pai Road, Kwai Chung") .setHomePhone("(852) 2877-8933") .setEmail("hongkong@ihg.com"); app.getContactHelper().fillContactForm(contactData); app.getContactHelper().submitContactModification(); app.getNavigationHelper().gotoHomePage(); } }
Add markers to time series
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h sleep_durations.append(sleep_total) nap_durations.append(nap_total) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration', mode='lines+markers') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration', mode='lines+markers') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h sleep_durations.append(sleep_total) nap_durations.append(nap_total) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
Add execute_anybodycon to toplevel package
# -*- coding: utf-8 -*- """AnyPyTools library.""" import sys import platform import logging from anypytools.abcutils import AnyPyProcess, execute_anybodycon from anypytools.macroutils import AnyMacro from anypytools import macro_commands logger = logging.getLogger('abt.anypytools') logger.addHandler(logging.NullHandler()) __all__ = [ 'datautils', 'h5py_wrapper', 'AnyPyProcess', 'AnyMacro', 'macro_commands', 'print_versions', 'execute_anybodycon', ] __version__ = '0.10.2' def print_versions(): """Print all the versions of software that AnyPyTools relies on.""" import numpy as np import scipy as sp print("-=" * 38) print("AnyPyTools version: %s" % __version__) print("NumPy version: %s" % np.__version__) print("SciPy version: %s" % sp.__version__) print("Python version: %s" % sys.version) (sysname, nodename, release, version, machine, processor) = \ platform.uname() print("Platform: %s-%s-%s (%s)" % (sysname, release, machine, version)) if sysname == "Linux": print("Linux dist: %s" % " ".join(platform.linux_distribution()[:-1])) if not processor: processor = "not recognized" print("Processor: %s" % processor) print("Byte-ordering: %s" % sys.byteorder) print("-=" * 38)
# -*- coding: utf-8 -*- """AnyPyTools library.""" import sys import platform import logging from anypytools.abcutils import AnyPyProcess from anypytools.macroutils import AnyMacro from anypytools import macro_commands logger = logging.getLogger('abt.anypytools') logger.addHandler(logging.NullHandler()) __all__ = [ 'datautils', 'h5py_wrapper', 'AnyPyProcess', 'AnyMacro', 'macro_commands', 'print_versions', ] __version__ = '0.10.2' def print_versions(): """Print all the versions of software that AnyPyTools relies on.""" import numpy as np import scipy as sp print("-=" * 38) print("AnyPyTools version: %s" % __version__) print("NumPy version: %s" % np.__version__) print("SciPy version: %s" % sp.__version__) print("Python version: %s" % sys.version) (sysname, nodename, release, version, machine, processor) = \ platform.uname() print("Platform: %s-%s-%s (%s)" % (sysname, release, machine, version)) if sysname == "Linux": print("Linux dist: %s" % " ".join(platform.linux_distribution()[:-1])) if not processor: processor = "not recognized" print("Processor: %s" % processor) print("Byte-ordering: %s" % sys.byteorder) print("-=" * 38)
Check for empty strings in required validator
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): '''Validate 'required' properties.''' if not validator.is_type(instance, 'object'): return for index, requirement in enumerate(required): if requirement not in instance or instance[requirement] == '': error = jsonschema.ValidationError( 'This field may not be blank.', path=[requirement] ) yield error # Construct validator as extension of Json Schema Draft 4. Validator = jsonschema.validators.extend( validator=jsonschema.validators.Draft4Validator, validators={ 'required': _required } ) def validate_json(value): """ Validate that a given value can be successfully parsed as JSON. """ try: json.loads(value) except json.JSONDecodeError as err: raise ValidationError('%s is not valid JSON: %s', params=(value, err.msg))
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): '''Validate 'required' properties.''' if not validator.is_type(instance, 'object'): return for index, requirement in enumerate(required): if requirement not in instance: error = jsonschema.ValidationError( 'This field may not be blank.', path=[requirement] ) yield error # Construct validator as extension of Json Schema Draft 4. Validator = jsonschema.validators.extend( validator=jsonschema.validators.Draft4Validator, validators={ 'required': _required } ) def validate_json(value): """ Validate that a given value can be successfully parsed as JSON. """ try: json.loads(value) except json.JSONDecodeError as err: raise ValidationError('%s is not valid JSON: %s', params=(value, err.msg))
[AC-9046] Remove unused import and fix linting issues
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = ["/people", "/people/"] mentor_url = "/directory" community_url = "/community" mentor_refinement_url = ("/directory/?refinementList%5B" "home_program_family%5D%5B0%5D=Israel") community_refinement_url = ("/community/?refinementList%5B" "program_family_names%5D%5B0%5D=Israel") SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') SiteRedirectPage.objects.filter( Q(new_url__in=people_url) | Q(new_url=mentor_url) ).update(new_url=community_url) SiteRedirectPage.objects.filter( new_url=mentor_refinement_url ).update(new_url=community_refinement_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = ["/people", "/people/"] mentor_url = "/directory" community_url = "/community" mentor_refinement_url = ("/directory/?refinementList%5B" "home_program_family%5D%5B0%5D=Israel") community_refinement_url = ("/community/?refinementList%5B" "program_family_names%5D%5B0%5D=Israel") SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') SiteRedirectPage.objects.filter( Q(new_url__in=people_url) | Q(new_url=mentor_url) ).update(new_url=community_url) SiteRedirectPage.objects.filter( new_url=mentor_refinement_url ).update(new_url=community_refinement_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
Add error event to router.
import Vue from 'vue' import Router from 'vue-router' import menuModule from '../store/modules/menu' Vue.use(Router) const router = new Router({ mode: 'history', routes: [ ...generateRoutesFromMenu(menuModule.state.items), { name: 'News', path: '/culture/news/:id', component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) } }, { name: 'Error', path: '/error/:status', component: (resolve) => { require(['@/components/layout/Error.vue'], resolve) } }, { path: '*', redirect: '/error/404' } ] }) function generateRoutesFromMenu (menu = [], routes = []) { for (let i = 0, l = menu.length; i < l; i++) { let item = menu[i] if (item.path) { routes.push(item) } } return routes } export default router
import Vue from 'vue' import Router from 'vue-router' import menuModule from '../store/modules/menu' Vue.use(Router) const router = new Router({ mode: 'history', routes: [ ...generateRoutesFromMenu(menuModule.state.items), { name: 'News', path: '/culture/news/:id', component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) } }, { name: 'Error', path: '/error/:status', component: (resolve) => { require(['@/components/layout/Error.vue'], resolve) } } ] }) function generateRoutesFromMenu (menu = [], routes = []) { for (let i = 0, l = menu.length; i < l; i++) { let item = menu[i] if (item.path) { routes.push(item) } } return routes } export default router
Update test: Adjust assertions to removal of cardinality checks
var vCard = require( '..' ) var fs = require( 'fs' ) var assert = require( 'assert' ) suite( 'vCard', function() { suite( 'Character Sets', function() { test( 'charset should not be part of value', function() { var data = fs.readFileSync( __dirname + '/data/xing.vcf' ) var card = new vCard( data ) assert.strictEqual( typeof card.fn, 'object' ) assert.strictEqual( card.fn.data.indexOf( 'CHARSET' ), -1 ) }) }) suite( 'Photo URL', function() { test( 'URL parameters should not become object properties', function() { var data = fs.readFileSync( __dirname + '/data/xing.vcf' ) var card = new vCard( data ) assert.equal( card.photo.txtsize, null ) }) }) })
var vCard = require( '..' ) var fs = require( 'fs' ) var assert = require( 'assert' ) suite( 'vCard', function() { suite( 'Character Sets', function() { test( 'charset should not be part of value', function() { var data = fs.readFileSync( __dirname + '/data/xing.vcf' ) var card = new vCard( data ) assert.strictEqual( card.fn.indexOf( 'CHARSET' ), -1 ) }) }) suite( 'Photo URL', function() { test( 'URL parameters should not become object properties', function() { var data = fs.readFileSync( __dirname + '/data/xing.vcf' ) var card = new vCard( data ) assert.equal( card.photo.txtsize, null ) }) }) })
Declare mock as a requiement.
#!/usr/bin/env python import sys from setuptools import setup, find_packages from exam import __version__ try: import multiprocessing except ImportError: pass install_requires = ['mock'] lint_requires = ['pep8', 'pyflakes'] tests_require = ['nose', 'unittest2', 'describe==1.0.0beta1'] dependency_links = [ 'https://github.com/jeffh/describe/tarball/dev#egg=describe' ] setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name='exam', version=__version__, author='Jeff Pollard', author_email='jeff.pollard@gmail.com', url='https://github.com/fluxx/exam', description='Helpers for better testing.', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, setup_requires=setup_requires, extras_require={ 'test': tests_require, 'all': install_requires + tests_require, 'docs': ['sphinx'] + tests_require, 'lint': lint_requires }, zip_safe=False, test_suite='nose.collector', )
#!/usr/bin/env python import sys from setuptools import setup, find_packages from exam import __version__ try: import multiprocessing except ImportError: pass install_requires = [] lint_requires = ['pep8', 'pyflakes'] tests_require = ['mock', 'nose', 'unittest2', 'describe==1.0.0beta1'] dependency_links = [ 'https://github.com/jeffh/describe/tarball/dev#egg=describe' ] setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name='exam', version=__version__, author='Jeff Pollard', author_email='jeff.pollard@gmail.com', url='https://github.com/fluxx/exam', description='Helpers for better testing.', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, setup_requires=setup_requires, extras_require={ 'test': tests_require, 'all': install_requires + tests_require, 'docs': ['sphinx'] + tests_require, 'lint': lint_requires }, zip_safe=False, test_suite='nose.collector', )
[core] Make all methods in CodeSytemRequests static
/* * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg * * 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 com.b2international.snowowl.terminologyregistry.core.request; /** * @since 4.7 */ public class CodeSystemRequests { private CodeSystemRequests() {} public static CodeSystemCreateRequestBuilder prepareNewCodeSystem() { return new CodeSystemCreateRequestBuilder(); } public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) { return new CodeSystemUpdateRequestBuilder(uniqueId); } public static CodeSystemGetRequestBuilder prepareGetCodeSystem() { return new CodeSystemGetRequestBuilder(); } public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() { return new CodeSystemSearchRequestBuilder(); } public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() { return new CodeSystemVersionSearchRequestBuilder(); } }
/* * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg * * 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 com.b2international.snowowl.terminologyregistry.core.request; /** * @since 4.7 */ public class CodeSystemRequests { private final String repositoryId; public CodeSystemRequests(final String repositoryId) { this.repositoryId = checkNotNull(repositoryId, "repositoryId"); } public CodeSystemCreateRequestBuilder prepareNewCodeSystem() { return new CodeSystemCreateRequestBuilder(repositoryId); } public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) { return new CodeSystemUpdateRequestBuilder(uniqueId); } public static CodeSystemGetRequestBuilder prepareGetCodeSystem() { return new CodeSystemGetRequestBuilder(); } public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() { return new CodeSystemSearchRequestBuilder(); } public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() { return new CodeSystemVersionSearchRequestBuilder(); } public String getRepositoryId() { return repositoryId; } }
Expand schedule to fill viewport
import React from 'react'; import { gql, graphql } from 'react-apollo'; import FullSchedule from '../components/FullSchedule'; function Schedule({ data }) { return ( <div> <div className="Container"> <h1 className="Page__heading">Schedule</h1> </div> <FullSchedule schedule={data} /> </div> ); } const ScheduleQuery = gql` query ScheduleQuery { allSlots { show { name slug brandColor } startTime endTime day } automationShow { name slug brandColor } } `; export default graphql(ScheduleQuery)(Schedule);
import React from 'react'; import { gql, graphql } from 'react-apollo'; import FullSchedule from '../components/FullSchedule'; function Schedule({ data }) { return ( <div className="Container"> <h1 className="Page__heading">Schedule</h1> <FullSchedule schedule={data} /> </div> ); } const ScheduleQuery = gql` query ScheduleQuery { allSlots { show { name slug brandColor } startTime endTime day } automationShow { name slug brandColor } } `; export default graphql(ScheduleQuery)(Schedule);
Allow init_command to be set by env
from .base import * DEBUG = True INSTALLED_APPS += ('wagtail.contrib.wagtailstyleguide',) DATABASES = { 'default': { 'ENGINE': MYSQL_ENGINE, 'NAME': os.environ.get('MYSQL_NAME'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PW', ''), 'HOST': os.environ.get('MYSQL_HOST', ''), # empty string == localhost 'PORT': os.environ.get('MYSQL_PORT', ''), # empty string == default 'OPTIONS': {'init_command': os.environ.get('STORAGE_ENGINE', 'SET storage_engine=MYISAM') }, }, } STATIC_ROOT = REPOSITORY_ROOT.child('collectstatic') ALLOW_ADMIN_URL = DEBUG or os.environ.get('ALLOW_ADMIN_URL', False)
from .base import * DEBUG = True INSTALLED_APPS += ('wagtail.contrib.wagtailstyleguide',) DATABASES = { 'default': { 'ENGINE': MYSQL_ENGINE, 'NAME': os.environ.get('MYSQL_NAME'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PW', ''), 'HOST': os.environ.get('MYSQL_HOST', ''), # empty string == localhost 'PORT': os.environ.get('MYSQL_PORT', ''), # empty string == default 'OPTIONS': {'init_command': 'SET storage_engine=MYISAM', }, }, } STATIC_ROOT = REPOSITORY_ROOT.child('collectstatic') ALLOW_ADMIN_URL = DEBUG or os.environ.get('ALLOW_ADMIN_URL', False)
Allow any DOMNode to be passed as parameters
<?php namespace phpgt\dom; /** * Contains methods that are particular to Node objects that can have a parent. * * This trait is used by the following classes: * - Element * - DocumentType * - CharacterData */ trait ChildNode { /** * Removes this ChildNode from the children list of its parent. * @return void */ public function remove() { $this->parentNode->removeChild($this); } /** * Inserts a Node into the children list of this ChildNode's parent, * just before this ChildNode. * @return void */ public function before(\DOMNode $node) { $this->parentNode->insertBefore($node, $this); } /** * Inserts a Node into the children list of this ChildNode's parent, * just after this ChildNode. * @return void */ public function after(\DOMNode $node) { $this->parentNode->insertBefore($node, $this->nextSibling); } /** * Replace this ChildNode in the children list of its parent. * * @param Node $replacement * @return void */ public function replaceWith(\DOMNode $replacement) { $this->parentNode->insertBefore($replacement, $this); $this->remove(); } }#
<?php namespace phpgt\dom; /** * Contains methods that are particular to Node objects that can have a parent. * * This trait is used by the following classes: * - Element * - DocumentType * - CharacterData */ trait ChildNode { /** * Removes this ChildNode from the children list of its parent. * @return void */ public function remove() { $this->parentNode->removeChild($this); } /** * Inserts a Node into the children list of this ChildNode's parent, * just before this ChildNode. * @return void */ public function before(Node $node) { $this->parentNode->insertBefore($node, $this); } /** * Inserts a Node into the children list of this ChildNode's parent, * just after this ChildNode. * @return void */ public function after(Node $node) { $this->parentNode->insertBefore($node, $this->nextSibling); } /** * Replace this ChildNode in the children list of its parent. * * @param Node $replacement * @return void */ public function replaceWith(Node $replacement) { $this->parentNode->insertBefore($replacement, $this); $this->remove(); } }#
Simplify computation of photo width
import { MAX_PHOTO_WIDTH_IN_PX } from '../constants'; export const getRestaurantId = restaurant => restaurant.place_id; export const getRestaurantLocation = restaurant => restaurant.geometry.location; const getRestaurantPhotoUrl = (restaurant) => { const { photos } = restaurant; if (!photos || !photos.length) return undefined; const options = { maxWidth: Math.min(window.innerWidth, MAX_PHOTO_WIDTH_IN_PX) }; return photos[0].getUrl(options); }; export const parseRestaurantData = restaurant => ({ id: getRestaurantId(restaurant), name: restaurant.name, address: restaurant.vicinity, rating: restaurant.rating, photoUrl: getRestaurantPhotoUrl(restaurant), phone: restaurant.formatted_phone_number, websiteUrl: restaurant.website, googlePageUrl: restaurant.url }); export const parseDistanceData = ({ distance, duration }) => ({ distanceInSpace: distance.text, distanceInTime: duration.text });
import { MAX_PHOTO_WIDTH_IN_PX } from '../constants'; export const getRestaurantId = restaurant => restaurant.place_id; export const getRestaurantLocation = restaurant => restaurant.geometry.location; const getRestaurantPhotoUrl = (restaurant) => { const { photos } = restaurant; if (!photos || !photos.length) return undefined; const options = { maxWidth: window.innerWidth < MAX_PHOTO_WIDTH_IN_PX ? window.innerWidth : MAX_PHOTO_WIDTH_IN_PX, } return photos[0].getUrl(options); }; export const parseRestaurantData = restaurant => ({ id: getRestaurantId(restaurant), name: restaurant.name, address: restaurant.vicinity, rating: restaurant.rating, photoUrl: getRestaurantPhotoUrl(restaurant), phone: restaurant.formatted_phone_number, websiteUrl: restaurant.website, googlePageUrl: restaurant.url }); export const parseDistanceData = ({ distance, duration }) => ({ distanceInSpace: distance.text, distanceInTime: duration.text });
Revert "Revert "retrieve currently playing info (commented out)"" This reverts commit e14ee15116ee2137d528d298ca38e26e4f02f09f.
from flask import Flask, render_template from settings import * import jsonrpclib app = Flask(__name__) @app.route('/') def index(): xbmc = jsonrpclib.Server('http://%s:%s@%s:%s/jsonrpc' % (SERVER['username'], SERVER['password'], SERVER['hostname'], SERVER['port'])) episodes = xbmc.VideoLibrary.GetRecentlyAddedEpisodes() recently_added_episodes = [] # tidy up filenames of recently added episodes for episode in episodes['episodes'][:NUM_RECENT_EPISODES]: filename = episode['file'].split('/').pop().replace('.', ' ') recently_added_episodes.append(filename) # currently playing #currently_playing = xbmc.VideoPlaylist.GetItems(id=1) #time = xbmc.VideoPlayer.GetTime() return render_template('index.html', recently_added_episodes = recently_added_episodes, applications = APPLICATIONS, server = SERVER ) if __name__ == '__main__': app.run(debug=True)
from flask import Flask, render_template from settings import * import jsonrpclib app = Flask(__name__) @app.route('/') def index(): xbmc = jsonrpclib.Server('http://%s:%s@%s:%s/jsonrpc' % (SERVER['username'], SERVER['password'], SERVER['hostname'], SERVER['port'])) episodes = xbmc.VideoLibrary.GetRecentlyAddedEpisodes() recently_added_episodes = [] # tidy up filenames of recently added episodes for episode in episodes['episodes'][:NUM_RECENT_EPISODES]: filename = episode['file'].split('/').pop().replace('.', ' ') recently_added_episodes.append(filename) return render_template('index.html', recently_added_episodes = recently_added_episodes, applications = APPLICATIONS, server = SERVER ) if __name__ == '__main__': app.run(debug=True)
CLEAN simplify useless dep and methods
class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, cycle=4): super(bar, self).__init__() self.cycle = cycle self.notes = dict() def add_note(self, note, start_time): """ note : note : note instance start_time : int : start time inside the measure """ self.notes[note] = start_time class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() def add_bar(bar): self.bars.append(bar) class stave(sheet): """ stave: sheet that is displayed in music theory representation""" def __init__(self): super(stave, self).__init__() class tab(sheet): """ tab: sheet that is displayed with tab representation""" def __init__(self): super(tab, self).__init__() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, cycle=4): super(bar, self).__init__() self.cycle = cycle self.notes = dict() def add_note(self, note, start_time): """ note : note : note instance start_time : int : start time inside the measure """ self.notes[note] = start_time class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
Add website code to body class
<?php /** * Copyright © 2017 Sam Granger. All rights reserved. * * @author Sam Granger <sam.granger@gmail.com> */ namespace SamGranger\StoreCodeBodyClass\Plugin; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer; use Magento\Framework\View\Page\Config; use Magento\Store\Model\StoreManagerInterface; class StoreCodeBodyClassPlugin implements ObserverInterface { protected $config; protected $storeManager; public function __construct( Config $config, StoreManagerInterface $storeManager ){ $this->config = $config; $this->storeManager = $storeManager; } public function execute(Observer $observer){ $store = $this->storeManager->getStore(); $storeCode = $store->getCode(); $websiteCode = $store->getWebsite()->getCode(); $this->config->addBodyClass($storeCode); $this->config->addBodyClass($websiteCode); } }
<?php /** * Copyright © 2017 Sam Granger. All rights reserved. * * @author Sam Granger <sam.granger@gmail.com> */ namespace SamGranger\StoreCodeBodyClass\Plugin; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer; use Magento\Framework\View\Page\Config; use Magento\Store\Model\StoreManagerInterface; class StoreCodeBodyClassPlugin implements ObserverInterface { protected $config; protected $storeManager; public function __construct( Config $config, StoreManagerInterface $storeManager ){ $this->config = $config; $this->storeManager = $storeManager; } public function execute(Observer $observer){ $storeCode = $this->storeManager->getStore()->getCode(); $this->config->addBodyClass($storeCode); } }
Remove --ffast-math for all builds Due to a bug in anaconda's libm support for linux, fast-math is unusable. And I don't want to try to hack a way to decide if it's usable on things other than linux, because it's just one more thing to break.
#!/usr/bin/env python def configuration(parent_package='',top_path=None): import numpy import os from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion',parent_package,top_path) config.add_extension('numpy_quaternion', ['quaternion.c','numpy_quaternion.c'], extra_compile_args=compile_args,) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration)
#!/usr/bin/env python def configuration(parent_package='',top_path=None): import numpy import os from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info if(os.environ.get('THIS_IS_TRAVIS') is not None): print("This appears to be Travis!") compile_args = ['-O3'] else: compile_args = ['-ffast-math', '-O3'] config = Configuration('quaternion',parent_package,top_path) config.add_extension('numpy_quaternion', ['quaternion.c','numpy_quaternion.c'], extra_compile_args=compile_args,) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration)
Remove the custom URL when initialize socket.io
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { RouterProvider } from 'react-router5'; import App from './containers/App'; import io from 'socket.io-client'; // Router import createRouter from './router'; // Redux import configureStore from './stores'; // Styles import './index.css'; // Basic simple peer config // let config = { // iceServers: [ // { url: 'stun:stun.l.google.com:19302' } // ] // }; const socket = io(); // Redux and router const router = createRouter(); const store = configureStore(router, { // Initial State socket: { socket } }); router.start((err, state) => { ReactDOM.render( <Provider store={ store }> <RouterProvider router={ router }> <App /> </RouterProvider> </Provider>, document.getElementById('root') ); });
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { RouterProvider } from 'react-router5'; import App from './containers/App'; import io from 'socket.io-client'; // Router import createRouter from './router'; // Redux import configureStore from './stores'; // Styles import './index.css'; // Basic simple peer config // let config = { // iceServers: [ // { url: 'stun:stun.l.google.com:19302' } // ] // }; const socket = io('http://api.discuzzion.docker'); // Redux and router const router = createRouter(); const store = configureStore(router, { // Initial State socket: { socket } }); router.start((err, state) => { ReactDOM.render( <Provider store={ store }> <RouterProvider router={ router }> <App /> </RouterProvider> </Provider>, document.getElementById('root') ); });
Use webpack to minify built files
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: './src/jtml.js', devtool: 'source-map', output: { path: './lib', filename: 'jtml.js', library: 'jtml', libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { loader: 'babel', test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], plugins: ['babel-plugin-add-module-exports'] } } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, output: { comments: false, }, }), ] };
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: './src/jtml.js', devtool: 'source-map', output: { path: './lib', filename: 'jtml.js', library: 'jtml', libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { loader: 'babel', test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], plugins: ['babel-plugin-add-module-exports'] } } ] }, plugins: [ // new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false, // }, // output: { // comments: false, // }, // }), ] };
Fix sourcemaps for SASS 3.4.x
// * Gulpfile // * --------------------- // * This file contains the gulp build-process. // * --------------------- // * Core // * --------------------- // * Require gulp modules var gulp = require("gulp"), rename = require("gulp-rename"), prefix = require("gulp-autoprefixer"), sass = require("gulp-ruby-sass"); // * scss // * 1. handle errors // * 2. sass // * 3. prefix // * --> write out // * 4. minify // * --> write out // * --------------------- gulp.task("sass", function () { gulp.src("scss/fundament-grid.scss") .pipe(sass({noCache:true, 'sourcemap=none': true})) .pipe(prefix({ browsers: ["last 1 version", "Explorer >= 10", "Android >= 4.4"] })) .pipe(rename("fundament-grid.css")) .pipe(gulp.dest("./dist")); }); // * Tasks // * --------------------- // * Default task gulp.task("default", ["sass"]);
// * Gulpfile // * --------------------- // * This file contains the gulp build-process. // * --------------------- // * Core // * --------------------- // * Require gulp modules var gulp = require("gulp"), rename = require("gulp-rename"), prefix = require("gulp-autoprefixer"), sass = require("gulp-ruby-sass"); // * scss // * 1. handle errors // * 2. sass // * 3. prefix // * --> write out // * 4. minify // * --> write out // * --------------------- gulp.task("sass", function () { gulp.src("scss/fundament-grid.scss") .pipe(sass()) .pipe(prefix({ browsers: ["last 1 version", "Explorer >= 4.4"] })) .pipe(rename("fundament-grid.css")) .pipe(gulp.dest("./dist")); }); // * Tasks // * --------------------- // * Default task gulp.task("default", ["sass"]);
Update configurator mock in deselector spec
"use strict"; describe("deselector", function() { var element; var state; var configurator = { provideResource: function() {}, configurationFor: function() {} }; beforeEach(module("arethusa.core", function($provide) { $provide.value('configurator', configurator); })); beforeEach(inject(function($compile, $rootScope, _state_) { element = angular.element("<span deselector/>"); $compile(element)($rootScope); state = _state_; })); describe("on click", function() { it('deselects all tokens', function() { state.selectToken('01', 'ctrl-click'); state.selectToken('02', 'ctrl-click'); expect(state.hasSelections()).toBeTruthy(); element.triggerHandler('click'); expect(state.hasSelections()).toBeFalsy(); }); }); });
"use strict"; describe("deselector", function() { var element; var state; var configurator = { provideResource: function() {} }; beforeEach(module("arethusa.core", function($provide) { $provide.value('configurator', configurator); })); beforeEach(inject(function($compile, $rootScope, _state_) { element = angular.element("<span deselector/>"); $compile(element)($rootScope); state = _state_; })); describe("on click", function() { it('deselects all tokens', function() { state.selectToken('01', 'ctrl-click'); state.selectToken('02', 'ctrl-click'); expect(state.hasSelections()).toBeTruthy(); element.triggerHandler('click'); expect(state.hasSelections()).toBeFalsy(); }); }); });
Fix potential null pointer during product translation
const utils = require('../lib/utils') const insecurity = require('../lib/insecurity') const models = require('../models/index') const challenges = require('../data/datacache').challenges module.exports = function retrieveBasket () { return (req, res, next) => { const id = req.params.id models.Basket.findOne({ where: { id }, include: [{ model: models.Product, paranoid: false }] }) .then(basket => { /* jshint eqeqeq:false */ if (utils.notSolved(challenges.basketAccessChallenge)) { const user = insecurity.authenticatedUsers.from(req) if (user && id && id !== 'undefined' && id !== 'null' && user.bid != id) { // eslint-disable-line eqeqeq utils.solve(challenges.basketAccessChallenge) } } if (basket && basket.Products && basket.Products.length > 0) { for (let i = 0; i < basket.Products.length; i++) { basket.Products[i].name = req.__(basket.Products[i].name) } } res.json(utils.queryResultToJson(basket)) }).catch(error => { next(error) }) } }
const utils = require('../lib/utils') const insecurity = require('../lib/insecurity') const models = require('../models/index') const challenges = require('../data/datacache').challenges module.exports = function retrieveBasket () { return (req, res, next) => { const id = req.params.id models.Basket.findOne({ where: { id }, include: [{ model: models.Product, paranoid: false }] }) .then(basket => { /* jshint eqeqeq:false */ if (utils.notSolved(challenges.basketAccessChallenge)) { const user = insecurity.authenticatedUsers.from(req) if (user && id && id !== 'undefined' && id !== 'null' && user.bid != id) { // eslint-disable-line eqeqeq utils.solve(challenges.basketAccessChallenge) } } if (basket.Products && basket.Products.length > 0) { for (let i = 0; i < basket.Products.length; i++) { basket.Products[i].name = req.__(basket.Products[i].name) } } res.json(utils.queryResultToJson(basket)) }).catch(error => { next(error) }) } }
Fix php warning on LinearRing creation with invalid params
<?php namespace GeoJson\Geometry; /** * Polygon geometry object. * * Coordinates consist of an array of LinearRing coordinates. * * @see http://www.geojson.org/geojson-spec.html#polygon * @since 1.0 */ class Polygon extends Geometry { protected $type = 'Polygon'; /** * Constructor. * * @param float[][][]|LinearRing[] $linearRings * @param CoordinateResolutionSystem|BoundingBox $arg,... */ public function __construct(array $linearRings) { foreach ($linearRings as $linearRing) { if ( ! $linearRing instanceof LinearRing) { $linearRing = new LinearRing($linearRing); } $this->coordinates[] = $linearRing->getCoordinates(); } if (func_num_args() > 1) { $this->setOptionalConstructorArgs(array_slice(func_get_args(), 1)); } } }
<?php namespace GeoJson\Geometry; /** * Polygon geometry object. * * Coordinates consist of an array of LinearRing coordinates. * * @see http://www.geojson.org/geojson-spec.html#polygon * @since 1.0 */ class Polygon extends Geometry { protected $type = 'Polygon'; /** * Constructor. * * @param float[][][]|LinearRing[] $linearRings * @param CoordinateResolutionSystem|BoundingBox $arg,... */ public function __construct(array $linearRings) { $this->coordinates = array_map( function($linearRing) { if ( ! $linearRing instanceof LinearRing) { $linearRing = new LinearRing($linearRing); } return $linearRing->getCoordinates(); }, $linearRings ); if (func_num_args() > 1) { $this->setOptionalConstructorArgs(array_slice(func_get_args(), 1)); } } }
Add defaultHead to validated content-loader options
// @flow import memoize from "lru-memoize" const fieldTypes = { context: "string", renderer: "function", feedsOptions: "object", feeds: "object", description: "object", defaultHead: "object", } const validator = function( userConfig: Object = {} ): void { const errors = [] Object.keys(userConfig).forEach((key) => { if (!fieldTypes[key]) { errors.push( `Unknow option '${ key }'.` ) } else if (fieldTypes[key] !== typeof userConfig[key]) { errors.push( `Wrong type for '${ key }': expected '${ fieldTypes[key] }', ` + `got '${ typeof userConfig[key] }'.` ) } }) if (errors.length > 0) { throw new Error( `Your 'content-loader' config is invalid. Please fix the errors: \n- ` + errors.join("\n- ") + "\n\n" + "See 'Configuration' section in documentation." ) } } export default memoize(10)(validator)
// @flow import memoize from "lru-memoize" const fieldTypes = { context: "string", renderer: "function", feedsOptions: "object", feeds: "object", description: "object", } const validator = function( userConfig: Object = {} ): void { const errors = [] Object.keys(userConfig).forEach((key) => { if (!fieldTypes[key]) { errors.push( `Unknow option '${ key }'.` ) } else if (fieldTypes[key] !== typeof userConfig[key]) { errors.push( `Wrong type for '${ key }': expected '${ fieldTypes[key] }', ` + `got '${ typeof userConfig[key] }'.` ) } }) if (errors.length > 0) { throw new Error( `Your 'content-loader' config is invalid. Please fix the errors: \n- ` + errors.join("\n- ") + "\n\n" + "See 'Configuration' section in documentation." ) } } export default memoize(10)(validator)
Fix TM2 test to match renamed symbol
package peer import ( "fmt" "io/ioutil" "testing" ) func TestCrStates(t *testing.T) { t.Log("Running Peer Tests") text, err := ioutil.ReadFile("crstates.json") if err != nil { t.Log(err) } crStates, err := CrstatesUnMarshall(text) if err != nil { t.Log(err) } fmt.Println(len(crStates.Caches), "caches found") for cacheName, crState := range crStates.Caches { t.Logf("%v -> %v", cacheName, crState.IsAvailable) } fmt.Println(len(crStates.Deliveryservice), "deliveryservices found") for dsName, deliveryService := range crStates.Deliveryservice { t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations)) } }
package peer import ( "fmt" "io/ioutil" "testing" ) func TestCrStates(t *testing.T) { t.Log("Running Peer Tests") text, err := ioutil.ReadFile("crstates.json") if err != nil { t.Log(err) } crStates, err := CrStatesUnMarshall(text) if err != nil { t.Log(err) } fmt.Println(len(crStates.Caches), "caches found") for cacheName, crState := range crStates.Caches { t.Logf("%v -> %v", cacheName, crState.IsAvailable) } fmt.Println(len(crStates.Deliveryservice), "deliveryservices found") for dsName, deliveryService := range crStates.Deliveryservice { t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations)) } }
Fix `unquote` strategy for strings containing just a single quote
package org.metaborg.meta.lang.template.strategies; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.strategoxt.lang.Context; import org.strategoxt.lang.Strategy; public class unquote_0_0 extends Strategy { public static String unquote(String s) { return s != null && s.length() >= 2 && (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'")) ? s.substring(1, s.length() - 1) : s; } public static unquote_0_0 instance = new unquote_0_0(); @Override public IStrategoTerm invoke(Context context, IStrategoTerm current) { final String str = Tools.asJavaString(current); final ITermFactory factory = context.getFactory(); IStrategoTerm after = factory.makeString(unquote(str)); after = factory.annotateTerm(after, current.getAnnotations()); after = factory.copyAttachments(current, after); return after; } }
package org.metaborg.meta.lang.template.strategies; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.strategoxt.lang.Context; import org.strategoxt.lang.Strategy; public class unquote_0_0 extends Strategy { public static String unquote(String s) { return (s != null && ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'")))) ? s = s.substring(1, s.length() - 1) : s; } public static unquote_0_0 instance = new unquote_0_0(); @Override public IStrategoTerm invoke(Context context, IStrategoTerm current) { final String str = Tools.asJavaString(current); final ITermFactory factory = context.getFactory(); IStrategoTerm after = factory.makeString(unquote(str)); after = factory.annotateTerm(after, current.getAnnotations()); after = factory.copyAttachments(current, after); return after; } }
Raise Http404 instead of 404
# Create your views here. import json from django.template import RequestContext from django.shortcuts import render_to_response from django.utils import simplejson from django.http import HttpResponse, Http404 from .models import BenchmarkLogs, MachineInfo import data def rawdata(request, plotname): """ Based on the ajax request from the template, it calls data.py to fetch the appropriate data. It returns a JSON dump of the dictionary that is returned from data.py """ if request.is_ajax(): try: data_dict = {} data_dict = getattr(data, plotname).__call__() print data_dict return HttpResponse(simplejson.dumps(data_dict), content_type="application/json") except AttributeError: raise Http404 raise Http404 def draw(request, plotname): """ The draw view is responsible for drawing the chart. It renders a template chart.html which sends ajax request for the JSON data. It also provides the template the name of the plot to draw via the <name_dict> dictionary. """ name_dict = {'plotname': plotname} return render_to_response("flot-chart.html", name_dict, context_instance=RequestContext(request))
# Create your views here. import json from django.template import RequestContext from django.shortcuts import render_to_response from django.utils import simplejson from django.http import HttpResponse, Http404 from .models import BenchmarkLogs, MachineInfo import data def rawdata(request, plotname): """ Based on the ajax request from the template, it calls data.py to fetch the appropriate data. It returns a JSON dump of the dictionary that is returned from data.py """ if request.is_ajax(): try: data_dict = {} data_dict = getattr(data, plotname).__call__() print data_dict return HttpResponse(simplejson.dumps(data_dict), content_type="application/json") except AttributeError: raise 404 raise 404 def draw(request, plotname): """ The draw view is responsible for drawing the chart. It renders a template chart.html which sends ajax request for the JSON data. It also provides the template the name of the plot to draw via the <name_dict> dictionary. """ name_dict = {'plotname': plotname} return render_to_response("flot-chart.html", name_dict, context_instance=RequestContext(request))
Add additional isNaN check for check methods.
'use strict'; function hasTypeNumber(numberToCheck) { return typeof numberToCheck === 'number'; } module.exports = { isNumeric: function isNumeric(numberToCheck) { if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) { return false; } return (numberToCheck - parseFloat(numberToCheck) + 1) >= 0; }, isInt: function isInt(numberToCheck) { if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) { return false; } return parseInt(numberToCheck) === numberToCheck; }, isFloat: function isInt(numberToCheck) { if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) { return false; } return !module.exports.isInt(numberToCheck); } };
'use strict'; function hasTypeNumber(numberToCheck) { return typeof numberToCheck === 'number'; } module.exports = { isNumeric: function isNumeric(numberToCheck) { if(!hasTypeNumber(numberToCheck)) { return false; } return (numberToCheck - parseFloat(numberToCheck) + 1) >= 0; }, isInt: function isInt(numberToCheck) { if(!hasTypeNumber(numberToCheck)) { return false; } return parseInt(numberToCheck) === numberToCheck; }, isFloat: function isInt(numberToCheck) { if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) { return false; } return !module.exports.isInt(numberToCheck); } };
Fix a warning and make field final Drive-by fix - additionalHeader should be final, - the class is not serializable, no uuid is needed Change-Id: I484b07e64942179d153e7c42ca32d753fb2a5b23 Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.api; import org.w3c.dom.Document; import com.google.common.base.Optional; /** * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for * implementing ProtocolMessage interface. */ public final class NetconfMessage { private final String additionalHeader; private final Document doc; public NetconfMessage(final Document doc) { this(doc, null); } public NetconfMessage(Document doc, String additionalHeader) { this.doc = doc; this.additionalHeader = additionalHeader; } public Document getDocument() { return this.doc; } public Optional<String> getAdditionalHeader() { return additionalHeader== null ? Optional.<String>absent() : Optional.of(additionalHeader); } }
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.api; import org.w3c.dom.Document; import com.google.common.base.Optional; /** * NetconfMessage represents a wrapper around org.w3c.dom.Document. Needed for * implementing ProtocolMessage interface. */ public final class NetconfMessage { private static final long serialVersionUID = 462175939836367285L; private final Document doc; private String additionalHeader; public NetconfMessage(final Document doc) { this(doc, null); } public NetconfMessage(Document doc, String additionalHeader) { this.doc = doc; this.additionalHeader = additionalHeader; } public Document getDocument() { return this.doc; } public Optional<String> getAdditionalHeader() { return additionalHeader== null ? Optional.<String>absent() : Optional.of(additionalHeader); } }
Add parentFolderId to document post
package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; /** * Optional id of the folder to hold this document. * @since 1.3.0 */ private Long parentFolderId; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } }
package com.researchspace.api.clientmodel; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.Singular; /** * Models the request body of a /documents POST request. All content is optional. * If a form ID is set then the field content must match the field types defined by the Form * @author rspace * @since 1.1.0 * */ @Data @Builder public class DocumentPost { /** * Comma separated tags */ private String tags; /** * name of document */ private String name; @Singular private List<FieldPost> fields; private FormRef form; /** * Appends a {@link FieldPost} to the list of Fields * @param toAdd a {@link FieldPost} * @return <code>true</code> if added, <code>false</code> otherwise */ public boolean addField(FieldPost toAdd) { if(fields == null) { fields = new ArrayList<>(); } return fields.add(toAdd); } }
Move StyleDeclaration outside main function
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser var parser = wef.fn.cssParser; //TODO: loader //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <uo1398@uniovi.es>"], licenses:["MIT"], //TODO: Licenses init:function () { document.addEventListener(parser.events.PROPERTY_FOUND, function (e) { //console.log(e.data.selectorText, e.data.declaration); lastEvent = e; //TODO populate TemplateDOM }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = null; wef.plugins.register("templateLayout", templateLayout); })();
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser var parser = wef.fn.cssParser; //TODO: loader //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <uo1398@uniovi.es>"], licenses:["MIT"], //TODO: Licenses init:function () { document.addEventListener(parser.events.PROPERTY_FOUND, function (e) { // e.target matches the elem from above lastEvent = e; //TODO populate TemplateDOM }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = null; wef.plugins.register("templateLayout", templateLayout); })();
Switch to new ec2 instance
from fabric.api import env env.client = 'zsoobhan' env.project_code = 'prometheus' env.web_dir = 'www' # Environment-agnostic folders env.project_dir = '/var/www/%(client)s/%(project_code)s' % env env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env env.builds_dir = '%(project_dir)s/builds' % env def _configure(build_name): env.build = build_name env.virtualenv = '%(project_dir)s/virtualenvs/%(build)s/' % env env.data_dir = '%(project_dir)s/data/%(build)s/' % env env.nginx_conf = 'www/deploy/nginx/%(build)s.conf' % env env.supervisord_conf = 'www/deploy/supervisord/%(build)s.conf' % env env.wsgi = 'deploy/wsgi/%(build)s.wsgi' % env env.webserver_user = 'www-data' def prod(): _configure('prod') env.hosts = ['ec2-54-154-143-128.eu-west-1.compute.amazonaws.com'] env.remote_user = 'ubuntu' def test(): _configure('test') env.remote_user = 'ubuntu'
from fabric.api import env env.client = 'zsoobhan' env.project_code = 'prometheus' env.web_dir = 'www' # Environment-agnostic folders env.project_dir = '/var/www/%(client)s/%(project_code)s' % env env.static_dir = '/mnt/static/%(client)s/%(project_code)s' % env env.builds_dir = '%(project_dir)s/builds' % env def _configure(build_name): env.build = build_name env.virtualenv = '%(project_dir)s/virtualenvs/%(build)s/' % env env.data_dir = '%(project_dir)s/data/%(build)s/' % env env.nginx_conf = 'www/deploy/nginx/%(build)s.conf' % env env.supervisord_conf = 'www/deploy/supervisord/%(build)s.conf' % env env.wsgi = 'deploy/wsgi/%(build)s.wsgi' % env env.webserver_user = 'www-data' def prod(): _configure('prod') env.hosts = ['ec2-54-77-186-157.eu-west-1.compute.amazonaws.com'] env.remote_user = 'ubuntu' def test(): _configure('test') env.remote_user = 'ubuntu'
Remove unused import left over from an earlier version of this patch
from distutils.core import Extension from os.path import dirname, join, relpath ASTROPY_UTILS_ROOT = dirname(__file__) def get_extensions(): return [ Extension('astropy.utils._compiler', [relpath(join(ASTROPY_UTILS_ROOT, 'src', 'compiler.c'))]) ] def get_package_data(): # Installs the testing data files return { 'astropy.utils.tests': [ 'data/*.dat', 'data/*.dat.gz', 'data/*.dat.bz2', 'data/*.txt'] }
from distutils.core import Extension from os.path import dirname, join, relpath, exists ASTROPY_UTILS_ROOT = dirname(__file__) def get_extensions(): return [ Extension('astropy.utils._compiler', [relpath(join(ASTROPY_UTILS_ROOT, 'src', 'compiler.c'))]) ] def get_package_data(): # Installs the testing data files return { 'astropy.utils.tests': [ 'data/*.dat', 'data/*.dat.gz', 'data/*.dat.bz2', 'data/*.txt'] }
Enable preventing remote access to debug environment on production server
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. /*if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); }*/ $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Update development status trove classifier from Alpha to Beta
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import carrot setup( name='carrot', version=carrot.__version__, description=carrot.__doc__, author=carrot.__author__, author_email=carrot.__contact__, url=carrot.__homepage__, platforms=["any"], packages=find_packages(exclude=['ez_setup']), test_suite="nose.collector", install_requires=[ 'amqplib', ], classifiers=[ "Development Status :: 4 - Beta", "Framework :: Django", "Operating System :: OS Independent", "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Topic :: Communications", "Topic :: System :: Distributed Computing", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description=codecs.open('README.rst', "r", "utf-8").read(), )
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import carrot setup( name='carrot', version=carrot.__version__, description=carrot.__doc__, author=carrot.__author__, author_email=carrot.__contact__, url=carrot.__homepage__, platforms=["any"], packages=find_packages(exclude=['ez_setup']), test_suite="nose.collector", install_requires=[ 'amqplib', ], classifiers=[ "Development Status :: 3 - Alpha", "Framework :: Django", "Operating System :: OS Independent", "Programming Language :: Python", ], long_description=codecs.open('README.rst', "r", "utf-8").read(), )
Modify the Page parameter with url supplied
''' from pycrawl import crawler # Execute variants page = crawler.grab('http://www.pasarpanda.com') page = crawler.from_file('file.html') page = crawler.from_text("<html></html>") # methods page.html('#my_container') # get html content by given css selector page.text('#my_container') # get text content by given css selector page.images() # all images links # information provided page.title # page title page.encoding # page encoding page.language # text language of page page.metas # list dictionary of meta page.content # text content page.copyright # copyright page.links # all links on the site page.original_links # all original links (the domain links are same as the requested page) page.resource_links # all js & css links page.js_links # all javascript links page.css_links # all css links page.favicon # favicon url ''' from .http import HttpRequest from .page import Page class Crawler: @classmethod def grab(cls, url): content = HttpRequest.get(url) return Page(content, url=url) @classmethod def from_file(cls, abs_path): f = open(abs_path, 'r') content = f.read() f.close() return Page(content) @classmethod def from_text(cls, text): return Page(text)
''' from pycrawl import crawler # Execute variants page = crawler.grab('http://www.pasarpanda.com') page = crawler.from_file('file.html') page = crawler.from_text("<html></html>") # methods page.html('#my_container') # get html content by given css selector page.text('#my_container') # get text content by given css selector page.images() # all images links # information provided page.title # page title page.encoding # page encoding page.language # text language of page page.metas # list dictionary of meta page.content # text content page.copyright # copyright page.links # all links on the site page.original_links # all original links (the domain links are same as the requested page) page.resource_links # all js & css links page.js_links # all javascript links page.css_links # all css links page.favicon # favicon url ''' from .http import HttpRequest from .page import Page class Crawler: @classmethod def grab(cls, url): content = HttpRequest.get(url) return Page(content) @classmethod def from_file(cls, abs_path): f = open(abs_path, 'r') content = f.read() f.close() return Page(content) @classmethod def from_text(cls, text): return Page(text)
Revert "log to file, don't email" This reverts commit a132890ef32c99b938021717b67c3e58c13952b0.
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
Rename event handler, add docstrings
package edu.colorado.csdms.wmt.client.ui.cell; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.ui.TextBox; import edu.colorado.csdms.wmt.client.data.ParameterJSO; /** * Creates an editable text box in a {@link ValueCell}. {@link KeyUpHandler} * events are handled in {@link TextCellHandler}. * * @author Mark Piper (mark.piper@colorado.edu) */ public class TextCell extends TextBox { private ValueCell parent; private ParameterJSO parameter; /** * Makes a {@link TextCell} initialized with the default value of a "string" * parameter type. * * @param parent the parent of the TextCell, a ValueCell */ public TextCell(ValueCell parent) { this.parent = parent; this.parameter = this.parent.getParameter(); this.addKeyUpHandler(new TextCellHandler()); this.setStyleName("wmt-TextBoxen"); this.setText(parameter.getValue().getDefault()); } /** * The handler for keyboard events in a TextCell. */ public class TextCellHandler implements KeyUpHandler { @Override public void onKeyUp(KeyUpEvent event) { GWT.log("(onKeyUp:text)"); TextCell cell = (TextCell) event.getSource(); parent.setParameterValue(cell.getText()); } } }
package edu.colorado.csdms.wmt.client.ui.cell; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.ui.TextBox; import edu.colorado.csdms.wmt.client.data.ParameterJSO; /** * Displays an editable text box in a {@link ValueCell}. It's initialized with * the default value of a "string" parameter type. * * @author Mark Piper (mark.piper@colorado.edu) */ public class TextCell extends TextBox { private ValueCell parent; private ParameterJSO parameter; public TextCell(ValueCell parent) { this.parent = parent; this.parameter = this.parent.getParameter(); this.addKeyUpHandler(new TextEditHandler()); this.setStyleName("wmt-TextBoxen"); this.setText(parameter.getValue().getDefault()); } /** * The handler for keyboard events in a TextCell. */ public class TextEditHandler implements KeyUpHandler { @Override public void onKeyUp(KeyUpEvent event) { GWT.log("(onKeyUp:text)"); TextCell cell = (TextCell) event.getSource(); parent.setParameterValue(cell.getText()); } } }
Use PHP 5.4 short array syntax.
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'))); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
Fix ordering in string expansion example
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') result = bibpy.read_file(filename, format='relaxed') entries, strings = result.entries, result.strings print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') entries, strings = bibpy.read_file(filename, format='relaxed')[:2] print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
Use discover runner on older djangos
#!/usr/bin/env python # Adapted from https://raw.githubusercontent.com/hzy/django-polarize/master/runtests.py import sys from django.conf import settings from django.core.management import execute_from_command_line import django if django.VERSION < (1, 6): extra_settings = { 'TEST_RUNNER': 'discover_runner.DiscoverRunner', } else: extra_settings = {} if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INSTALLED_APPS=( 'tests', ), MIDDLEWARE_CLASSES=( ), ROOT_URLCONF='tests.urls', **extra_settings, ) def runtests(): argv = sys.argv[:1] + ['test', 'tests'] execute_from_command_line(argv) if __name__ == '__main__': runtests()
#!/usr/bin/env python # Adapted from https://raw.githubusercontent.com/hzy/django-polarize/master/runtests.py import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INSTALLED_APPS=( 'tests', ), MIDDLEWARE_CLASSES=( ), ROOT_URLCONF='tests.urls', ) def runtests(): argv = sys.argv[:1] + ['test', 'tests'] execute_from_command_line(argv) if __name__ == '__main__': runtests()
Handle the case where the user exits the panel
import sublime import sublime_plugin class QuickFileOpenCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') if type(files) == list: self.window.show_quick_panel(files, self.on_done) elif files is None: self.window.show_quick_panel(['Set the \'files\' setting to use QuickFileOpen'], None) else: sublime.error_message('The \'files\' setting must be a list') def on_done(self, selected): if selected == -1: return settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') fileName = files[selected] self.window.open_file(fileName)
import sublime import sublime_plugin class QuickFileOpenCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') if type(files) == list: self.window.show_quick_panel(files, self.on_done) elif files is None: self.window.show_quick_panel(['Set the \'files\' setting to use QuickFileOpen'], None) else: sublime.error_message('The \'files\' setting must be a list') def on_done(self, selected): settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') fileName = files[selected] self.window.open_file(fileName)
Fix error with setting version
from setuptools import setup, find_packages execfile('./bmi_ilamb/version.py') setup(name='bmi-ilamb', version=__version__, description='BMI for ILAMB', long_description=open('README.md').read(), url='https://github.com/permamodel/bmi-ilamb', license='MIT', author='Mark Piper', author_email='mark.piper@colorado.edu', packages=find_packages(exclude=['*.tests']), package_data={'': ['data/*']}, install_requires=['pyyaml', 'basic-modeling-interface'], keywords='CSDMS BMI ILAMB model benchmark', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], )
from setuptools import setup, find_packages setup(name='bmi-ilamb', version=execfile('./bmi_ilamb/version.py'), description='BMI for ILAMB', long_description=open('README.md').read(), url='https://github.com/permamodel/bmi-ilamb', license='MIT', author='Mark Piper', author_email='mark.piper@colorado.edu', packages=find_packages(exclude=['*.tests']), package_data={'': ['data/*']}, install_requires=['pyyaml', 'basic-modeling-interface'], keywords='CSDMS BMI ILAMB model benchmark', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], )
Update with reference to global nav partial
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-transform/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-transform/tachyons-text-transform.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-transform.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/text-transform/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/text-transform/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-transform/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-transform/tachyons-text-transform.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-transform.css', 'utf8') var template = fs.readFileSync('./templates/docs/text-transform/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/typography/text-transform/index.html', html)
Add PySide to as.studio init preferred binding
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import *
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = "PyQt4" from _appleseedstudio import *
Fix deprecation warning for the source-mongodb plugin.
module.exports = { plugins: [ /* * Gatsby's data processing layer begins with “source” plugins. Here we * setup the site to pull data from the "documents" collection in a local * MongoDB instance */ { resolve: 'gatsby-source-mongodb', options: { dbName: process.env.MONGODB_NAME, server: { address: process.env.MONGODB_ADDRESS, port: process.env.MONGODB_PORT }, auth: { user: process.env.MONGODB_USER, password: process.env.MONGODB_PASS }, collection: ['sportsAndCountries', 'events'], clientOptions: { useUnifiedTopology: true } } }, { resolve: 'gatsby-plugin-stylus' } ] }
module.exports = { plugins: [ /* * Gatsby's data processing layer begins with “source” plugins. Here we * setup the site to pull data from the "documents" collection in a local * MongoDB instance */ { resolve: 'gatsby-source-mongodb', options: { dbName: process.env.MONGODB_NAME, server: { address: process.env.MONGODB_ADDRESS, port: process.env.MONGODB_PORT }, auth: { user: process.env.MONGODB_USER, password: process.env.MONGODB_PASS }, collection: ['sportsAndCountries', 'events'] } }, { resolve: 'gatsby-plugin-stylus' } ] }
Add get all posts route
import Job from './handlers/job' import Home from './handlers/home' import Github from './handlers/github' import Ping from './handlers/ping' import Post from './handlers/post' export default [ { method: 'GET', path: '/', config: { auth: false, handler: Home } }, { method: 'GET', path: '/ping', config: { auth: false, handler: Ping } }, { method: 'POST', path: '/jobs', config: Job.create }, { method: 'GET', path: '/jobs/{id}', config: Job.get }, { method: 'GET', path: '/jobs', config: Job.getAll }, { method: 'DELETE', path: '/jobs/{id}', config: Job.remove }, { method: 'PUT', path: '/jobs/{id}', config: Job.update }, { method: 'GET', path: '/github/activities', config: Github.getAll }, { method: 'POST', path: '/posts', config: Post.create }, { method: 'GET', path: '/posts/{slug}', config: Post.get }, { method: 'GET', path: '/posts', config: Post.getAll } ]
import Job from './handlers/job' import Home from './handlers/home' import Github from './handlers/github' import Ping from './handlers/ping' import Post from './handlers/post' export default [ { method: 'GET', path: '/', config: { auth: false, handler: Home } }, { method: 'GET', path: '/ping', config: { auth: false, handler: Ping } }, { method: 'POST', path: '/jobs', config: Job.create }, { method: 'GET', path: '/jobs/{id}', config: Job.get }, { method: 'GET', path: '/jobs', config: Job.getAll }, { method: 'DELETE', path: '/jobs/{id}', config: Job.remove }, { method: 'PUT', path: '/jobs/{id}', config: Job.update }, { method: 'GET', path: '/github/activities', config: Github.getAll }, { method: 'POST', path: '/posts', config: Post.create }, { method: 'GET', path: '/posts/{slug}', config: Post.get } ]
Add an option to disable code reloader to runserver command
#!/usr/bin/env python import os from argh import arg, ArghParser from argh.exceptions import CommandError from functools import wraps CONFIG = os.environ.get('ALFRED_CONFIG') def with_app(func): @wraps(func) @arg('--config', help='path to config') def wrapper(args): from alfred import create_app if not CONFIG and not args.config: raise CommandError('There is no config file specified') app = create_app(args.config or CONFIG) return func(app, args) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) @with_app def collectassets(app, args): from alfred.assets import gears gears.get_environment(app).save() def main(): parser = ArghParser() parser.add_commands([runserver, shell, collectassets]) parser.dispatch() if __name__ == '__main__': main()
#!/usr/bin/env python import os from argh import arg, ArghParser from argh.exceptions import CommandError from functools import wraps CONFIG = os.environ.get('ALFRED_CONFIG') def with_app(func): @wraps(func) @arg('--config', help='path to config') def wrapper(args): from alfred import create_app if not CONFIG and not args.config: raise CommandError('There is no config file specified') app = create_app(args.config or CONFIG) return func(app, args) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) @with_app def collectassets(app, args): from alfred.assets import gears gears.get_environment(app).save() def main(): parser = ArghParser() parser.add_commands([runserver, shell, collectassets]) parser.dispatch() if __name__ == '__main__': main()
:new: Add onDidUpdateMessages to indie registry
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.subscriptions.add('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.subscriptions.add('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) this.emit('observe', indieLinter) return indieLinter } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.subscriptions.add('observe', callback) } dispose() { this.subscriptions.dispose() } }
Include the request method in `trackAPIError`.
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( type, identifier, datapoint, error ) { await trackEvent( 'api_error', `${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
Fix WinMailslot object to only use a single handle rather than a list
# Copyright (c) 2013, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import unittest from cybox.objects.win_mailslot_object import WinMailslot from cybox.test.objects import ObjectTestCase class TestWinMailslot(ObjectTestCase, unittest.TestCase): object_type = "WindowsMailslotObjectType" klass = WinMailslot _full_dict = { 'handle': { 'name': "First Mailslot Handle", 'type': "Mailslot", 'xsi:type': "WindowsHandleObjectType", }, 'max_message_size': 1024, 'name': "My Mailslot", 'read_timeout': 2000, 'security_attributes': "SecAttributes", 'xsi:type': object_type, } if __name__ == "__main__": unittest.main()
# Copyright (c) 2013, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import unittest from cybox.objects.win_mailslot_object import WinMailslot from cybox.test.objects import ObjectTestCase class TestWinMailslot(ObjectTestCase, unittest.TestCase): object_type = "WindowsMailslotObjectType" klass = WinMailslot _full_dict = { 'handle': [ { 'name': "First Mailslot Handle", 'type': "Mailslot", 'xsi:type': "WindowsHandleObjectType", }, { 'name': "Second Mailslot Handle", 'xsi:type': "WindowsHandleObjectType", }, ], 'max_message_size': 1024, 'name': "My Mailslot", 'read_timeout': 2000, 'security_attributes': "SecAttributes", 'xsi:type': object_type, } if __name__ == "__main__": unittest.main()
Add gulp task to run tests on file change.
'use strict'; var gulp = require('gulp'); var del = require('del'); var babel = require('gulp-babel'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var mocha = require('gulp-mocha'); var mochaBabelRegister = require('babel/register'); var buildDestination = 'build' gulp.task('build', function() { del([buildDestination], function() { var bundleStream = browserify({ entries: './index.js', debug: true, }).bundle(); return bundleStream .pipe(source('min-flux.js')) .pipe(buffer()) .pipe(babel()) .pipe(gulp.dest(buildDestination)); }); }); gulp.task('test', function() { return gulp.src(['test/**/*.js'], { read: false }) .pipe(mocha({ reporter: 'dot', })); }); gulp.task('live-test', function() { return gulp.watch(['index.js', 'lib/**/*.js', 'test/**/*.js'], ['test']); }); gulp.task('default', ['test']);
'use strict'; var gulp = require('gulp'); var del = require('del'); var babel = require('gulp-babel'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var mocha = require('gulp-mocha'); var mochaBabelRegister = require('babel/register'); var buildDestination = 'build' gulp.task('build', function() { del([buildDestination], function() { var bundleStream = browserify({ entries: './index.js', debug: true, }).bundle(); return bundleStream .pipe(source('min-flux.js')) .pipe(buffer()) .pipe(babel()) .pipe(gulp.dest(buildDestination)); }); }); gulp.task('test', function() { var MinFlux = require('./index'); var expect = require('chai').expect; return gulp.src(['test/**/*.js'], { read: false }) .pipe(mocha({ reporter: 'dot', require: [ './index', 'chai', ], })); }); gulp.task('default', ['test']);
Fix user password editing in the backend
<?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. */ namespace Sylius\Bundle\CoreBundle\EventListener; use FOS\UserBundle\Model\UserInterface; use FOS\UserBundle\Model\UserManagerInterface; use Sylius\Component\Resource\Exception\UnexpectedTypeException; use Symfony\Component\EventDispatcher\GenericEvent; /** * User update listener. * * @author Saša Stamenković <umpirsky@gmail.com> */ class UserUpdateListener { protected $userManager; public function __construct(UserManagerInterface $userManager) { $this->userManager = $userManager; } public function processUser(GenericEvent $event) { $user = $event->getSubject(); if (!$user instanceof UserInterface) { throw new UnexpectedTypeException( $user, 'FOS\UserBundle\Model\UserInterface' ); } $this->userManager->updateUser($user); $this->userManager->reloadUser($user); } }
<?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. */ namespace Sylius\Bundle\CoreBundle\EventListener; use FOS\UserBundle\Model\UserInterface; use FOS\UserBundle\Model\UserManagerInterface; use Sylius\Component\Resource\Exception\UnexpectedTypeException; use Symfony\Component\EventDispatcher\GenericEvent; /** * User update listener. * * @author Saša Stamenković <umpirsky@gmail.com> */ class UserUpdateListener { protected $userManager; public function __construct(UserManagerInterface $userManager) { $this->userManager = $userManager; } public function processUser(GenericEvent $event) { $user = $event->getSubject(); if (!$user instanceof UserInterface) { throw new UnexpectedTypeException( $user, 'FOS\UserBundle\Model\UserInterface' ); } $this->userManager->reloadUser($user); } }
Make ball start by flying upwards
/* * Object that contains Game initialization data. */ export default class { constructor(canvasWidth, canvasHeight) { this.gameInits = {}; this._generateInitialSettings(canvasWidth, canvasHeight); } _generateInitialSettings(canvasWidth, canvasHeight) { this.gameInits.paddle = (()=> { let width = 60; let height = 6; return { x: (canvasWidth - width) / 2, y: canvasHeight - height, color: '#555555', width: width, height: height }; })(); this.gameInits.ball = (()=> { return { x: canvasWidth / 2, y: canvasHeight - 30, velocityX: 1, velocityY: -1, color: '#555555', radius: 10, }; })(); } };
/* * Object that contains Game initialization data. */ export default class { constructor(canvasWidth, canvasHeight) { this.gameInits = {}; this._generateInitialSettings(canvasWidth, canvasHeight); } _generateInitialSettings(canvasWidth, canvasHeight) { this.gameInits.paddle = (()=> { let width = 60; let height = 6; return { x: (canvasWidth - width) / 2, y: canvasHeight - height, color: '#555555', width: width, height: height }; })(); this.gameInits.ball = (()=> { return { x: canvasWidth / 2, y: canvasHeight - 30, velocityX: 1, velocityY: 1, color: '#555555', radius: 10, }; })(); } };
Fix the callback call in risk free rate.
"use strict"; var request = require("request"), cheerio = require("cheerio"); function getRiskFreeRateFromYahoo(callback) { var url = "http://finance.yahoo.com/bonds"; request({ method: "GET", uri: url }, function (err, response, body) { var $, rf; if (!err) { $ = cheerio.load(body); // US Treasury Bonds Rates 3 Month rf = $("table.yfirttbl > tbody > " + "tr:nth-child(1) > td:nth-child(2)") .text() / 100; } callback(err, rf); }); } exports.getRiskFreeRateFromYahoo = getRiskFreeRateFromYahoo;
"use strict"; var request = require("request"), cheerio = require("cheerio"); function getRiskFreeRateFromYahoo(callback) { var url = "http://finance.yahoo.com/bonds"; request({ method: "GET", uri: url }, function (err, response, body) { var $, rf; if (!err) { $ = cheerio.load(body); // US Treasury Bonds Rates 3 Month rf = $("table.yfirttbl > tbody > " + "tr:nth-child(1) > td:nth-child(2)") .text() / 100; callback(err, rf); } }); } exports.getRiskFreeRateFromYahoo = getRiskFreeRateFromYahoo;
Add info inside TPC check iframe attribute for curious eyes
/* globals self, bufferpm, chrome */ // buffer-tpc-check.js // (c) 2013 Sunil Sadasivan // Check if third party cookies are disabled // ;(function () { if (window !== window.top) return; ;(function check() { if((self.port) || (xt && xt.options)) { //if the 3rd party cookies check is disabled, store it bufferpm.bind("buffer_3pc_disabled", function(){ if(xt && xt.options) { xt.options['buffer.op.tpc-disabled'] = true; } self.port.emit('buffer_tpc_disabled'); return false; }); var iframe = document.createElement('iframe'); iframe.id = 'buffer_tpc_check'; iframe.src = xt.data.get('data/shared/tpc-check.html'); iframe.style.display="none"; iframe.setAttribute('data-info', 'The Buffer extension uses this iframe to automatically ' + 'detect the browser\'s third-party cookies settings and offer the best experience based on those'); document.body.appendChild(iframe); } else { setTimeout(check, 50); } }()); }());
/* globals self, bufferpm, chrome */ // buffer-tpc-check.js // (c) 2013 Sunil Sadasivan // Check if third party cookies are disabled // ;(function () { if (window !== window.top) return; ;(function check() { if((self.port) || (xt && xt.options)) { //if the 3rd party cookies check is disabled, store it bufferpm.bind("buffer_3pc_disabled", function(){ if(xt && xt.options) { xt.options['buffer.op.tpc-disabled'] = true; } self.port.emit('buffer_tpc_disabled'); return false; }); var iframe = document.createElement('iframe'); iframe.id = 'buffer_tpc_check'; iframe.src = xt.data.get('data/shared/tpc-check.html'); iframe.style.display="none"; document.body.appendChild(iframe); } else { setTimeout(check, 50); } }()); }());
Create destination directory if not exists
'use strict'; var fs = require('fs'); var path = require('path'); var q = require('q'); var mkdir = q.denodeify(fs.mkdir); /** * Themeleon helper constructor. * * See the functions from `factory.js` for variables signification. * * This constructor has an empty prototype (except the `use` method) since * Themeleon works only with mixins. There's a main mixin in `main.js` * containing the base functions, and all the extensions are merged in the * same way on the object instance. * * The purpose of this constructor is only to create new instances with * conventional properties to be used by the mixins. * * @constructor * @param {String} src * @param {String} dest * @param {Object} ctx */ module.exports = function Themeleon(src, dest, ctx) { this.tasks = []; this.src = path.resolve(src); this.dest = path.resolve(dest); this.ctx = ctx; // Shortcut to push a promise this.push = this.tasks.push.bind(this.tasks); // Create directory maybe this.push(mkdir(dest)); }; /** * Mix given object(s) with current instance. * * @param {...Object} obj */ module.exports.prototype.use = function (/* obj... */) { for (var i = 0; i < arguments.length; i++) { for (var j in arguments[i]) { this[j] = arguments[i][j]; } } };
'use strict'; var path = require('path'); /** * Themeleon helper constructor. * * See the functions from `factory.js` for variables signification. * * This constructor has an empty prototype (except the `use` method) since * Themeleon works only with mixins. There's a main mixin in `main.js` * containing the base functions, and all the extensions are merged in the * same way on the object instance. * * The purpose of this constructor is only to create new instances with * conventional properties to be used by the mixins. * * @constructor * @param {String} src * @param {String} dest * @param {Object} ctx */ module.exports = function Themeleon(src, dest, ctx) { this.tasks = []; this.src = path.resolve(src); this.dest = path.resolve(dest); this.ctx = ctx; // Shortcut to push a promise this.push = this.tasks.push.bind(this.tasks); }; /** * Mix given object(s) with current instance. * * @param {...Object} obj */ module.exports.prototype.use = function (/* obj... */) { for (var i = 0; i < arguments.length; i++) { for (var j in arguments[i]) { this[j] = arguments[i][j]; } } };
Use upload widget in the default state.
from django.apps import AppConfig from .ckeditor_config import DEFAULT_CONFIG default_app_config = 'leonardo_ckeditor.Config' LEONARDO_APPS = [ 'leonardo_ckeditor', 'ckeditor', 'ckeditor_uploader' ] LEONARDO_CONFIG = { 'CKEDITOR_UPLOAD_PATH': ('', ('CKEditor upload directory')), 'CKEDITOR_CONFIGS': ({'default': DEFAULT_CONFIG}, 'ckeditor config') } LEONARDO_OPTGROUP = 'CKEditor' LEONARDO_JS_FILES = [ "leonardo_ckeditor/js/ckeditor-modal-init.js", ] LEONARDO_CSS_FILES = [ 'ckeditor/ckeditor/skins/moono/editor.css' ] LEONARDO_PUBLIC = True LEONARDO_URLS_CONF = 'ckeditor_uploader.urls' class Config(AppConfig): name = 'leonardo_ckeditor' verbose_name = "leonardo-ckeditor" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from leonardo.module.web.widget.htmltext import models models.HtmlTextWidget.widgets['text'] = CKEditorUploadingWidget()
from django.apps import AppConfig from .ckeditor_config import DEFAULT_CONFIG default_app_config = 'leonardo_ckeditor.Config' LEONARDO_APPS = [ 'leonardo_ckeditor', 'ckeditor', 'ckeditor_uploader' ] LEONARDO_CONFIG = { 'CKEDITOR_UPLOAD_PATH': ('uploads/', ('CKEditor upload directory')), 'CKEDITOR_CONFIGS': ({'default': DEFAULT_CONFIG}, 'ckeditor config') } LEONARDO_OPTGROUP = 'CKEditor' LEONARDO_JS_FILES = [ "leonardo_ckeditor/js/ckeditor-modal-init.js", ] LEONARDO_CSS_FILES = [ 'ckeditor/ckeditor/skins/moono/editor.css' ] LEONARDO_PUBLIC = True LEONARDO_URLS_CONF = 'ckeditor_uploader.urls' class Config(AppConfig): name = 'leonardo_ckeditor' verbose_name = "leonardo-ckeditor" def ready(self): from ckeditor.widgets import CKEditorWidget from leonardo.module.web.widget.htmltext import models models.HtmlTextWidget.widgets['text'] = CKEditorWidget()
Add list_filter to example ArticleAdmin When using a list filter and then adding or editing an object the language GET parameter goes missing causing the wrong translation to be edited.
from django.contrib import admin from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget from parler.admin import TranslatableAdmin from .models import Article from parler.forms import TranslatableModelForm, TranslatedField class ArticleAdminForm(TranslatableModelForm): """ Example form Translated fields can be enhanced by manually declaring them: """ title = TranslatedField(widget=AdminTextInputWidget) content = TranslatedField(widget=AdminTextareaWidget) class ArticleAdmin(TranslatableAdmin): """ Example admin. Using an empty class would already work, but this example shows some additional options. """ # The 'language_column' is provided by the base class: list_display = ('title', 'language_column') list_filter = ('published',) # Example custom form usage. form = ArticleAdminForm # NOTE: when using Django 1.4, use declared_fieldsets= instead of fieldsets= fieldsets = ( (None, { 'fields': ('title', 'slug', 'published'), }), ("Contents", { 'fields': ('content',), }) ) def get_prepopulated_fields(self, request, obj=None): # Can't use prepopulated_fields= yet, but this is a workaround. return {'slug': ('title',)} admin.site.register(Article, ArticleAdmin)
from django.contrib import admin from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget from parler.admin import TranslatableAdmin from .models import Article from parler.forms import TranslatableModelForm, TranslatedField class ArticleAdminForm(TranslatableModelForm): """ Example form Translated fields can be enhanced by manually declaring them: """ title = TranslatedField(widget=AdminTextInputWidget) content = TranslatedField(widget=AdminTextareaWidget) class ArticleAdmin(TranslatableAdmin): """ Example admin. Using an empty class would already work, but this example shows some additional options. """ # The 'language_column' is provided by the base class: list_display = ('title', 'language_column') # Example custom form usage. form = ArticleAdminForm # NOTE: when using Django 1.4, use declared_fieldsets= instead of fieldsets= fieldsets = ( (None, { 'fields': ('title', 'slug', 'published'), }), ("Contents", { 'fields': ('content',), }) ) def get_prepopulated_fields(self, request, obj=None): # Can't use prepopulated_fields= yet, but this is a workaround. return {'slug': ('title',)} admin.site.register(Article, ArticleAdmin)
Remove the unnecessary render on start up
const { configureStore } = require('../store'); const readline = require('readline'); const draw = require('./draw'); const { keys } = require('./input'); const actions = require('../actions'); const resize = (proc, store) => { const action = actions.resize({ rows: proc.stdout.rows, columns: proc.stdout.columns }); store.dispatch(action); }; module.exports = (initialState, proc = process) => { const store = configureStore(proc, initialState); const onStateChange = draw(proc, store); store.subscribe(onStateChange); proc.stdin.addListener('keypress', keys(store)); proc.stdout.addListener('resize', () => resize(proc, store)); resize(proc, store); readline.emitKeypressEvents(proc.stdin); proc.stdin.setRawMode(true); };
const { configureStore } = require('../store'); const readline = require('readline'); const draw = require('./draw'); const { keys } = require('./input'); const actions = require('../actions'); const resize = (proc, store) => { const action = actions.resize({ rows: proc.stdout.rows, columns: proc.stdout.columns }); store.dispatch(action); }; module.exports = (initialState, proc = process) => { const store = configureStore(proc, initialState); const onStateChange = draw(proc, store); store.subscribe(onStateChange); onStateChange(); proc.stdin.addListener('keypress', keys(store)); proc.stdout.addListener('resize', () => resize(proc, store)); resize(proc, store); readline.emitKeypressEvents(proc.stdin); proc.stdin.setRawMode(true); };
Fix minor bug in weather source.
/** * Provides weather data from the Yahoo API. The ID of a location can be found at * http://woeid.rosselliot.co.nz/. * * Provides data in the form: * { * temperature: "14" // in Celsius * code: "weather_condition_code" // one from http://developer.yahoo.com/weather/#codes * city: "city name" * } */ Dashboard.WeatherSource = Dashboard.PeriodicSource.extend({ period: 300000, woeId: null, dataUpdate: function(callback) { var query = "select * from weather.forecast WHERE woeid=" + this.get('woeId') + " and u='c'"; var url = "http://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(query) + "&format=json"; $.get(url, function(data) { var results = data.query.results; var condition = results.channel.item.condition; callback({ temperature: condition.temp, code: condition.code, city: results.channel.location.city }) }); } });
/** * Provides weather data from the Yahoo API. The ID of a location can be found at * http://woeid.rosselliot.co.nz/. * * Provides data in the form: * { * temperature: "14" // in Celsius * code: "weather_condition_code" // one from http://developer.yahoo.com/weather/#codes * city: "city name" * } */ Dashboard.WeatherSource = Dashboard.PeriodicSource.extend({ period: 300000, woeId: null, dataUpdate: function(callback) { var query = "select * from weather.forecast WHERE woeid=" + this.get('woeId') + " and u='c'&format=json"; var url = "http://query.yahooapis.com/v1/public/yql?q=" + encodeURI(query); $.get(url, function(data) { var results = data.query.results; var condition = results.channel.item.condition; callback({ temperature: condition.temp, code: condition.code, city: results.channel.location.city }) }); } });
Add initial url to question
"""golingo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from quiz.views import QuestionTemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^question/$', QuestionTemplateView.as_view(), name='question'), ]
"""golingo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
Clear label state when navigating away from it.
/* @flow */ import { createAction } from 'redux-actions' const { objOf, map } = require('ramda') import { compose } from 'sanctuary' import { get_body } from 'app/http' import { PATH_UPDATE } from '../../../shared/redux/modules/route.js' import type { Action, Reducer } from 'redux' type State = typeof initialState const initialState = { addresses: [] } const reducer: Reducer<State, Action> = (state = initialState, { type, payload }) => { switch (type) { case NEWSLETTER_LABELS: return compose(objOf('addresses'))(map(addresses))(payload.results) case PATH_UPDATE: return initialState default: return state } } export default reducer const addresses = ( { title , first_name , last_name , initials , ...address_lines } ) => ( { addressee: `${title || ''} ${first_name || initials || ''} ${last_name}` , ...address_lines } ) const NEWSLETTER_LABELS = 'NEWSLETTER_LABELS' export const newsletter_labels = createAction(NEWSLETTER_LABELS, () => get_body('/api/newsletter-labels'))
/* @flow */ import { createAction } from 'redux-actions' const { objOf, map } = require('ramda') import { compose } from 'sanctuary' import { get_body } from 'app/http' import type { Action, Reducer } from 'redux' type State = typeof initialState const initialState = { addresses: [] } const reducer: Reducer<State, Action> = (state = initialState, { type, payload }) => { switch (type) { case NEWSLETTER_LABELS: return compose(objOf('addresses'))(map(addresses))(payload.results) default: return state } } export default reducer const addresses = ( { title , first_name , last_name , initials , ...address_lines } ) => ( { addressee: `${title || ''} ${first_name || initials || ''} ${last_name}` , ...address_lines } ) const NEWSLETTER_LABELS = 'NEWSLETTER_LABELS' export const newsletter_labels = createAction(NEWSLETTER_LABELS, () => get_body('/api/newsletter-labels'))
Fix the ASDF test for TimeDelta formats
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time, TimeDelta @pytest.mark.parametrize('fmt', TimeDelta.FORMATS.keys()) def test_timedelta(fmt, tmpdir): t1 = Time(Time.now()) t2 = Time(Time.now()) td = TimeDelta(t2 - t1, format=fmt) tree = dict(timedelta=td) assert_roundtrip_tree(tree, tmpdir) @pytest.mark.parametrize('scale', list(TimeDelta.SCALES) + [None]) def test_timedetal_scales(scale, tmpdir): tree = dict(timedelta=TimeDelta(0.125, scale=scale)) assert_roundtrip_tree(tree, tmpdir)
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time, TimeDelta @pytest.mark.parametrize('fmt', Time.FORMATS.keys()) def test_timedelta(fmt, tmpdir): t1 = Time(Time.now(), format=fmt) t2 = Time(Time.now(), format=fmt) td = t2 - t1 tree = dict(timedelta=td) assert_roundtrip_tree(tree, tmpdir) @pytest.mark.parametrize('scale', list(TimeDelta.SCALES) + [None]) def test_timedetal_scales(scale, tmpdir): tree = dict(timedelta=TimeDelta(0.125, scale=scale)) assert_roundtrip_tree(tree, tmpdir)
Fix count -> strlen bug
<?php /** * Input receiver for SMTP server piping * In your application file: list($message, $additionalData) = require('$path_to_smp/includes/message-pipe.php'); * Usage for Exim4 filter file: pipe "php $path_to_bin/your_application.php $sender_address" * Raw mail body given on STDIN */ if ($argc < 2) { die("Sender address required as the first parameter\n"); } $senderAddress = $argv[1]; $rawMessage = file_get_contents('php://stdin'); if ($rawMessage === false) { die("Can't read standard input to get message body\n"); } if (strlen($rawMessage) < 1) { die("Message body (read from standard input) is empty\n"); } $rawClearedMessage = substr($rawMessage, strpos($rawMessage, "\n") + 1); $message = \Feedbee\Smp\Mail\Message::fromString($rawClearedMessage); return [$message, ['sender_address' => $senderAddress]];
<?php /** * Input receiver for SMTP server piping * In your application file: list($message, $additionalData) = require('$path_to_smp/includes/message-pipe.php'); * Usage for Exim4 filter file: pipe "php $path_to_bin/your_application.php $sender_address" * Raw mail body given on STDIN */ if ($argc < 2) { die("Sender address required as the first parameter\n"); } $senderAddress = $argv[1]; $rawMessage = file_get_contents('php://stdin'); if ($rawMessage === false) { die("Can't read standard input to get message body\n"); } if (count($rawMessage) < 1) { die("Message body (read from standard input) is empty\n"); } $rawClearedMessage = substr($rawMessage, strpos($rawMessage, "\n") + 1); $message = \Feedbee\Smp\Mail\Message::fromString($rawClearedMessage); return [$message, ['sender_address' => $senderAddress]];