text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Reduce number of entries shown on index
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
Fix lifecycle events to satisfy recommendations
import ClickOutsideMixin from './mixin'; import Component from '@ember/component'; import { next, cancel } from '@ember/runloop'; import $ from 'jquery'; export default Component.extend(ClickOutsideMixin, { clickOutside(e) { if (this.isDestroying || this.isDestroyed) { return; } const exceptSelector = this.get('except-selector'); if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) { return; } let action = this.get('action'); if (typeof action !== 'undefined') { action(e); } }, didInsertElement() { this._super(...arguments); this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener); }, willDestroyElement() { cancel(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); } });
import ClickOutsideMixin from './mixin'; import Component from '@ember/component'; import { on } from '@ember/object/evented'; import { next, cancel } from '@ember/runloop'; import $ from 'jquery'; export default Component.extend(ClickOutsideMixin, { clickOutside(e) { if (this.isDestroying || this.isDestroyed) { return; } const exceptSelector = this.get('except-selector'); if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) { return; } let action = this.get('action'); if (typeof action !== 'undefined') { action(e); } }, _attachClickOutsideHandler: on('didInsertElement', function() { this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener); }), _removeClickOutsideHandler: on('willDestroyElement', function() { cancel(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); }) });
Add TOPLEVEL pos to unify node pos interface
import extlib.vimlparser class Parser(object): def __init__(self, plugins=None): """ Initialize Parser with the specified plugins. The plugins can add attributes to the AST. """ self.plugins = plugins or [] def parse(self, string): """ Parse vim script string and return the AST. """ lines = string.split('\n') reader = extlib.vimlparser.StringReader(lines) parser = extlib.vimlparser.VimLParser() ast = parser.parse(reader) # TOPLEVEL does not have a pos, but we need pos for all nodes ast['pos'] = {'col': 1, 'i': 0, 'lnum': 1} for plugin in self.plugins: plugin.process(ast) return ast def parse_file(self, file_path): """ Parse vim script file and return the AST. """ with file_path.open() as f: return self.parse(f.read())
import extlib.vimlparser class Parser(object): def __init__(self, plugins=None): """ Initialize Parser with the specified plugins. The plugins can add attributes to the AST. """ self.plugins = plugins or [] def parse(self, string): """ Parse vim script string and return the AST. """ lines = string.split('\n') reader = extlib.vimlparser.StringReader(lines) parser = extlib.vimlparser.VimLParser() ast = parser.parse(reader) for plugin in self.plugins: plugin.process(ast) return ast def parse_file(self, file_path): """ Parse vim script file and return the AST. """ with file_path.open() as f: return self.parse(f.read())
Move the notification on the about page below the text so that when the page loads, the text gets loaded first, then the notification content and then Vue renders it as a notification
@extends('layout') @section('content') @component('partials.header') @slot('theme') is-dark @endslot @slot('subtitle') About section @endslot @endcomponent <div class="section"> <div class="container"> <div class="content column is-half is-offset-one-quarter"> {!! $markdown !!} </div> </div> </div> <Notification v-show="showNotifcation" type="info" :timer="false" @close="showNotifcation = false"> This is a render of the current readme file from the <a href="https://github.com/Musmula/Zippy" target="_blank" class="link-invert">Github repo</a>. </Notification> @stop
@extends('layout') @section('content') @component('partials.header') @slot('theme') is-dark @endslot @slot('subtitle') About section @endslot @endcomponent <Notification v-show="showNotifcation" type="info" :timer="false" @close="showNotifcation = false"> This is a render of the current readme file from the <a href="https://github.com/Musmula/Zippy" target="_blank" class="link-invert">Github repo</a>. </Notification> <div class="section"> <div class="container"> <div class="content column is-half is-offset-one-quarter"> {!! $markdown !!} </div> </div> </div> @stop
Sort plg: fix caret pos after 'delete empty lines'
import os from cudatext import * def get_ini_fn(): return os.path.join(app_path(APP_DIR_SETTINGS), 'cuda_sort.ini') def ed_set_text_all(lines): ed.set_text_all('\n'.join(lines)+'\n') def ed_get_text_all(): n = ed.get_line_count() if ed.get_text_line(n-1)=='': n-=1 return [ed.get_text_line(i) for i in range(n)] def ed_insert_to_lines(lines, line1, line2): ed.delete(0, line1, 0, line2+1) ed.insert(0, line1, '\n'.join(lines)+'\n') ed.set_caret(0, line1+len(lines), 0, line1) def ed_set_tab_title(s): ed.set_prop(PROP_TAB_TITLE, s) def ed_convert_tabs_to_spaces(s): return ed.convert(CONVERT_LINE_TABS_TO_SPACES, 0, 0, s) def msg_show_error(s): msg_box(s, MB_OK+MB_ICONERROR) def ed_get_sel_lines(): return ed.get_sel_lines()
import os from cudatext import * def get_ini_fn(): return os.path.join(app_path(APP_DIR_SETTINGS), 'cuda_sort.ini') def ed_set_text_all(lines): ed.set_text_all('\n'.join(lines)+'\n') def ed_get_text_all(): n = ed.get_line_count() if ed.get_text_line(n-1)=='': n-=1 return [ed.get_text_line(i) for i in range(n)] def ed_insert_to_lines(lines, line1, line2): ed.delete(0, line1, 0, line2+1) ed.insert(0, line1, '\n'.join(lines)+'\n') ed.set_caret(0, line2+1, 0, line1) def ed_set_tab_title(s): ed.set_prop(PROP_TAB_TITLE, s) def ed_convert_tabs_to_spaces(s): return ed.convert(CONVERT_LINE_TABS_TO_SPACES, 0, 0, s) def msg_show_error(s): msg_box(s, MB_OK+MB_ICONERROR) def ed_get_sel_lines(): return ed.get_sel_lines()
Remove usage of deprecated Collection
<?php namespace Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** @ODM\Document(collection="DoctrineMongoDBBundle_Tests_Validator_Document") */ class Document { /** @ODM\Id(strategy="none") */ protected $id; /** @ODM\Field(type="string") */ public $name; /** @ODM\Field(type="hash") */ public $hash; /** @ODM\Field(type="collection") */ public $collection; /** @ODM\ReferenceOne(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\Document") */ public $referenceOne; /** @ODM\EmbedOne(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\EmbeddedDocument") */ public $embedOne; /** @ODM\EmbedMany(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\EmbeddedDocument") */ public $embedMany = []; public function __construct($id) { $this->id = $id; } } /** @ODM\EmbeddedDocument */ class EmbeddedDocument { /** @ODM\Field(type="string") */ public $name; }
<?php namespace Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** @ODM\Document(collection="DoctrineMongoDBBundle_Tests_Validator_Document") */ class Document { /** @ODM\Id(strategy="none") */ protected $id; /** @ODM\Field(type="string") */ public $name; /** @ODM\Field(type="hash") */ public $hash; /** @ODM\Collection */ public $collection; /** @ODM\ReferenceOne(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\Document") */ public $referenceOne; /** @ODM\EmbedOne(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\EmbeddedDocument") */ public $embedOne; /** @ODM\EmbedMany(targetDocument="Doctrine\Bundle\MongoDBBundle\Tests\Fixtures\Validator\EmbeddedDocument") */ public $embedMany = []; public function __construct($id) { $this->id = $id; } } /** @ODM\EmbeddedDocument */ class EmbeddedDocument { /** @ODM\Field(type="string") */ public $name; }
Fix new docs ESLint rule violation.
/** * Modules datastore fixtures. * * 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. */ /** * Internal dependencies */ import modules from '../fixtures.json'; // TODO: move into this directory. // Only Search Console and Site Verification are always active. const alwaysActive = [ 'search-console', 'site-verification' ]; /** * Makes a copy of the modules with the given module activation set. * * @since n.e.x.t * * @param {...string} slugs Active module slugs. * @return {Object[]} Array of module objects. */ export const withActive = ( ...slugs ) => { const activeSlugs = alwaysActive.concat( slugs ); return modules.map( ( module ) => { return { ...module, active: activeSlugs.includes( module.slug ) }; } ); }; export default withActive();
/** * Modules datastore fixtures. * * 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. */ /** * Internal dependencies */ import modules from '../fixtures.json'; // TODO: move into this directory. // Only Search Console and Site Verification are always active. const alwaysActive = [ 'search-console', 'site-verification' ]; /** * Makes a copy of the modules with the given module activation set. * * @param {...string} slugs Active module slugs. * @return {Object[]} Array of module objects. */ export const withActive = ( ...slugs ) => { const activeSlugs = alwaysActive.concat( slugs ); return modules.map( ( module ) => { return { ...module, active: activeSlugs.includes( module.slug ) }; } ); }; export default withActive();
Allow mixing the loaded WAV file from stereo to mono.
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1)), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1))): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor return samples, fs
Disable minificiation when preprocessing is enabled
import * as t from 'babel-types' import { useMinify, useCSSPreprocessor } from '../utils/options' import { isStyled, isHelper } from '../utils/detectors' const minify = (linebreak) => { const regex = new RegExp(linebreak + '\\s*', 'g') return (code) => code.split(regex).filter(line => line.length > 0).map((line) => { return line.indexOf('//') === -1 ? line : line + '\n'; }).join('') } const minifyRaw = minify('(?:\\\\r|\\\\n|\\r|\\n)') const minifyCooked = minify('[\\r\\n]') export default (path, state) => { if ( useMinify(state) && !useCSSPreprocessor(state) && ( isStyled(path.node.tag, state) || isHelper(path.node.tag, state) ) ) { const templateLiteral = path.node.quasi for (let element of templateLiteral.quasis) { element.value.raw = minifyRaw(element.value.raw) element.value.cooked = minifyCooked(element.value.cooked) } } }
import * as t from 'babel-types' import { useMinify } from '../utils/options' import { isStyled, isHelper } from '../utils/detectors' const minify = (linebreak) => { const regex = new RegExp(linebreak + '\\s*', 'g') return (code) => code.split(regex).filter(line => line.length > 0).map((line) => { return line.indexOf('//') === -1 ? line : line + '\n'; }).join('') } const minifyRaw = minify('(?:\\\\r|\\\\n|\\r|\\n)') const minifyCooked = minify('[\\r\\n]') export default (path, state) => { if (useMinify(state) && (isStyled(path.node.tag, state) || isHelper(path.node.tag, state))) { const templateLiteral = path.node.quasi for (let element of templateLiteral.quasis) { element.value.raw = minifyRaw(element.value.raw) element.value.cooked = minifyCooked(element.value.cooked) } } }
Add license info (retroactively applied to all commits).
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='tempora', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="tempora", long_description=long_description, url="https://bitbucket.org/jaraco/tempora", py_modules=['tempora'], license='MIT', entry_points={ 'console_scripts': [ 'calc-prorate = tempora:calculate_prorated_values', ], }, setup_requires=[ 'hgtools', 'pytest-runner', 'sphinx', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='tempora', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="tempora", long_description=long_description, url="https://bitbucket.org/jaraco/tempora", py_modules=['tempora'], entry_points={ 'console_scripts': [ 'calc-prorate = tempora:calculate_prorated_values', ], }, setup_requires=[ 'hgtools', 'pytest-runner', 'sphinx', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
Remove dependency on default parameters in JS Apparently it's only supported by Firefox, source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/default_parameters This issue was brought up in #3.
'use strict'; app.factory('Product', function($http) { function getUrl(id) { id = typeof id !== 'undefined' ? id : ''; return 'http://127.0.0.1:8000/api/products/' + id + '?format=json'; } return { get: function(id, callback) { return $http.get(getUrl(id)).success(callback); }, query: function(page, page_size, callback) { return $http.get(getUrl() + '&page_size=' + page_size + '&page=' + page).success(callback); }, save: function(product, callback) { return $http.post(getUrl(), product).success(callback); }, remove: function(id, callback) { return $http.delete(getUrl(id)).success(callback); }, put: function(product, callback) { return $http.put(getUrl(product.id), product).success(callback); } }; });
'use strict'; app.factory('Product', function($http) { function getUrl(id = '') { return 'http://127.0.0.1:8000/api/products/' + id + '?format=json'; } return { get: function(id, callback) { return $http.get(getUrl(id)).success(callback); }, query: function(page, page_size, callback) { return $http.get(getUrl() + '&page_size=' + page_size + '&page=' + page).success(callback); }, save: function(product, callback) { return $http.post(getUrl(), product).success(callback); }, remove: function(id, callback) { return $http.delete(getUrl(id)).success(callback); }, put: function(product, callback) { return $http.put(getUrl(product.id), product).success(callback); } }; });
Make Webpack logs a bit less verbose.
/* * `server` task * ============= * * Creates a Browsersync Web server instance for live development. Makes use of * some Webpack middlewares to enable live reloading features. */ import browsersync from 'browser-sync'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import config from '../config/browsersync'; import webpack from '../lib/webpack'; const server = browsersync.create(); const serve = () => { const compiler = webpack('development'); config.middleware = [ webpackDevMiddleware(compiler, { quiet: true, stats: { colors: true, modules: false } }), webpackHotMiddleware(compiler, { log: () => {} }) ]; server.init(config); }; serve.description = `Create a Browsersync instance for live development.`; export default serve;
/* * `server` task * ============= * * Creates a Browsersync Web server instance for live development. Makes use of * some Webpack middlewares to enable live reloading features. */ import browsersync from 'browser-sync'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import config from '../config/browsersync'; import webpack from '../lib/webpack'; const server = browsersync.create(); const serve = () => { const compiler = webpack('development'); config.middleware = [ webpackDevMiddleware(compiler, { quiet: true, stats: { colors: true } }), webpackHotMiddleware(compiler, { log: () => {} }) ]; server.init(config); }; serve.description = `Create a Browsersync instance for live development.`; export default serve;
Change the default kns table
package org.aksw.kbox.kibe; import java.net.MalformedURLException; import java.net.URL; import org.aksw.kbox.kns.CustomKNSServerList; import org.aksw.kbox.kns.KNSServerListVisitor; public class DefaultKNSServerList extends URLKNSServerList { // Default KNS table URL private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/AKSW/KBox/master/kns/2.0/"; private CustomKNSServerList customKNSServerList = new CustomKNSServerList(); public DefaultKNSServerList() throws MalformedURLException { super(new URL(DEFAULT_KNS_TABLE_URL)); } @Override public boolean visit(KNSServerListVisitor visitor) throws Exception { boolean next = super.visit(visitor); if(next) { next = customKNSServerList.visit(visitor); } return next; } }
package org.aksw.kbox.kibe; import java.net.MalformedURLException; import java.net.URL; import org.aksw.kbox.kns.CustomKNSServerList; import org.aksw.kbox.kns.KNSServerListVisitor; public class DefaultKNSServerList extends URLKNSServerList { // Default KNS table URL private final static String DEFAULT_KNS_TABLE_URL = "https://raw.github.com/AKSW/kbox/master"; private CustomKNSServerList customKNSServerList = new CustomKNSServerList(); public DefaultKNSServerList() throws MalformedURLException { super(new URL(DEFAULT_KNS_TABLE_URL)); } @Override public boolean visit(KNSServerListVisitor visitor) throws Exception { boolean next = super.visit(visitor); if(next) { next = customKNSServerList.visit(visitor); } return next; } }
Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
Update selector for removing li Also remove console.log
$('#title').addClass('redtitle'); var json = { "room":{ "name":"FangDev", "members":"Salgat:1452401384430,Fangfang2:1452401457085", "messages":[ "Salgat: I love you more xiaobei", "Fangfang: I love you Laobei" ] } }; function removeMessages(){ $('#messages').find('li').remove(); } function showMessages(messages){ var arrayLength = messages.length; for (var i = 0; i < arrayLength; i++) { $('#messages').find('ul').append('<li>' + messages[i] + '</li>'); } } window.setInterval(function(){ $.post( "http://singleendpointchatserver.herokuapp.com/api/v1/chatroom/FangDev?username=Fangfang&expireafter=60", function( json ) { var messages = json.room.messages; removeMessages(); showMessages(messages); }); }, 1000); $('#messageSubmit').on('click', function(event) { var message = $('#messageInput').val(); $('#messageInput').val(''); var encodedMessage = encodeURIComponent(message); $.post( "http://singleendpointchatserver.herokuapp.com/api/v1/chatroom/FangDev?username=Fangfang&message="+encodedMessage+"&expireafter=60"); });
$('#title').addClass('redtitle'); var json = { "room":{ "name":"FangDev", "members":"Salgat:1452401384430,Fangfang2:1452401457085", "messages":[ "Salgat: I love you more xiaobei", "Fangfang: I love you Laobei" ] } }; function removeMessages(){ $('li').remove(); } function showMessages(messages){ var arrayLength = messages.length; for (var i = 0; i < arrayLength; i++) { $('#messages').find('ul').append('<li>' + messages[i] + '</li>'); } } window.setInterval(function(){ $.post( "http://singleendpointchatserver.herokuapp.com/api/v1/chatroom/FangDev?username=Fangfang&expireafter=60", function( json ) { var messages = json.room.messages; removeMessages(); showMessages(messages); }); }, 1000); $('#messageSubmit').on('click', function(event) { var message = $('#messageInput').val(); $('#messageInput').val(''); console.log("Button pressed with value: " + message); var encodedMessage = encodeURIComponent(message); $.post( "http://singleendpointchatserver.herokuapp.com/api/v1/chatroom/FangDev?username=Fangfang&message="+encodedMessage+"&expireafter=60"); });
Use color suggested by @xavijam
module.exports = { COLORS: [ '#F24440', '#11A579', '#3969AC', '#E73F74', '#80BA5A', '#E68310', '#008695', '#CF1C90', '#f97b72', '#A5AA99' ], /** * Returns a color given a letter * @param {String} Letter. eg: 'a', 'b', 'c', etc. * @return {String} Hex color code: eg: '#7F3C8D' */ getColorForLetter: function (letter) { if (!letter) { return this.COLORS[0]; } var letterNumber = letter.charCodeAt(0) - 97; var colorIndex = ((letterNumber / this.COLORS.length % 1) * 10).toFixed(); return this.COLORS[colorIndex] || this.COLORS[0]; } };
module.exports = { COLORS: [ '#7F3C8D', '#11A579', '#3969AC', '#E73F74', '#80BA5A', '#E68310', '#008695', '#CF1C90', '#f97b72', '#A5AA99' ], /** * Returns a color given a letter * @param {String} Letter. eg: 'a', 'b', 'c', etc. * @return {String} Hex color code: eg: '#7F3C8D' */ getColorForLetter: function (letter) { if (!letter) { return this.COLORS[0]; } var letterNumber = letter.charCodeAt(0) - 97; var colorIndex = ((letterNumber / this.COLORS.length % 1) * 10).toFixed(); return this.COLORS[colorIndex] || this.COLORS[0]; } };
Change default logging level to INFO+
<?php include('../src/common.php'); use Monolog\Logger; use Monolog\Handler\StreamHandler; use unreal4u\Telegram\Types\Update; use unreal4u\Telegram\Types\InlineQueryResultArticle; use unreal4u\Telegram\Methods\AnswerInlineQuery; use unreal4u\TgLog; $parsedRequestUri = trim($_SERVER['REQUEST_URI'], '/'); if (array_key_exists($parsedRequestUri, BOT_TOKENS)) { $currentBot = BOT_TOKENS[$parsedRequestUri]; $logger = new Logger($currentBot); $streamHandler = new StreamHandler('telegramApiLogs/main.log'); $streamHandler->setLevel(Logger::INFO); $logger->pushHandler($streamHandler); $logger->addDebug('--------------------------------'); $logger->addInfo(sprintf('New request on bot %s', $currentBot)); $rest_json = file_get_contents("php://input"); $_POST = json_decode($rest_json, true); try { $completeName = 'unreal4u\\Bots\\' . $currentBot; $bot = new $completeName($logger, $parsedRequestUri); $bot->run($_POST); } catch (\Exception $e) { $logger->addError(sprintf('Captured exception: "%s"', $e->getMessage())); } } else { header('Location: https://github.com/unreal4u?tab=repositories', true, 302); }
<?php include('../src/common.php'); use Monolog\Logger; use Monolog\Handler\StreamHandler; use unreal4u\Telegram\Types\Update; use unreal4u\Telegram\Types\InlineQueryResultArticle; use unreal4u\Telegram\Methods\AnswerInlineQuery; use unreal4u\TgLog; $parsedRequestUri = trim($_SERVER['REQUEST_URI'], '/'); if (array_key_exists($parsedRequestUri, BOT_TOKENS)) { $currentBot = BOT_TOKENS[$parsedRequestUri]; $logger = new Logger($currentBot); $logger->pushHandler(new StreamHandler('telegramApiLogs/main.log')); $logger->addDebug('--------------------------------'); $logger->addInfo(sprintf('New request on bot %s', $currentBot)); $rest_json = file_get_contents("php://input"); $_POST = json_decode($rest_json, true); try { $completeName = 'unreal4u\\Bots\\' . $currentBot; $bot = new $completeName($logger, $parsedRequestUri); $bot->run($_POST); } catch (\Exception $e) { $logger->addError(sprintf('Captured exception: "%s"', $e->getMessage())); } } else { header('Location: https://github.com/unreal4u?tab=repositories', true, 302); }
Use build-in method to get user homedir instead of eval on sh
// +build !windows package main import ( "errors" "os" "os/user" "path/filepath" ) func configFile() (string, error) { dir, err := homeDir() if err != nil { return "", err } return filepath.Join(dir, ".terraformrc"), nil } func configDir() (string, error) { dir, err := homeDir() if err != nil { return "", err } return filepath.Join(dir, ".terraform.d"), nil } func homeDir() (string, error) { // First prefer the HOME environmental variable if home := os.Getenv("HOME"); home != "" { // FIXME: homeDir gets called from globalPluginDirs during init, before // the logging is setup. We should move meta initializtion outside of // init, but in the meantime we just need to silence this output. //log.Printf("[DEBUG] Detected home directory from env var: %s", home) return home, nil } // If that fails, try build-in module user, err := user.Current() if err != nil { return "", err } if user.HomeDir == "" { return "", errors.New("blank output") } return user.HomeDir, nil }
// +build !windows package main import ( "bytes" "errors" "os" "os/exec" "path/filepath" "strings" ) func configFile() (string, error) { dir, err := homeDir() if err != nil { return "", err } return filepath.Join(dir, ".terraformrc"), nil } func configDir() (string, error) { dir, err := homeDir() if err != nil { return "", err } return filepath.Join(dir, ".terraform.d"), nil } func homeDir() (string, error) { // First prefer the HOME environmental variable if home := os.Getenv("HOME"); home != "" { // FIXME: homeDir gets called from globalPluginDirs during init, before // the logging is setup. We should move meta initializtion outside of // init, but in the meantime we just need to silence this output. //log.Printf("[DEBUG] Detected home directory from env var: %s", home) return home, nil } // If that fails, try the shell var stdout bytes.Buffer cmd := exec.Command("sh", "-c", "eval echo ~$USER") cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return "", err } result := strings.TrimSpace(stdout.String()) if result == "" { return "", errors.New("blank output") } return result, nil }
Add prop to disable submit
import React, {PropTypes, Component} from 'react'; import {View} from 'react-native'; export default class Form extends Component { _listeners = []; static PropTypes = { onSuccess: PropTypes.func, onFail: PropTypes.func, submitButton: PropTypes.element.isRequired } static childContextTypes = { addFormListener: PropTypes.func, removeFormListener: PropTypes.func } getChildContext() { return { addFormListener: this.addFormListener.bind(this), removeFormListener: this.removeFormListener.bind(this) } } addFormListener(ln) { this._listeners.push(ln); } removeFormListener(ln) { this._listeners = this._listeners.filter(l => l !== ln); } onSubmit() { const defaultFn = () => {}; const {onFail = defaultFn, onSuccess = defaultFn} = this.props; const stop = this._listeners.reduce((stop, _listener) => { return _listener() || stop; }, false); if (stop) { return onFail(); }; onSuccess(); } render() { const {submitButton, children, style, disableSubmit} = this.props; return ( <View style={style}> {children} {submitButton(this.onSubmit.bind(this), disableSubmit)} </View> ) } }
import React, {PropTypes, Component} from 'react'; import {View} from 'react-native'; export default class Form extends Component { _listeners = []; static PropTypes = { onSuccess: PropTypes.func, onFail: PropTypes.func, submitButton: PropTypes.element.isRequired } static childContextTypes = { addFormListener: PropTypes.func, removeFormListener: PropTypes.func } getChildContext() { return { addFormListener: this.addFormListener.bind(this), removeFormListener: this.removeFormListener.bind(this) } } addFormListener(ln) { this._listeners.push(ln); } removeFormListener(ln) { this._listeners = this._listeners.filter(l => l !== ln); } onSubmit() { const defaultFn = () => {}; const {onFail = defaultFn, onSuccess = defaultFn} = this.props; const stop = this._listeners.reduce((stop, _listener) => { return _listener() || stop; }, false); if (stop) { return onFail(); }; onSuccess(); } render() { const {submitButton, children, style} = this.props; return ( <View style={style}> {children} {submitButton(this.onSubmit.bind(this))} </View> ) } }
Set user.email_address.verified as true when user changed his password
from django.contrib.sessions.models import Session from django.dispatch import receiver from django.utils.translation import ugettext as _ from account.models import EmailAddress from account.signals import email_confirmation_sent, password_changed, user_signed_up from board.models import Board, Notification from board.utils import treedict @receiver(email_confirmation_sent) def email_confirmation_sent_callback(sender, confirmation, **kwargs): user = confirmation.email_address.user # Logout user [s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id] @receiver(user_signed_up) def user_signed_up_callback(sender, user, form, **kwargs): user.is_active = True user.save() data = treedict() data['type'] = 'SITE_ANNOUNCEMENT' data['message'] = _('New site announcement') data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.') data['url'] = Board.objects.get(slug='notice').get_absolute_url() Notification.create(None, user, data) @receiver(password_changed) def password_changed_callback(sender, user, **kwargs): email = EmailAddress.objects.get_primary(user) if not email.verified: email.verified = True email.save()
from django.contrib.sessions.models import Session from django.dispatch import receiver from django.utils.translation import ugettext as _ from account.signals import email_confirmation_sent, user_signed_up from board.models import Board, Notification from board.utils import treedict @receiver(email_confirmation_sent) def email_confirmation_sent_callback(sender, confirmation, **kwargs): user = confirmation.email_address.user # Logout user [s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id] @receiver(user_signed_up) def user_signed_up_callback(sender, user, form, **kwargs): user.is_active = True user.save() data = treedict() data['type'] = 'SITE_ANNOUNCEMENT' data['message'] = _('New site announcement') data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.') data['url'] = Board.objects.get(slug='notice').get_absolute_url() Notification.create(None, user, data)
Fix extracted star coordinates from 1- to 0-based indexing Note that center of first pixel is 0, ie. edge of first pixel is -0.5
# -*- coding: utf-8 -*- """ Created on Mon Dec 25 15:19:55 2017 @author: vostok """ import os import tempfile from astropy.io import fits def extract_stars(input_array): (infilehandle, infilepath) = tempfile.mkstemp(suffix='.fits') os.close(infilehandle) fits.writeto(infilepath, \ input_array.astype('float32'), \ fits.Header(), \ overwrite=True) return_code = os.system('image2xy -O {}'.format(infilepath)) if return_code != 0: raise "image2xy returned with error code %d" % return_code result = fits.open(infilepath.replace('.fits', '.xy.fits'))[1].data os.unlink(infilepath) result['X'] -= 1 result['Y'] -= 1 return result
# -*- coding: utf-8 -*- """ Created on Mon Dec 25 15:19:55 2017 @author: vostok """ import os import tempfile from astropy.io import fits def extract_stars(input_array): (infilehandle, infilepath) = tempfile.mkstemp(suffix='.fits') os.close(infilehandle) fits.writeto(infilepath, \ input_array.astype('float32'), \ fits.Header(), \ overwrite=True) return_code = os.system('image2xy -O {}'.format(infilepath)) if return_code != 0: raise "image2xy returned with error code %d" % return_code result = fits.open(infilepath.replace('.fits', '.xy.fits'))[1].data os.unlink(infilepath) return result
Remove dependency on six for simplekv.
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='simplekv', version='0.9.4.dev1', description=('A key-value storage for binary data, support many ' 'backends.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/simplekv', license='MIT', packages=find_packages(exclude=['test']), install_requires=[], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='simplekv', version='0.9.4.dev1', description=('A key-value storage for binary data, support many ' 'backends.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/simplekv', license='MIT', packages=find_packages(exclude=['test']), install_requires=['six'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Adjust test outcome to new nub source numbers
package org.gbif.checklistbank.nub.source; import org.gbif.api.vocabulary.Rank; import org.gbif.checklistbank.nub.model.SrcUsage; import java.util.List; import java.util.UUID; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ClasspathUsageSourceTest { /** * integration test with prod registry * @throws Exception */ @Test public void testListSources() throws Exception { ClasspathUsageSource src = ClasspathUsageSource.allSources(); List<NubSource> sources = src.listSources(); assertEquals(8, sources.size()); assertEquals(1, sources.get(0).priority); assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove); } @Test public void testIterateSource() throws Exception { ClasspathUsageSource src = ClasspathUsageSource.emptySource(); NubSource fungi = new NubSource(); fungi.name = "squirrels"; fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01"); fungi.ignoreRanksAbove = Rank.SPECIES; int counter = 0; for (SrcUsage u : src.iterateSource(fungi)) { counter++; System.out.print(u.key + " "); System.out.println(u.scientificName); } assertEquals(9, counter); } }
package org.gbif.checklistbank.nub.source; import org.gbif.api.vocabulary.Rank; import org.gbif.checklistbank.nub.model.SrcUsage; import java.util.List; import java.util.UUID; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ClasspathUsageSourceTest { /** * integration test with prod registry * @throws Exception */ @Test public void testListSources() throws Exception { ClasspathUsageSource src = ClasspathUsageSource.allSources(); List<NubSource> sources = src.listSources(); assertEquals(3, sources.size()); assertEquals(1, sources.get(0).priority); assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove); } @Test public void testIterateSource() throws Exception { ClasspathUsageSource src = ClasspathUsageSource.emptySource(); NubSource fungi = new NubSource(); fungi.name = "squirrels"; fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01"); fungi.ignoreRanksAbove = Rank.SPECIES; int counter = 0; for (SrcUsage u : src.iterateSource(fungi)) { counter++; System.out.print(u.key + " "); System.out.println(u.scientificName); } assertEquals(9, counter); } }
Make context name for a filter form configurable
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): qs = super(FilterFormMixin, self).get_queryset() qs = self.get_filter().filter(qs).distinct() return qs def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): return {'user': self.request.user}
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False def get_filter(self): return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): qs = super(FilterFormMixin, self).get_queryset() qs = self.get_filter().filter(qs).distinct() return qs def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) context['filterform'] = self.get_filter() return context def get_runtime_context(self): return {'user': self.request.user}
Allow newer versions of chardet
from setuptools import setup from distutils.core import Command import os import sys import codecs class TestCommand(Command): description = "Run tests" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s']) raise SystemExit(errno) setup( name='mafan', version='0.3.1', author='Herman Schaaf', author_email='herman@ironzebra.com', packages=[ 'mafan', 'mafan.hanzidentifier', 'mafan.third_party', 'mafan.third_party.jianfan' ], scripts=['bin/convert.py'], url='https://github.com/hermanschaaf/mafan', license='LICENSE.txt', description='A toolbox for working with the Chinese language in Python', long_description=codecs.open('docs/README.md', 'r', 'utf-8').read(), cmdclass={ 'test': TestCommand, }, install_requires=[ "jieba == 0.37", "argparse == 1.1", "chardet >= 2.1.1", "future", ], )
from setuptools import setup from distutils.core import Command import os import sys import codecs class TestCommand(Command): description = "Run tests" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s']) raise SystemExit(errno) setup( name='mafan', version='0.3.1', author='Herman Schaaf', author_email='herman@ironzebra.com', packages=[ 'mafan', 'mafan.hanzidentifier', 'mafan.third_party', 'mafan.third_party.jianfan' ], scripts=['bin/convert.py'], url='https://github.com/hermanschaaf/mafan', license='LICENSE.txt', description='A toolbox for working with the Chinese language in Python', long_description=codecs.open('docs/README.md', 'r', 'utf-8').read(), cmdclass={ 'test': TestCommand, }, install_requires=[ "jieba == 0.37", "argparse == 1.1", "chardet == 2.1.1", "future", ], )
Fix text color for account disabled page
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @extends('master') @section('content') <div class="osu-page osu-page--generic"> @include(i18n_view('users._disabled_message')) </div> @endsection
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @extends('master') @section('content') <div class="osu-layout__row osu-layout__row--page"> @include(i18n_view('users._disabled_message')) </div> @endsection
Fix for periodic task scheduler (3)
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
Handle also .pm and .pl file types
"use babel"; fs = require('fs-plus') /** * This class provides the file-icons service API implemented by tree-view * Please see https://github.com/atom/tree-view#api */ module.exports = class Perl6FileIconsProvider { iconClassForPath(filePath) { extension = path.extname(filePath) if (fs.isSymbolicLinkSync(filePath)) { return 'icon-file-symlink-file' } else if (fs.isReadmePath(filePath)) { return 'icon-book' } else if (fs.isCompressedExtension(extension)) { return 'icon-file-zip' } else if (fs.isImageExtension(extension)) { return 'icon-file-media' } else if (fs.isPdfExtension(extension)) { return 'icon-file-pdf' } else if (fs.isBinaryExtension(extension)) { return 'icon-file-binary' } else if (extension == ".pm6" || extension == ".pm" || extension == ".pl6" || extension == ".p6" || extension == ".pl" || extension == ".t") { return 'icon-file-perl6' } else { return 'icon-file-text' } } onWillDeactivate(fn) { return } }
"use babel"; fs = require('fs-plus') /** * This class provides the file-icons service API implemented by tree-view * Please see https://github.com/atom/tree-view#api */ module.exports = class Perl6FileIconsProvider { iconClassForPath(filePath) { extension = path.extname(filePath) if (fs.isSymbolicLinkSync(filePath)) { return 'icon-file-symlink-file' } else if (fs.isReadmePath(filePath)) { return 'icon-book' } else if (fs.isCompressedExtension(extension)) { return 'icon-file-zip' } else if (fs.isImageExtension(extension)) { return 'icon-file-media' } else if (fs.isPdfExtension(extension)) { return 'icon-file-pdf' } else if (fs.isBinaryExtension(extension)) { return 'icon-file-binary' } else if (extension == ".pm6" || extension == ".pl6" || extension == ".p6" || extension == ".t") { return 'icon-file-perl6' } else { return 'icon-file-text' } } onWillDeactivate(fn) { return } }
Remove no longer needed comments
'use strict'; var _ = require('lodash'); var glimpse = require('glimpse'); var processMessages = function(messages) { return { messages: messages, groupedById: _.groupBy(messages, 'context.id') }; }; // republish Found Summary (function () { function republishFoundSummary(messages) { var payload = processMessages(messages); glimpse.emit('data.message.summary.found', payload); } glimpse.on('data.message.summary.found.stream', republishFoundSummary); glimpse.on('data.message.summary.found.remote', republishFoundSummary); })(); // republish Found Details (function () { function republishFoundDetail(messages) { var payload = processMessages(messages); glimpse.emit('data.message.detail.found', payload); } glimpse.on('data.message.detail.found.stream', republishFoundDetail); glimpse.on('data.message.detail.found.remote', republishFoundDetail); })();
'use strict'; var _ = require('lodash'); var glimpse = require('glimpse'); var processMessages = function(messages) { return { messages: messages, groupedById: _.groupBy(messages, 'context.id') }; }; // republish Found Summary (function () { function republishFoundSummary(messages) { var payload = processMessages(messages); glimpse.emit('data.message.summary.found', payload); } glimpse.on('data.message.summary.found.stream', republishFoundSummary); glimpse.on('data.message.summary.found.remote', republishFoundSummary); //TODO: not yet implemented })(); // republish Found Details (function () { function republishFoundDetail(messages) { var payload = processMessages(messages); glimpse.emit('data.message.detail.found', payload); } glimpse.on('data.message.detail.found.stream', republishFoundDetail); glimpse.on('data.message.detail.found.remote', republishFoundDetail); //TODO: not yet implemented })();
WebApp-4b: Sort tasks by createdAt timestamp
// simple-todos.js // TODO: Add tasks from console to populate collection // On Server: // db.tasks.insert({ text: "Hello world!", createdAt: new Date() }); // On Client: // Tasks.insert({ text: "Hello world!", createdAt: new Date() }); Tasks = new Mongo.Collection("tasks"); if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: function () { // Show newest tasks first return Tasks.find({}, {sort: {createdAt: -1}}); } }); // Inside the if (Meteor.isClient) block, right after Template.body.helpers: Template.body.events({ "submit .new-task": function (event) { // This function is called when the new task form is submitted var text = event.target.text.value; Tasks.insert({ text: text, createdAt: new Date() // current time }); // Clear form event.target.text.value = ""; // Prevent default form submit return false; } }); }
// simple-todos.js // TODO: Add tasks from console to populate collection // On Server: // db.tasks.insert({ text: "Hello world!", createdAt: new Date() }); // On Client: // Tasks.insert({ text: "Hello world!", createdAt: new Date() }); Tasks = new Mongo.Collection("tasks"); if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: function () { return Tasks.find({}); } }); // Inside the if (Meteor.isClient) block, right after Template.body.helpers: Template.body.events({ "submit .new-task": function (event) { // This function is called when the new task form is submitted var text = event.target.text.value; Tasks.insert({ text: text, createdAt: new Date() // current time }); // Clear form event.target.text.value = ""; // Prevent default form submit return false; } }); }
Update /admin/debug/clear with new logging semantics
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS 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. 'use strict'; module.exports = function createDebugClearHandler(ringpop) { return function handleDebugClear(arg1, arg2, hostInfo, callback) { ringpop.config.set('gossipLogLevel', 'off'); callback(null, null, 'ok'); }; };
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS 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. 'use strict'; module.exports = function createDebugClearHandler(ringpop) { return function handleDebugClear(arg1, arg2, hostInfo, callback) { ringpop.config.set('gossipLogLevel', 'debug'); callback(null, null, 'ok'); }; };
Use the DefaultScheduler if none is assigned Fixes #1
let scheduler = null export function setScheduler (customScheduler) { scheduler = customScheduler } export function getScheduler () { if (!scheduler) { scheduler = new DefaultScheduler() } return scheduler } class DefaultScheduler { constructor () { this.updateRequests = [] this.frameRequested = false this.performUpdates = this.performUpdates.bind(this) } updateDocument (fn) { this.updateRequests.push(fn) if (!this.frameRequested) { this.frameRequested = true window.requestAnimationFrame(this.performUpdates) } } performUpdates () { this.frameRequested = false while (this.updateRequests.length > 0) { this.updateRequests.shift()() } } }
let scheduler = null export function setScheduler (customScheduler) { if (customScheduler) { scheduler = customScheduler } else { scheduler = new DefaultScheduler() } } export function getScheduler () { return scheduler } class DefaultScheduler { constructor () { this.updateRequests = [] this.frameRequested = false this.performUpdates = this.performUpdates.bind(this) } updateDocument (fn) { this.updateRequests.push(fn) if (!this.frameRequested) { this.frameRequested = true window.requestAnimationFrame(this.performUpdates) } } performUpdates () { this.frameRequested = false while (this.updateRequests.length > 0) { this.updateRequests.shift()() } } }
Use HTTPS in homepage URL
import sys, os from setuptools import setup, find_packages import subprocess version = "0.3.3" base_reqs = [ "requests" ] setup( name="waybackpack", description="Command-line tool that lets you download the entire Wayback Machine archive for a given URL.", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.4" ], keywords="wayback machine archive", author="Jeremy Singer-Vine", author_email="jsvine@gmail.com", url="https://github.com/jsvine/waybackpack", license="MIT", version=version, packages=find_packages(exclude=["test",]), tests_require=[ "nose" ] + base_reqs, install_requires=base_reqs, entry_points={ "console_scripts": [ "waybackpack = waybackpack.cli:main" ] } )
import sys, os from setuptools import setup, find_packages import subprocess version = "0.3.3" base_reqs = [ "requests" ] setup( name="waybackpack", description="Command-line tool that lets you download the entire Wayback Machine archive for a given URL.", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.4" ], keywords="wayback machine archive", author="Jeremy Singer-Vine", author_email="jsvine@gmail.com", url="http://github.com/jsvine/waybackpack", license="MIT", version=version, packages=find_packages(exclude=["test",]), tests_require=[ "nose" ] + base_reqs, install_requires=base_reqs, entry_points={ "console_scripts": [ "waybackpack = waybackpack.cli:main" ] } )
Update ps test: add All option
package dockercommand import ( "testing" "github.com/stretchr/testify/assert" ) func TestShortDockerPs(t *testing.T) { docker, err := NewDockerForTest() if err != nil { t.Fatalf("err: %s", err) } containers, err := docker.Ps(&PsOptions{All: true}) if err != nil { t.Fatalf("err: %s", err) } assert.NotEmpty(t, containers) assert.Len(t, containers, 2) assert.Equal(t, containers[0].ID, "8dfafdbc3a40") assert.Equal(t, containers[1].ID, "0236fd017853") } func TestLongDockerPs(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } docker, err := NewDocker("") if err != nil { t.Fatalf("err: %s", err) } _, err = docker.Run(&RunOptions{ Image: "ubuntu", Cmd: []string{"ls", "/"}, }) if err != nil { t.Fatalf("err: %s", err) } containers, err := docker.Ps(&PsOptions{}) if err != nil { t.Fatalf("err: %s", err) } assert.NotEmpty(t, containers) }
package dockercommand import ( "testing" "github.com/stretchr/testify/assert" ) func TestShortDockerPs(t *testing.T) { docker, err := NewDockerForTest() if err != nil { t.Fatalf("err: %s", err) } containers, err := docker.Ps(&PsOptions{}) if err != nil { t.Fatalf("err: %s", err) } assert.NotEmpty(t, containers) assert.Len(t, containers, 2) assert.Equal(t, containers[0].ID, "8dfafdbc3a40") assert.Equal(t, containers[1].ID, "0236fd017853") } func TestLongDockerPs(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } docker, err := NewDocker("") if err != nil { t.Fatalf("err: %s", err) } _, err = docker.Run(&RunOptions{ Image: "ubuntu", Cmd: []string{"ls", "/"}, }) if err != nil { t.Fatalf("err: %s", err) } containers, err := docker.Ps(&PsOptions{}) if err != nil { t.Fatalf("err: %s", err) } assert.NotEmpty(t, containers) }
Update Dockstore link to release 0.0.6.
'use strict'; /** * @ngdoc service * @name dockstore.ui.WebService * @description * # WebService * Constant in the dockstore.ui. */ angular.module('dockstore.ui') .constant('WebService', { API_URI: 'http://localhost:8080', API_URI_DEBUG: 'http://localhost:9000/tests/dummy-data', GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize', GITHUB_CLIENT_ID: 'a70739297a7d67f915de', GITHUB_REDIRECT_URI: 'http://localhost:9000/%23/login', GITHUB_SCOPE: 'read:org', QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize', QUAYIO_CLIENT_ID: 'RWCBI3Y6QUNXDPYKNLMC', QUAYIO_REDIRECT_URI: 'http://localhost:9000/%23/onboarding', QUAYIO_SCOPE: 'repo:read,user:read', DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/' + 'releases/download/0.0.6/dockstore' });
'use strict'; /** * @ngdoc service * @name dockstore.ui.WebService * @description * # WebService * Constant in the dockstore.ui. */ angular.module('dockstore.ui') .constant('WebService', { API_URI: 'http://localhost:8080', API_URI_DEBUG: 'http://localhost:9000/tests/dummy-data', GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize', GITHUB_CLIENT_ID: 'a70739297a7d67f915de', GITHUB_REDIRECT_URI: 'http://localhost:9000/%23/login', GITHUB_SCOPE: 'read:org', QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize', QUAYIO_CLIENT_ID: 'RWCBI3Y6QUNXDPYKNLMC', QUAYIO_REDIRECT_URI: 'http://localhost:9000/%23/onboarding', QUAYIO_SCOPE: 'repo:read,user:read', DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/' + 'releases/download/0.0.4/dockstore' });
Migrate usage of the TokenGrant in the sample
package de.rheinfabrik.heimdalldroid.network.oauth2; import de.rheinfabrik.heimdall2.OAuth2AccessToken; import de.rheinfabrik.heimdall2.grants.OAuth2RefreshAccessTokenGrant; import de.rheinfabrik.heimdalldroid.network.TraktTvApiFactory; import de.rheinfabrik.heimdalldroid.network.models.RefreshTokenRequestBody; import io.reactivex.Single; /** * TraktTv refresh token grant as described in http://docs.trakt.apiary.io/#reference/authentication-oauth/token/exchange-refresh_token-for-access_token. */ public class TraktTvRefreshAccessTokenGrant extends OAuth2RefreshAccessTokenGrant<OAuth2AccessToken> { // Properties public String clientSecret; public String clientId; public String redirectUri; // OAuth2RefreshAccessTokenGrant @Override public Single<OAuth2AccessToken> grantNewAccessToken() { RefreshTokenRequestBody body = new RefreshTokenRequestBody(getRefreshToken(), clientId, clientSecret, redirectUri, getGRANT_TYPE()); return TraktTvApiFactory.newApiService().refreshAccessToken(body).singleOrError(); } }
package de.rheinfabrik.heimdalldroid.network.oauth2; import de.rheinfabrik.heimdall2.OAuth2AccessToken; import de.rheinfabrik.heimdall2.grants.OAuth2RefreshAccessTokenGrant; import de.rheinfabrik.heimdalldroid.network.TraktTvApiFactory; import de.rheinfabrik.heimdalldroid.network.models.RefreshTokenRequestBody; import io.reactivex.Single; /** * TraktTv refresh token grant as described in http://docs.trakt.apiary.io/#reference/authentication-oauth/token/exchange-refresh_token-for-access_token. */ public class TraktTvRefreshAccessTokenGrant extends OAuth2RefreshAccessTokenGrant<OAuth2AccessToken> { // Properties public String clientSecret; public String clientId; public String redirectUri; // OAuth2RefreshAccessTokenGrant @Override public Single<OAuth2AccessToken> grantNewAccessToken() { RefreshTokenRequestBody body = new RefreshTokenRequestBody(refreshToken, clientId, clientSecret, redirectUri, GRANT_TYPE); return TraktTvApiFactory.newApiService().refreshAccessToken(body).singleOrError(); } }
Bump new dev version to 0.3.0
import os __version__ = (0, 3, 0, 'alpha', 1) def get_fancypages_paths(path): """ Get absolute paths for *path* relative to the project root """ return [os.path.join(os.path.dirname(os.path.abspath(__file__)), path)] def get_required_apps(): return [ 'django_extensions', # used for image thumbnailing 'sorl.thumbnail', # framework used for the internal API 'rest_framework', # provides a convenience layer around model inheritance # that makes lookup of nested models easier. This is used # for the content block hierarchy. 'model_utils', # static file compression and collection 'compressor', # migration handling 'south', # package used for twitter block 'twitter_tag', ] def get_fancypages_apps(): return [ 'fancypages.assets', 'fancypages', ]
import os __version__ = (0, 1, 1, 'alpha', 1) def get_fancypages_paths(path): """ Get absolute paths for *path* relative to the project root """ return [os.path.join(os.path.dirname(os.path.abspath(__file__)), path)] def get_required_apps(): return [ 'django_extensions', # used for image thumbnailing 'sorl.thumbnail', # framework used for the internal API 'rest_framework', # provides a convenience layer around model inheritance # that makes lookup of nested models easier. This is used # for the content block hierarchy. 'model_utils', # static file compression and collection 'compressor', # migration handling 'south', # package used for twitter block 'twitter_tag', ] def get_fancypages_apps(): return [ 'fancypages.assets', 'fancypages', ]
Make deps an explicit dependency
Package.describe({ summary: 'Display the connection status with the server' }) Package.on_use(function(api, where) { api.use([ 'meteor', 'deps', 'underscore', 'templating' ], 'client') api.use(['tap-i18n'], ['client', 'server']) api.add_files('package-tap.i18n', ['client', 'server']) api.add_files([ 'lib/status.html', 'lib/retry_time.js', 'lib/status.js', 'i18n/en.i18n.json', 'i18n/es.i18n.json' ], 'client') }) Package.on_test(function(api) { api.use([ 'status', 'tinytest', 'test-helpers' ], 'client') api.add_files('test/status_tests.js', 'client') })
Package.describe({ summary: 'Display the connection status with the server' }) Package.on_use(function(api, where) { api.use([ 'meteor', 'underscore', 'templating' ], 'client') api.use(['tap-i18n'], ['client', 'server']) api.add_files('package-tap.i18n', ['client', 'server']) api.add_files([ 'lib/status.html', 'lib/retry_time.js', 'lib/status.js', 'i18n/en.i18n.json', 'i18n/es.i18n.json' ], 'client') }) Package.on_test(function(api) { api.use([ 'status', 'tinytest', 'test-helpers' ], 'client') api.add_files('test/status_tests.js', 'client') })
Add validation id for staging tests.
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.application.validation; import java.util.Optional; /** * Ids of validations that can be overridden * * @author bratseth */ public enum ValidationId { indexingChange("indexing-change"), indexModeChange("indexing-mode-change"), fieldTypeChange("field-type-change"), clusterSizeReduction("cluster-size-reduction"), contentClusterRemoval("content-cluster-removal"), configModelVersionMismatch("config-model-version-mismatch"), skipOldConfigModels("skip-old-config-models"), skipVespaStagingTests("skip-vespa-staging-tests"); private final String id; ValidationId(String id) { this.id = id; } public String value() { return id; } @Override public String toString() { return id; } /** * Returns the validation id from this string. * Use this instead of valueOf to match string on the (canonical) dash-separated form. * * @return the matching validation id or empty if none */ public static Optional<ValidationId> from(String id) { for (ValidationId candidate : ValidationId.values()) if (id.equals(candidate.toString())) return Optional.of(candidate); return Optional.empty(); } }
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.application.validation; import java.util.Optional; /** * Ids of validations that can be overridden * * @author bratseth */ public enum ValidationId { indexingChange("indexing-change"), indexModeChange("indexing-mode-change"), fieldTypeChange("field-type-change"), clusterSizeReduction("cluster-size-reduction"), contentClusterRemoval("content-cluster-removal"), configModelVersionMismatch("config-model-version-mismatch"), skipOldConfigModels("skip-old-config-models"); private final String id; ValidationId(String id) { this.id = id; } public String value() { return id; } @Override public String toString() { return id; } /** * Returns the validation id from this string. * Use this instead of valueOf to match string on the (canonical) dash-separated form. * * @return the matching validation id or empty if none */ public static Optional<ValidationId> from(String id) { for (ValidationId candidate : ValidationId.values()) if (id.equals(candidate.toString())) return Optional.of(candidate); return Optional.empty(); } }
Revert "$this->app->share deprecated in 5.4" This reverts commit 3297ab6d4c36bbe8e15701bae370177e9bb91e81.
<?php namespace Cornford\Bootstrapper; use Illuminate\Support\ServiceProvider; class BootstrapServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $assetPath = __DIR__.'/../../../public'; $this->publishes([$assetPath => public_path('packages/cornford/bootstrapper')], 'bootstrapper'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['bootstrap'] = $this->app->share(function($app) { return new Bootstrap( $this->app->make('Illuminate\Html\FormBuilder', ['csrfToken' => $app['session.store']->getToken()]), $this->app->make('Illuminate\Html\HtmlBuilder'), $this->app->make('Illuminate\Http\Request') ); }); } /** * Get the services provided by the provider. * * @return string[] */ public function provides() { return array('bootstrap'); } }
<?php namespace Cornford\Bootstrapper; use Illuminate\Support\ServiceProvider; class BootstrapServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $assetPath = __DIR__.'/../../../public'; $this->publishes([$assetPath => public_path('packages/cornford/bootstrapper')], 'bootstrapper'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('bootstrap', function($app) { return new Bootstrap( $this->app->make('Illuminate\Html\FormBuilder', ['csrfToken' => $app['session.store']->getToken()]), $this->app->make('Illuminate\Html\HtmlBuilder'), $this->app->make('Illuminate\Http\Request') ); }); } /** * Get the services provided by the provider. * * @return string[] */ public function provides() { return array('bootstrap'); } }
Replace the 'Customize' Tab with 'Install'
<?php /* Tab Menu */ $tabs = array( array( 'url'=>"index.php", 'label'=>"Home" ), array( 'url'=>"impulserecreations.user.js", 'label'=>"Install" ), //array( 'url'=>"customize", 'label'=>"Customize" ), array( 'url'=>"http://www.impulsecreations.net/", 'label'=>"Impulse Creations" ) ); if ( DEBUG_LVL >= 1 ) { $tabs []= array( 'url'=>"debug", 'label'=>"[ debug ]" ); } ?> <div class="nav tabs"> <ul> <?php foreach ($tabs as $tab): $class = (isset($irec_selected_tab) && $irec_selected_tab == $tab['label']) ? "class=\"selected\"" : ""; $target = ( substr($tab['url'],0,4) == "http" ) ? "target=\"_blank\"" : ""; ?> <li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?></a></li> <?php endforeach; ?> </ul> </div>
<?php /* Tab Menu */ $tabs = array( array( 'url'=>"index.php", 'label'=>"Home" ), array( 'url'=>"customize", 'label'=>"Customize" ), array( 'url'=>"http://www.impulsecreations.net/", 'label'=>"Impulse Creations" ) ); if ( DEBUG_LVL >= 1 ) { $tabs []= array( 'url'=>"debug", 'label'=>"[ debug ]" ); } ?> <div class="nav tabs"> <ul> <?php foreach ($tabs as $tab): $class = (isset($irec_selected_tab) && $irec_selected_tab == $tab['label']) ? "class=\"selected\"" : ""; $target = ( substr($tab['url'],0,4) == "http" ) ? "target=\"_blank\"" : ""; ?> <li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?></a></li> <?php endforeach; ?> </ul> </div>
Use expanded style in rendered css
let fs = require('fs'); let mkdirp = require('mkdirp'); let sass = require('node-sass'); sass.render({ file: 'sass/matter.sass', indentedSyntax: true, outputStyle: 'expanded', }, function (renderError, result) { if (renderError) { console.log(renderError); } else { mkdirp('dist/css', function (mkdirError) { if (mkdirError) { console.log(mkdirError); } else { fs.writeFile('dist/css/matter.css', result.css, function (writeError) { if (writeError) { console.log(writeError); } else { console.log('dist/css/matter.css generated!'); } }); } }); } });
let fs = require('fs'); let mkdirp = require('mkdirp'); let sass = require('node-sass'); sass.render({ file: 'sass/matter.sass', }, function (renderError, result) { if (renderError) { console.log(renderError); } else { mkdirp('dist/css', function (mkdirError) { if (mkdirError) { console.log(mkdirError); } else { fs.writeFile('dist/css/matter.css', result.css, function (writeError) { if (writeError) { console.log(writeError); } else { console.log('dist/css/matter.css generated!'); } }); } }); } });
Fix error when docs isn't set
var express = require('express'); var router = express.Router(); var Fact = require('../db').Fact; var missingFact = { id: "missingfact", text: "I'm sorry, I can't remember that fact:(" } // API information routes router.get('/', function(req, res, next) { res.render('api', { title: 'Fun Facts API' }); }); router.get('/v1/', function(req, res, next) { res.render('api-v1', { title: 'Fun Facts API v1' }); }); // 1.X Routes router.get('/v1/fact/random', function(req, res, next) { Fact.random(function(err, docs) { res.json(cleanFact(docs)); }); }); router.get('/v1/fact/:factId', function(req, res, next) { var factId = req.params.factId; Fact.fetch(factId, function(err, docs) { res.json(cleanFact(docs)); }); }); // Helper functions var cleanFact = function(docs) { if (docs != null) { if (docs[0] != null) { var factData = docs[0]; var fact = { id: factData.id, text: factData.text } return fact; } else { return missingFact; } } else { return missingFact; } }; module.exports = router;
var express = require('express'); var router = express.Router(); var Fact = require('../db').Fact; // API information routes router.get('/', function(req, res, next) { res.render('api', { title: 'Fun Facts API' }); }); router.get('/v1/', function(req, res, next) { res.render('api-v1', { title: 'Fun Facts API v1' }); }); // 1.X Routes router.get('/v1/fact/random', function(req, res, next) { Fact.random(function(err, docs) { res.json(cleanFact(docs)); }); }); router.get('/v1/fact/:factId', function(req, res, next) { var factId = req.params.factId; Fact.fetch(factId, function(err, docs) { res.json(cleanFact(docs)); }); }); // Helper functions var cleanFact = function(docs) { if (docs[0] != null) { var factData = docs[0]; var fact = { id: factData.id, text: factData.text } return fact; } else { return fact = { id: "missingfact", text: "I'm sorry, I can't remember that fact :(" } } }; module.exports = router;
Change entity create to call set event
import * as ecsChanges from './changes'; const ECSController = { [ecsChanges.ENTITY_CREATE]: (change, store, notify) => { const { id, template } = change.data; // Manipulate change data to include entity data let entity = store.state.create(id); change.data.entity = entity; for (let name in template) { // Use template to call SET change event store.changes.unshift(ecsChanges.set(entity, name, template[name])); } notify(change); }, [ecsChanges.ENTITY_REMOVE]: (change, store, notify) => { notify(); store.state.remove(change.data); }, [ecsChanges.SET]: (change) => { const { entity, key, value } = change.data; // notify(); entity.set(key, value); }, [ecsChanges.REMOVE]: (change) => { const { entity, key } = change.data; // notify(); entity.remove(key); } }; export default ECSController;
import * as ecsChanges from './changes'; const ECSController = { [ecsChanges.ENTITY_CREATE]: (change, store, notify) => { const { id, template } = change.data; // Manipulate change data to include entity data change.data.entity = store.state.create(id, template); notify(change); }, [ecsChanges.ENTITY_REMOVE]: (change, store, notify) => { notify(); store.state.remove(change.data); }, [ecsChanges.SET]: (change) => { const { entity, key, value } = change.data; // notify(); entity.set(key, value); }, [ecsChanges.REMOVE]: (change) => { const { entity, key } = change.data; // notify(); entity.remove(key); } }; export default ECSController;
Add default handler for other routes that are not cached
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); workbox.precaching.precache(['/offline/']); const persistentPages = ['/', '/blog/', '/events/', '/projects/']; const persistentPagesStrategy = new workbox.strategies.StaleWhileRevalidate({ cacheName: 'persistent-pages', plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }); persistentPages.forEach(path => { workbox.routing.registerRoute(path, persistentPagesStrategy); }); // https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route workbox.routing.setCatchHandler(context => { if (context.event.request.destination === 'document') { return caches.match('/offline/'); } return Response.error(); }); workbox.routing.setDefaultHandler( new workbox.strategies.NetworkOnly() );
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); workbox.precaching.precache(['/offline/']); const persistentPages = ['/', '/blog/', '/events/', '/projects/']; const persistentPagesStrategy = new workbox.strategies.StaleWhileRevalidate({ cacheName: 'persistent-pages', plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }); persistentPages.forEach(path => { workbox.routing.registerRoute(path, persistentPagesStrategy); }); // https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route workbox.routing.setCatchHandler(context => { if (context.event.request.destination === 'document') { return caches.match('/offline/'); } return Response.error(); });
Fix unit test case error
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * 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 * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.api.extension; import java.util.Locale; import java.util.ResourceBundle; import com.ibm.icu.util.ULocale; import com.ibm.icu.util.UResourceBundle; /** * Provides the resource bundle with the given locale. */ public interface IResourceBundleProvider { /** * Returns the resource bundle with the locale. * * @param locale * the given locale * @return the resource bundle * @deprecated to support ICU4J, replaced by : * getResourceBundle(ULocale locale) */ public ResourceBundle getResourceBundle( Locale locale ); /** * Returns the resource bundle with the locale. * * @param locale * the given locale * @return the resource bundle */ public UResourceBundle getResourceBundle( ULocale locale ); }
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * 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 * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.api.extension; import java.util.Locale; import java.util.ResourceBundle; import com.ibm.icu.util.ULocale; /** * Provides the resource bundle with the given locale. */ public interface IResourceBundleProvider { /** * Returns the resource bundle with the locale. * * @param locale * the given locale * @return the resource bundle * @deprecated to support ICU4J, replaced by : * getResourceBundle(ULocale locale) */ public ResourceBundle getResourceBundle( Locale locale ); /** * Returns the resource bundle with the locale. * * @param locale * the given locale * @return the resource bundle */ public ResourceBundle getResourceBundle( ULocale locale ); }
Add log statement if REST API can't be accessed
import requests import json from subprocess import Popen, PIPE import tempfile import os import sys config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi)) if request.status_code == 200: cjson = request.json(); else: print >> sys.stderr, "Unable to access REST API: %s" % request.status_code return None # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
import requests import json from subprocess import Popen, PIPE import tempfile import os config = {} with open ('../config/conversion.json') as fp: config = json.load(fp) def to_cml(inchi): request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi)) if request.status_code == 200: cjson = request.json(); else: return None print cjson # Call convertion routine p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(json.dumps(cjson['results'][0])) fd, path = tempfile.mkstemp(suffix='.cml') with open(path, 'w') as fp: fp.write(str(stdout)) os.close(fd) return path
Rewrite render string method to support newer Twig engine
<?php namespace CodeGen; use Twig_Loader_String; use Twig_Environment; use Closure; class Utils { static $stringloader = null; static $twig; static public function renderStringTemplate($templateContent, array $args = array(), Twig_Environment $env = null) { if (!$env) { $env = new Twig_Environment; } $template = $twig->createTemplate($templateContent); if (is_callable($args)) { $args = call_user_func($args); } elseif ($args instanceof Closure) { $args = $args(); } return $template->render($args); } static public function evalCallback($cb) { return is_callable($cb) ? $cb() : $cb; } static public function indent($indent = 1, $spaces = 4) { return str_repeat(' ', $spaces * $indent); } }
<?php namespace CodeGen; use Twig_Loader_String; use Twig_Environment; use Closure; class Utils { static $stringloader = null; static $twig; static public function renderStringTemplate($templateContent, array $args = array()) { if (!self::$stringloader) { self::$stringloader = new Twig_Loader_String(); } if (!self::$twig) { self::$twig = new Twig_Environment(self::$stringloader); } if (is_callable($args)) { $args = call_user_func($args); } elseif ($args instanceof Closure) { $args = $args(); } return self::$twig->render($templateContent, $args); } static public function evalCallback($cb) { return is_callable($cb) ? $cb() : $cb; } static public function indent($indent = 1, $spaces = 4) { return str_repeat(' ', $spaces * $indent); } }
Fix problem with exception classes
<?php namespace SBLayout\Model\Page; use SBLayout\Model\Application; use SBLayout\Model\PageForbiddenException; use SBLayout\Model\PageNotFoundException; use SBLayout\Model\Page\Content\Contents; /** * Defines a page displaying arbitrary contents in one or more content sections. */ class ContentPage extends Page { /** A content object storing properties of the content sections of a page */ public $contents; /** * Creates a new ContentPage instance * * @param string $title Title of the page that is used as a label in a menu section * @param Contents $contents A content object storing properties of the content sections of a page */ public function __construct($title, Contents $contents) { parent::__construct($title); $this->contents = $contents; } /** * @see Page::checkVisibility() */ public function checkVisibility() { return true; } /** * @see Page::checkAccessibility() */ public function checkAccessibility() { return true; } /** * @see Page::lookupSubPage() */ public function lookupSubPage(Application $application, array $ids, $index = 0) { if(count($ids) == $index) { if($this->checkAccessibility()) return $this; else throw new PageForbiddenException(); } else throw new PageNotFoundException(); // A ContentPage does not refer to sub pages } } ?>
<?php namespace SBLayout\Model\Page; use SBLayout\Model\Application; use SBLayout\Model\Page\Content\Contents; /** * Defines a page displaying arbitrary contents in one or more content sections. */ class ContentPage extends Page { /** A content object storing properties of the content sections of a page */ public $contents; /** * Creates a new ContentPage instance * * @param string $title Title of the page that is used as a label in a menu section * @param Contents $contents A content object storing properties of the content sections of a page */ public function __construct($title, Contents $contents) { parent::__construct($title); $this->contents = $contents; } /** * @see Page::checkVisibility() */ public function checkVisibility() { return true; } /** * @see Page::checkAccessibility() */ public function checkAccessibility() { return true; } /** * @see Page::lookupSubPage() */ public function lookupSubPage(Application $application, array $ids, $index = 0) { if(count($ids) == $index) { if($this->checkAccessibility()) return $this; else throw new PageForbiddenException(); } else throw new PageNotFoundException(); // A ContentPage does not refer to sub pages } } ?>
Taskwiki: Update tasks and evaluate viewports on saving
import sys import re import vim from tasklib.task import TaskWarrior, Task # Insert the taskwiki on the python path sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki') from regexp import * from task import VimwikiTask from cache import TaskCache """ How this plugin works: 1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their uuid. 2.) When saving, the opposite sync is performed (Vimwiki -> TW direction). a) if task is marked as subtask by indentation, the dependency is created between """ tw = TaskWarrior() cache = TaskCache(tw) def update_from_tw(): """ Updates all the incomplete tasks in the vimwiki file if the info from TW is different. """ cache.load_buffer() cache.update_tasks() cache.update_buffer() cache.evaluate_viewports() def update_to_tw(): """ Updates all tasks that differ from their TaskWarrior representation. """ cache.reset() cache.load_buffer() cache.update_tasks() cache.save_tasks() cache.update_buffer() cache.evaluate_viewports() if __name__ == '__main__': update_from_tw()
import sys import re import vim from tasklib.task import TaskWarrior, Task # Insert the taskwiki on the python path sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki') from regexp import * from task import VimwikiTask from cache import TaskCache """ How this plugin works: 1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their uuid. 2.) When saving, the opposite sync is performed (Vimwiki -> TW direction). a) if task is marked as subtask by indentation, the dependency is created between """ tw = TaskWarrior() cache = TaskCache(tw) def update_from_tw(): """ Updates all the incomplete tasks in the vimwiki file if the info from TW is different. """ cache.load_buffer() cache.update_tasks() cache.update_buffer() cache.evaluate_viewports() def update_to_tw(): """ Updates all tasks that differ from their TaskWarrior representation. """ cache.reset() cache.load_buffer() cache.save_tasks() cache.update_buffer() if __name__ == '__main__': update_from_tw()
Print what we're doing, and make executable
#!/usr/bin/env node var rimraf = require('rimraf') var fs = require('fs') var childProcess = require('child_process') var walkSync = require('./') rimraf.sync('benchmark.tmp') var directories = 100, files = 1000 function createDirWithFiles(dir) { fs.mkdirSync(dir) for (var i = 0; i < files; i++) { fs.writeFileSync(dir + '/' + i, 'foo') } } console.log('Creating ' + (directories * files) + ' files across ' + directories + ' directories') createDirWithFiles('benchmark.tmp') for (var i = 0; i < directories - 1; i++) { createDirWithFiles('benchmark.tmp/dir' + i) } childProcess.spawnSync('sync') console.time('walkSync') walkSync('benchmark.tmp') console.timeEnd('walkSync') console.time('walkSync with **/* glob') walkSync('benchmark.tmp', ['**/*']) console.timeEnd('walkSync with **/* glob') console.time('walkSync with **/*DOESNOTMATCH glob') walkSync('benchmark.tmp', ['**/*DOESNOTMATCH']) console.timeEnd('walkSync with **/*DOESNOTMATCH glob') console.time('walkSync with DOESNOTMATCH*/** glob') walkSync('benchmark.tmp', ['DOESNOTMATCH*/**']) console.timeEnd('walkSync with DOESNOTMATCH*/** glob') rimraf.sync('benchmark.tmp')
#!/usr/bin/env node var rimraf = require('rimraf') var fs = require('fs') var childProcess = require('child_process') var walkSync = require('./') rimraf.sync('benchmark.tmp') function createDirWithFiles(dir) { fs.mkdirSync(dir) for (var i = 0; i < 1000; i++) { fs.writeFileSync(dir + '/' + i, 'foo') } } createDirWithFiles('benchmark.tmp') for (var i = 0; i < 100; i++) { createDirWithFiles('benchmark.tmp/dir' + i) } childProcess.spawnSync('sync') console.time('walkSync') walkSync('benchmark.tmp') console.timeEnd('walkSync') console.time('walkSync with **/* glob') walkSync('benchmark.tmp', ['**/*']) console.timeEnd('walkSync with **/* glob') console.time('walkSync with **/*DOESNOTMATCH glob') walkSync('benchmark.tmp', ['**/*DOESNOTMATCH']) console.timeEnd('walkSync with **/*DOESNOTMATCH glob') console.time('walkSync with DOESNOTMATCH*/** glob') walkSync('benchmark.tmp', ['DOESNOTMATCH*/**']) console.timeEnd('walkSync with DOESNOTMATCH*/** glob') rimraf.sync('benchmark.tmp')
:art: Clean up boolean cell styles
import React from 'react'; import { Dropdown, Icon, Menu, Button } from 'antd'; import { func, number, string, any } from 'prop-types'; const { Item } = Menu; const BooleanCell = ({ children, onChange, row, column }) => ( <div css={{ width: 250, height: 42, }} > <Dropdown trigger={['click']} css={{ width: '100%', height: '100%', borderColor: 'transparent' }} overlay={ <Menu onClick={({ key }) => onChange(row, column, key === 'true')} > <Item key="true"> <Icon type="check-circle" /> true </Item> <Item key="false"> <Icon type="close-circle" /> false </Item> </Menu> } > <Button> <div css={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > {String(children)} <Icon type="down" /> </div> </Button> </Dropdown> </div> ); BooleanCell.propTypes = { row: number.isRequired, column: string.isRequired, onChange: func.isRequired, children: any, }; export default BooleanCell;
import React from 'react'; import { Dropdown, Icon, Menu, Button } from 'antd'; import { func, number, string, any } from 'prop-types'; const { Item } = Menu; const BooleanCell = ({ children, onChange, row, column }) => ( <div css={{ width: 250, height: 42, }} > <Dropdown trigger={['click']} css={{ width: '100%', height: '100%' }} overlay={ <Menu onClick={({ key }) => onChange(row, column, key === 'true')} > <Item key="true"> <Icon type="check-circle" /> true </Item> <Item key="false"> <Icon type="close-circle" /> false </Item> </Menu> } > <Button> <div css={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > {String(children)} <Icon type="down" /> </div> </Button> </Dropdown> </div> ); BooleanCell.propTypes = { row: number.isRequired, column: string.isRequired, onChange: func.isRequired, children: any, }; export default BooleanCell;
Set localhost as default proxy
var webpack = require('webpack'); var path = require('path'); var loaders = require('./webpack.loaders'); module.exports = { entry: [ 'webpack/hot/only-dev-server', './src/index.jsx' // Your appʼs entry point ], devtool: process.env.WEBPACK_DEVTOOL || 'source-map', output: { path: __dirname + '/build', publicPath: '/', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, postcss() { return [require('precss'), require('autoprefixer')] }, module: { loaders: loaders }, devServer: { historyApiFallback: true, contentBase: './build', hot: true, stats: { colors: true, chunks: false }, proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {'^/api' : ''} } }, }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.ProvidePlugin({ 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch' }) ] };
var webpack = require('webpack'); var path = require('path'); var loaders = require('./webpack.loaders'); module.exports = { entry: [ 'webpack/hot/only-dev-server', './src/index.jsx' // Your appʼs entry point ], devtool: process.env.WEBPACK_DEVTOOL || 'source-map', output: { path: __dirname + '/build', publicPath: '/', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, postcss() { return [require('precss'), require('autoprefixer')] }, module: { loaders: loaders }, devServer: { historyApiFallback: true, contentBase: './build', hot: true, stats: { colors: true, chunks: false }, proxy: { '/api': { target: 'http://10.0.0.171:3000', pathRewrite: {'^/api' : ''} } }, }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.ProvidePlugin({ 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch' }) ] };
Add general text message for feedback form
import Ember from "ember"; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; var msg = values.body; var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); if (url_for === "transport_page") { values.body = msg.replace( "[" + url_with_text + "]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>` ); } if (url_for === "feedback_form") { values.body = msg.replace( "[" + url_with_text + "]", `<a href=' https://crossroads-foundation.formstack.com/forms/goodcity_feedback?OfferId=${offerId}'>${url_text}</a>` ); } } });
import Ember from 'ember'; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; var msg = values.body; var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); if(url_for === 'transport_page'){ values.body = msg.replace("["+url_with_text+"]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>`); } } });
Add python_requires to help pip When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions. For more info on how this works: * https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4 * https://github.com/pypa/python-packaging-user-guide/issues/450
import sys import os from os.path import join from setuptools import setup # Also in twarc.py __version__ = '1.4.0' if sys.version_info[0] < 3: dependencies = open(join('requirements', 'python2.txt')).read().split() else: dependencies = open(join('requirements', 'python3.txt')).read().split() if __name__ == "__main__": setup( name='twarc', version=__version__, url='https://github.com/docnow/twarc', author='Ed Summers', author_email='ehs@pobox.com', packages=['twarc',], description='Archive tweets from the command line', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', install_requires=dependencies, setup_requires=['pytest-runner'], tests_require=['pytest'], entry_points={'console_scripts': ['twarc = twarc:main']} )
import sys import os from os.path import join from setuptools import setup # Also in twarc.py __version__ = '1.4.0' if sys.version_info[0] < 3: dependencies = open(join('requirements', 'python2.txt')).read().split() else: dependencies = open(join('requirements', 'python3.txt')).read().split() if __name__ == "__main__": setup( name='twarc', version=__version__, url='https://github.com/docnow/twarc', author='Ed Summers', author_email='ehs@pobox.com', packages=['twarc',], description='Archive tweets from the command line', install_requires=dependencies, setup_requires=['pytest-runner'], tests_require=['pytest'], entry_points={'console_scripts': ['twarc = twarc:main']} )
Fix fucking creazy bug :((((
<?php namespace Morilog\Acl\Console\Commands; use Illuminate\Console\Command; use Illuminate\Contracts\Config\Repository; use Morilog\Acl\Managers\Interfaces\RoleManagerInterface; class AddDefaultRoles extends Command { protected $signature = 'morilog:acl:add-roles'; protected $description = 'Insert default Roles to database.'; /** * @var RoleManagerInterface */ protected $roleManager; /** * @var Repository */ private $config; public function __construct(RoleManagerInterface $roleManager, Repository $config) { parent::__construct(); $this->roleManager = $roleManager; $this->config = $config; } public function handle() { try { $defaultRoles = $this->config->get('acl.default_roles', []); foreach ($defaultRoles as $roleName) { $newRole = $this->roleManager->createRoleByName($roleName); $this->info(sprintf('Role %s has beed added successfully.', $newRole->getName())); } } catch (\Exception $e) { $this->error($e->getMessage()); } } }
<?php namespace Morilog\Acl\Console\Commands; use Illuminate\Console\Command; use Illuminate\Contracts\Config\Repository; use Morilog\Acl\Managers\Interfaces\RoleManagerInterface; class AddDefaultRoles extends Command { protected $signature = 'morilog:acl:add-roles'; protected $description = 'Insert default Roles to database.'; /** * @var RoleManagerInterface */ protected $roleManager; /** * @var Repository */ private $config; public function __construct(RoleManagerInterface $roleManager, Repository $config) { parent::__construct(); $this->roleManger = $roleManager; $this->config = $config; } public function handle() { try { $defaultRoles = $this->config->get('acl.default_roles', []); foreach ($defaultRoles as $roleName) { $newRole = $this->roleManager->createRoleByName($roleName); $this->info(sprintf('Role %s has beed added successfully.', $newRole->getName())); } } catch (\Exception $e) { $this->error($e->getMessage()); } } }
Fix location coordinate field naming
module.exports = (function() { var config = require('config'); var mongoose = require('mongoose'); var db = mongoose.connection; var schemas = {}; var eventSchema = new mongoose.Schema({ 'category': String, 'coordinates': { 'latitude': Number, 'longitude': Number }, 'name': String, 'original_id': String, 'url': String }); var locationSchema = new mongoose.Schema({ 'category': String, 'coordinates': { 'latitude': Number, 'longitude': Number } }); schemas.Event = mongoose.model('Event', eventSchema); schemas.Location = mongoose.model('Location', locationSchema); mongoose.connect(config.get('mongo').url); return { db: db, schemas: schemas }; }());
module.exports = (function() { var config = require('config'); var mongoose = require('mongoose'); var db = mongoose.connection; var schemas = {}; var eventSchema = new mongoose.Schema({ 'category': String, 'coordinates': { 'latitude': Number, 'longitude': Number }, 'name': String, 'original_id': String, 'url': String }); var locationSchema = new mongoose.Schema({ 'category': String, 'location': { 'latitude': Number, 'longitude': Number } }); schemas.Event = mongoose.model('Event', eventSchema); schemas.Location = mongoose.model('Location', locationSchema); mongoose.connect(config.get('mongo').url); return { db: db, schemas: schemas }; }());
Remove Textarea Label, Use Frig Version Instead
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), valueLink: this.props.valueLink, }) } _cx() { return cx({ "form-group": true, "has-error": this.props.errors != null, "has-success": this.state.edited && this.props.errors == null, }) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, label(this.props), div({className: "controls"}, textarea(this._inputHtml()), ), errorList(this.props.errors), ), ) } }
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), valueLink: this.props.valueLink, }) } _cx() { return cx({ "form-group": true, "has-error": this.props.errors != null, "has-success": this.state.edited && this.props.errors == null, }) } _label() { if (this.props.label == null) return "" return label(this.props.labelHtml, this.props.label) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, this._label(), div({className: "controls"}, textarea(this._inputHtml()), ), this._errorList(this.props.errors), ), ) } }
Comment how to port to new Base64 encoder in Java 8 and 9
package net.bettyluke.tracinstant.data; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import net.bettyluke.tracinstant.prefs.SiteSettings; public final class AuthenticatedHttpRequester { private AuthenticatedHttpRequester() {} public static InputStream getInputStream(SiteSettings settings, URL url) throws IOException { URLConnection uc = url.openConnection(); if (!settings.getUsername().isEmpty()) { String userpass = settings.getUsername() + ":" + settings.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); // Note: change to the following when moving to Java 8, as the above will stop working in Java 9. // Base64.getEncoder().encodeToString(userpass.getBytes()); uc.setRequestProperty ("Authorization", basicAuth); } return uc.getInputStream(); } }
package net.bettyluke.tracinstant.data; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import net.bettyluke.tracinstant.prefs.SiteSettings; public final class AuthenticatedHttpRequester { private AuthenticatedHttpRequester() {} public static InputStream getInputStream(SiteSettings settings, URL url) throws IOException { URLConnection uc = url.openConnection(); if (!settings.getUsername().isEmpty()) { String userpass = settings.getUsername() + ":" + settings.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary( userpass.getBytes()); uc.setRequestProperty ("Authorization", basicAuth); } return uc.getInputStream(); } }
Change port and do make clean build
const path = require('path'); const merge = require('webpack-merge'); const exec = require('child_process').exec; const FilewatcherPlugin = require('filewatcher-webpack-plugin'); const WatchPlugin = require('webpack-watch-files-plugin').default; const ShellPlugin = require('webpack-shell-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', watch: true, devServer: { contentBase: path.join(__dirname, 'docs/build/html'), watchContentBase: true, compress: false, port: 1919, hot: false, liveReload: true, publicPath: '/_static/' }, plugins: [ new WatchPlugin({ files: [ './docs/**/*.rst', './docs/**/*.py', ] }), new ShellPlugin({ onBuildEnd: ['make -C docs clean html'], // dev=false here to force every build to trigger make, the default is // first build only. dev: false, }), ] });
const path = require('path'); const merge = require('webpack-merge'); const exec = require('child_process').exec; const FilewatcherPlugin = require('filewatcher-webpack-plugin'); const WatchPlugin = require('webpack-watch-files-plugin').default; const ShellPlugin = require('webpack-shell-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', watch: true, devServer: { contentBase: path.join(__dirname, 'docs/build/html'), watchContentBase: true, compress: false, port: 7070, hot: false, liveReload: true, publicPath: '/_static/' }, plugins: [ new WatchPlugin({ files: [ './docs/**/*.rst', './docs/**/*.py', ] }), new ShellPlugin({ onBuildEnd: ['make -C docs html'], dev: false, }), ] });
Add default step for setting (per hour)
<?php return [ 'App\Models\Business' => [ 'start_at' => ['type' => 'time', 'value' => '08:00:00'], 'finish_at' => ['type' => 'time', 'value' => '19:00:00'], 'show_map' => ['type' => 'bool', 'value' => false], 'show_postal_address' => ['type' => 'bool', 'value' => false], 'show_phone' => ['type' => 'bool', 'value' => false], 'appointment_annulation_pre_hs' => ['type' => 'int', 'value' => '48', 'step' => 1, 'icon' => 'hourglass'], 'appointment_take_today' => ['type' => 'bool', 'value' => false], 'appointment_code_length' => ['type' => 'int', 'value' => 4, 'icon' => 'barcode'], 'service_default_duration' => ['type' => 'int', 'value' => 30, 'step' => 5, 'icon' => 'hourglass'], 'annulation_policy_advice' => ['type' => 'string', 'value' => ''], ], ];
<?php return [ 'App\Models\Business' => [ 'start_at' => ['type' => 'time', 'value' => '08:00:00'], 'finish_at' => ['type' => 'time', 'value' => '19:00:00'], 'show_map' => ['type' => 'bool', 'value' => false], 'show_postal_address' => ['type' => 'bool', 'value' => false], 'show_phone' => ['type' => 'bool', 'value' => false], 'appointment_annulation_pre_hs' => ['type' => 'int', 'value' => '48', 'icon' => 'hourglass'], 'appointment_take_today' => ['type' => 'bool', 'value' => false], 'appointment_code_length' => ['type' => 'int', 'value' => 4, 'icon' => 'barcode'], 'service_default_duration' => ['type' => 'int', 'value' => 30, 'step' => 5, 'icon' => 'hourglass'], ], ];
Fix defaults for undefined options
'use strict'; var chalk = require('chalk'); var path = require('path'); function WebpackKarmaDieHardPlugin(options) { if (typeof(options) === "undefined") { options = {}; } chalk.enabled = options.colors !== false } WebpackKarmaDieHardPlugin.prototype.apply = function(compiler) { compiler.plugin('done', function(stats) { // Need to report warnings and errors manually, since these will not bubble // up to the user. stats.compilation.warnings.forEach(function (warning) { console.warn(chalk.yellow("WARNING: ./" + path.relative("", warning.module.resource))); console.warn(chalk.yellow(warning.message || warning)); }); stats.compilation.errors.forEach(function (error) { console.error(chalk.red("ERROR: ./" + path.relative("", error.module.resource))); console.error(chalk.red(error.message || error)); }); if (stats.compilation.errors.length > 0) { // karma-webpack will hang indefinitely if no assets are produced, so just // blow up noisily. process.exit(1); } }); }; module.exports = WebpackKarmaDieHardPlugin;
'use strict'; var chalk = require('chalk'); var path = require('path'); function WebpackKarmaDieHardPlugin(options) { if (typeof(options) === undefined) { options = {}; } chalk.enabled = options.colors !== false } WebpackKarmaDieHardPlugin.prototype.apply = function(compiler) { compiler.plugin('done', function(stats) { // Need to report warnings and errors manually, since these will not bubble // up to the user. stats.compilation.warnings.forEach(function (warning) { console.warn(chalk.yellow("WARNING: ./" + path.relative("", warning.module.resource))); console.warn(chalk.yellow(warning.message || warning)); }); stats.compilation.errors.forEach(function (error) { console.error(chalk.red("ERROR: ./" + path.relative("", error.module.resource))); console.error(chalk.red(error.message || error)); }); if (stats.compilation.errors.length > 0) { // karma-webpack will hang indefinitely if no assets are produced, so just // blow up noisily. process.exit(1); } }); }; module.exports = WebpackKarmaDieHardPlugin;
Replace usage of Math.sqrt in with Math.log LogFontScalar.java was (erroneously?) using Math.sqrt instead of Math.log to compute the leftSpan.
package com.kennycason.kumo.font.scale; /** * Created by kenny on 6/30/14. */ public class LogFontScalar implements FontScalar { private final int minFont; private final int maxFont; public LogFontScalar(final int minFont, final int maxFont) { this.minFont = minFont; this.maxFont = maxFont; } @Override public float scale(final int value, final int minValue, final int maxValue) { final double leftSpan = Math.log(maxValue) - Math.log(minValue); final double rightSpan = maxFont - minFont; // Convert the left range into a 0-1 range final double valueScaled = (Math.log(value) - Math.log(minValue)) / leftSpan; // Convert the 0-1 range into a value in the right range. return (float) (minFont + (valueScaled * rightSpan)); } }
package com.kennycason.kumo.font.scale; /** * Created by kenny on 6/30/14. */ public class LogFontScalar implements FontScalar { private final int minFont; private final int maxFont; public LogFontScalar(final int minFont, final int maxFont) { this.minFont = minFont; this.maxFont = maxFont; } @Override public float scale(final int value, final int minValue, final int maxValue) { final double leftSpan = Math.sqrt(maxValue) - Math.sqrt(minValue); final double rightSpan = maxFont - minFont; // Convert the left range into a 0-1 range final double valueScaled = (Math.log(value) - Math.log(minValue)) / leftSpan; // Convert the 0-1 range into a value in the right range. return (float) (minFont + (valueScaled * rightSpan)); } }
Rename anonymous to make the styling more like others
/** * Helper functions that are used in the other modules to reduce the number of times * that code for common tasks is rewritten * * (c) 2013, Greg Malysa <gmalysa@stanford.edu> * Permission to use granted under the terms of the MIT License. See LICENSE for details. */ /** * Retrieves the name for a function, using fn.name to determine what it is, or if no * name is given (i.e. an anonymous function), returns altname. If altname is ALSO not * given, returns (anonymous), as a final default value. * @param fn Function whose name we want to find * @param altname Optional string, name to use if the function was anonymous * @return String name of the function */ module.exports.fname = function(fn, altname) { if (fn.name) return fn.name; if (altname) return altname; return '<anonymous>'; } /** * Checks if a function name should be hidden from the call graph because it is an * internal function. This is a small hack, but it helps remove internals from the * call graph, which simplifies the view for the end user working with his code, all * of which exists outsie the library. * @param name The function name to test * @return bool True if this function name should not be pushed */ module.exports.hide_function = function(name) { if (name == '__after_glue' || name == '__chain_inner') return true; return false; }
/** * Helper functions that are used in the other modules to reduce the number of times * that code for common tasks is rewritten * * (c) 2013, Greg Malysa <gmalysa@stanford.edu> * Permission to use granted under the terms of the MIT License. See LICENSE for details. */ /** * Retrieves the name for a function, using fn.name to determine what it is, or if no * name is given (i.e. an anonymous function), returns altname. If altname is ALSO not * given, returns (anonymous), as a final default value. * @param fn Function whose name we want to find * @param altname Optional string, name to use if the function was anonymous * @return String name of the function */ module.exports.fname = function(fn, altname) { if (fn.name) return fn.name; if (altname) return altname; return '(anonymous)'; } /** * Checks if a function name should be hidden from the call graph because it is an * internal function. This is a small hack, but it helps remove internals from the * call graph, which simplifies the view for the end user working with his code, all * of which exists outsie the library. * @param name The function name to test * @return bool True if this function name should not be pushed */ module.exports.hide_function = function(name) { if (name == '__after_glue' || name == '__chain_inner') return true; return false; }
Fix import of 'reverse' for Django>1.9
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = path in request.path if active: return css_class return ''
from django import template from django.conf import settings from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = path in request.path if active: return css_class return ''
Use the app string version of foreign keying. It prevents a circular import.
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): user = models.ManyToManyField( 'tracker.Tbluser', related_name="user_foreign" ) activity = models.ManyToManyField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): from timetracker.tracker.models import Tbluser user = models.ManyToManyField( Tbluser, related_name="user_foreign" ) activity = models.ManyToManyField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
[fix] Use middleware db for the query
<?php use Hubzero\Content\Migration\Base; /** * Migration script for com_tools to specify display ranges assigned to a hub, * i.e., the range used on an execution host. **/ class Migration20180703151011ComTools extends Base { /** * Up **/ public function up() { if (!$mwdb = $this->getMWDBO()) { $this->setError('Failed to connect to the middleware database', 'warning'); return false; } // ADD COLUMN first_display to table host if ($mwdb->tableExists('host') && !$mwdb->tableHasField('host', 'first_display')) { $query = "ALTER TABLE host ADD COLUMN first_display INT DEFAULT 1;"; $mwdb->setQuery($query); $mwdb->query(); } } /** * Down **/ public function down() { if (!$mwdb = $this->getMWDBO()) { $this->setError('Failed to connect to the middleware database', 'warning'); return false; } // Drop column first_display if ($mwdb->tableExists('host') && $mwdb->tableHasField('host', 'first_display')) { $query = "ALTER TABLE host DROP COLUMN first_display;"; $mwdb->setQuery($query); $mwdb->query(); } } }
<?php use Hubzero\Content\Migration\Base; /** * Migration script for com_tools to specify display ranges assigned to a hub, * i.e., the range used on an execution host. **/ class Migration20180703151011ComTools extends Base { /** * Up **/ public function up() { if (!$mwdb = $this->getMWDBO()) { $this->setError('Failed to connect to the middleware database', 'warning'); return false; } // ADD COLUMN first_display to table host if ($mwdb->tableExists('host') && !$mwdb->tableHasField('host', 'first_display')) { $query = "ALTER TABLE host ADD COLUMN first_display INT DEFAULT 1;"; $this->db->setQuery($query); $this->db->query(); } } /** * Down **/ public function down() { if (!$mwdb = $this->getMWDBO()) { $this->setError('Failed to connect to the middleware database', 'warning'); return false; } // Drop column first_display if ($mwdb->tableExists('host') && $mwdb->tableHasField('host', 'first_display')) { $query = "ALTER TABLE host DROP COLUMN first_display;"; $this->db->setQuery($query); $this->db->query(); } } }
BLD: Add support for *.pyi data-files to `np.testing._private`
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testing', parent_package, top_path) config.add_subpackage('_private') config.add_subpackage('tests') config.add_data_files('*.pyi') config.add_data_files('_private/*.pyi') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer="NumPy Developers", maintainer_email="numpy-dev@numpy.org", description="NumPy test module", url="https://www.numpy.org", license="NumPy License (BSD Style)", configuration=configuration, )
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testing', parent_package, top_path) config.add_subpackage('_private') config.add_subpackage('tests') config.add_data_files('*.pyi') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer="NumPy Developers", maintainer_email="numpy-dev@numpy.org", description="NumPy test module", url="https://www.numpy.org", license="NumPy License (BSD Style)", configuration=configuration, )
Cut fbcode_builder dep for thrift on krb5 Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up. Reviewed By: stevegury, vitaut Differential Revision: D14814205 fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final') return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.github_project_workdir('krb5/krb5', 'src'), builder.autoconf_install('krb5/krb5'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
bracket-push: Add test for proper nesting This rules out solutions that simply count the number of open/close brackets without regard for whether they are properly nested. I submitted a solution (in another language track) that would have failed this test and did not realize it until looking at others' solutions. It would be great if I could have known before submitting, thus I add this test.
var bracket = require('./bracket_push'); describe('bracket push', function() { it('checks for appropriate bracketing in a set of brackets', function() { expect(bracket('{}')).toEqual(true); }); xit('returns false for unclosed brackets', function() { expect(bracket('{{')).toEqual(false); }); xit('returns false if brackets are out of order', function() { expect(bracket('}{')).toEqual(false); }); xit('checks bracketing in more than one pair of brackets', function() { expect(bracket('{}[]')).toEqual(true); }); xit('checks bracketing in nested brackets', function() { expect(bracket('{[]}')).toEqual(true); }); xit('rejects brackets that are properly balanced but improperly nested', function() { expect(bracket('{[}]')).toEqual(false); }); xit('checks bracket closure with deeper nesting', function() { expect(bracket('{[)][]}')).toEqual(false); }); xit('checks bracket closure in a long string of brackets', function() { expect(bracket('{[]([()])}')).toEqual(true); }); });
var bracket = require('./bracket_push'); describe('bracket push', function() { it('checks for appropriate bracketing in a set of brackets', function() { expect(bracket('{}')).toEqual(true); }); xit('returns false for unclosed brackets', function() { expect(bracket('{{')).toEqual(false); }); xit('returns false if brackets are out of order', function() { expect(bracket('}{')).toEqual(false); }); xit('checks bracketing in more than one pair of brackets', function() { expect(bracket('{}[]')).toEqual(true); }); xit('checks bracketing in nested brackets', function() { expect(bracket('{[]}')).toEqual(true); }); xit('checks bracket closure with deeper nesting', function() { expect(bracket('{[)][]}')).toEqual(false); }); xit('checks bracket closure in a long string of brackets', function() { expect(bracket('{[]([()])}')).toEqual(true); }); });
Make jpeg extension allowed for image component
export function isImageURL(url) { return (/^http.+(jpg|gif|png|svg|jpeg)$/i).test(url || ""); } export function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } const error = new Error(response.statusText); error.response = response; return response.json() .then((body) => { error.body = body; }) .catch(() => {}) // Catch body parsing errors and continue .then(() => { throw error; }); } export function fetchJSON(url, opts = {}) { const defaultOpts = { credentials: "same-origin" }; return fetch(url, Object.assign({}, defaultOpts, opts)) .then(checkStatus) .then((response) => response.json()); }
export function isImageURL(url) { return (/^http.+(jpg|gif|png|svg)$/i).test(url || ""); } export function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } const error = new Error(response.statusText); error.response = response; return response.json() .then((body) => { error.body = body; }) .catch(() => {}) // Catch body parsing errors and continue .then(() => { throw error; }); } export function fetchJSON(url, opts = {}) { const defaultOpts = { credentials: "same-origin" }; return fetch(url, Object.assign({}, defaultOpts, opts)) .then(checkStatus) .then((response) => response.json()); }
Fix weird terminal output format Signed-off-by: Lei Jitang <9ac444d2b5df3db1f31aa1c6462ac8e9e2bde241@huawei.com>
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) newState.Oflag = newState.Oflag | C.OPOST if err := tcset(fd, &newState); err != 0 { return nil, err } return &oldState, nil } func tcget(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } func tcset(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 }
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) if err := tcset(fd, &newState); err != 0 { return nil, err } return &oldState, nil } func tcget(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } func tcset(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 }
Handle empty values for FieldtypeDatetime.
<?php namespace ProcessWire\GraphQL\Field\Traits; use Youshido\GraphQL\Config\Field\FieldConfig; use Youshido\GraphQL\Execution\ResolveInfo; use Youshido\GraphQL\Field\InputField; use Youshido\GraphQL\Type\Scalar\StringType; use ProcessWire\GraphQL\Utils; use ProcessWire\NullPage; use ProcessWire\FieldtypeDatetime; trait DatetimeResolverTrait { public function build(FieldConfig $config) { $config->addArgument(new InputField([ 'name' => 'format', 'type' => new StringType(), 'description' => 'PHP date formatting string. Refer to https://devdocs.io/php/function.date', ])); } public function resolve($value, array $args, ResolveInfo $info) { $fieldName = $this->getName(); if (isset($args['format'])) { $format = $args['format']; $rawValue = $value->$fieldName; if (Utils::fields()->get($fieldName) instanceof FieldtypeDatetime) { $rawValue = $value->getUnformatted($fieldName); } if ($rawValue) { return date($format, $rawValue); } else { return ""; } } return $value->$fieldName; } }
<?php namespace ProcessWire\GraphQL\Field\Traits; use Youshido\GraphQL\Config\Field\FieldConfig; use Youshido\GraphQL\Execution\ResolveInfo; use Youshido\GraphQL\Field\InputField; use Youshido\GraphQL\Type\Scalar\StringType; use ProcessWire\GraphQL\Utils; use ProcessWire\NullPage; use ProcessWire\FieldtypeDatetime; trait DatetimeResolverTrait { public function build(FieldConfig $config) { $config->addArgument(new InputField([ 'name' => 'format', 'type' => new StringType(), 'description' => 'PHP date formatting string. Refer to https://devdocs.io/php/function.date', ])); } public function resolve($value, array $args, ResolveInfo $info) { $fieldName = $this->getName(); if (isset($args['format'])) { $format = $args['format']; $rawValue = $value->$fieldName; if (Utils::fields()->get($fieldName) instanceof FieldtypeDatetime) { $rawValue = $value->getUnformatted($fieldName); } return date($format, $rawValue); } return $value->$fieldName; } }
Remove spl converter, was only an experiment with Gangnam Style.
var abc = require('./converters/abc'), fs = require('fs'), p = require('path'), converters = { abc: abc }; function Playlist() { this.songs = []; } Playlist.prototype.load = function (dir) { var files = fs.readdirSync(dir), self = this; files.forEach(function (file) { console.log('Converting %s', file); var type = p.extname(file).replace(/^\./, ''), data = fs.readFileSync(p.join(dir, file)).toString(); if (converters[type]) { var song = converters[type].convert(data) self.songs.push(song); } else { console.error('Unable to convert %s', file); } }); }; Playlist.prototype.getSong = function (trackNumber) { return this.songs[trackNumber - 1]; }; module.exports = Playlist;
var abc = require('./converters/abc'), fs = require('fs'), p = require('path'), spl = require('./converters/spl'), converters = { abc: abc, spl: spl }; function Playlist() { this.songs = []; } Playlist.prototype.load = function (dir) { var files = fs.readdirSync(dir), self = this; files.forEach(function (file) { console.log('Converting %s', file); var type = p.extname(file).replace(/^\./, ''), data = fs.readFileSync(p.join(dir, file)).toString(); if (converters[type]) { var song = converters[type].convert(data) self.songs.push(song); } else { console.error('Unable to convert %s', file); } }); }; Playlist.prototype.getSong = function (trackNumber) { return this.songs[trackNumber - 1]; }; module.exports = Playlist;
[Discord] Use string methods for encode and decode caesar functions To determine (in)valid characters to encode and decode
def encode_caesar(message, key): encoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
def encode_caesar(message, key): encoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
Change readme to md to match.
#!/usr/bin/env python from setuptools import setup, find_packages import re # get version from __init__.py INITFILE = "toytree/__init__.py" CUR_VERSION = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", open(INITFILE, "r").read(), re.M).group(1) # run setup setup( name="toytree", version=CUR_VERSION, url="https://github.com/eaton-lab/toytree", author="Deren Eaton", author_email="de2356@columbia.edu", description="minimalist tree plotting using toyplot", long_description=open('README.md').read(), long_description_content_type='text/x-rst', packages=find_packages(), install_requires=[ "toyplot", "numpy", "requests", "future", ], entry_points={}, license='GPL', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
#!/usr/bin/env python from setuptools import setup, find_packages import re # get version from __init__.py INITFILE = "toytree/__init__.py" CUR_VERSION = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", open(INITFILE, "r").read(), re.M).group(1) # run setup setup( name="toytree", version=CUR_VERSION, url="https://github.com/eaton-lab/toytree", author="Deren Eaton", author_email="de2356@columbia.edu", description="minimalist tree plotting using toyplot", long_description=open('README.rst').read(), long_description_content_type='text/x-rst', packages=find_packages(), install_requires=[ "toyplot", "numpy", "requests", "future", ], entry_points={}, license='GPL', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Fix lang entries on emailer sub_nav
<ul class="nav nav-pills"> <li <?php echo $this->uri->segment(4) == '' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer') ?>"><?php echo lang('bf_context_settings'); ?></a> </li> <li <?php echo $this->uri->segment(4) == 'template' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/template') ?>"><?php echo lang('em_email_template') ?></a> </li> <li <?php echo $this->uri->segment(4) == 'queue' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/queue') ?>"><?php echo lang('em_emailer_queue') ?></a> </li> <li <?php echo $this->uri->segment(4) == 'create' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/create')?>"><?php echo lang('em_create_email'); ?></a> </li> </ul>
<ul class="nav nav-pills"> <li <?php echo $this->uri->segment(4) == '' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer') ?>"><?php echo lang('bf_context_settings'); ?></a> </li> <li <?php echo $this->uri->segment(4) == 'template' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/template') ?>"><?php echo lang('template') ?></a> </li> <li <?php echo $this->uri->segment(4) == 'queue' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/queue') ?>"><?php echo lang('queue') ?></a> </li> <li <?php echo $this->uri->segment(4) == 'create' ? 'class="active"' : '' ?>> <a href="<?php echo site_url(SITE_AREA .'/settings/emailer/create')?>"><?php echo lang('em_create_email'); ?></a> </li> </ul>
Update use composer install of twitterOaUth
<?php require "vendor/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; require_once('twitterbotclass.php'); set_time_limit(0); ignore_user_abort(); function run($tweets){ global $bot; foreach($tweets->statuses as $tweet){ if(!$bot->inblacklist($tweet->user->id_str)){ if(rand(1,2) == 2){ $bot->retweet($tweet->id_str, $tweet->user->id_str); } else{ $bot->favorite($tweet->id_str, $tweet->user->id_str); $bot->retweet($tweet->id_str, $tweet->user->id_str); } $bot->follow($tweet->user->id_str); } sleep(60); } } $bot = new twitterbot; $bot->connect('', '', '', ''); $bot->addblacklist(array("1390693447", "558800766", "2198265000")); $bot->checkignore(array("ignore", "stop"), "You have been added to the ignore list. Any more problems? Contact https://twitter.com/jdf221"); $bot->action("run", $bot->search("#php OR #php5 OR #phpgd OR @phpstorm OR #phpdev")); ?>
<?php require_once('twitteroauth-master/twitteroauth/twitteroauth.php'); require_once('twitterbotclass.php'); set_time_limit(0); ignore_user_abort(); function run($tweets){ global $bot; foreach($tweets->statuses as $tweet){ if(!$bot->inblacklist($tweet->user->id_str)){ if(rand(1,2) == 2){ $bot->retweet($tweet->id_str, $tweet->user->id_str); } else{ $bot->favorite($tweet->id_str, $tweet->user->id_str); $bot->retweet($tweet->id_str, $tweet->user->id_str); } $bot->follow($tweet->user->id_str); } sleep(60); } } $bot = new twitterbot; $bot->connect('', '', '', ''); $bot->addblacklist(array("1390693447", "558800766", "2198265000")); $bot->checkignore(array("ignore", "stop"), "You have been added to the ignore list. Any more problems? Contact https://twitter.com/jdf221"); $bot->action("run", $bot->search("#php OR #php5 OR #phpgd OR @phpstorm OR #phpdev")); ?>
Fix secondary display toast placement on Android 11
/* Copyright 2017 Braden Farmer * * 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.farmerbb.taskbar.util; import android.annotation.SuppressLint; import android.content.Context; import android.view.Gravity; import android.widget.Toast; import com.farmerbb.taskbar.R; class ToastFrameworkImpl implements ToastInterface { private Toast toast; @SuppressLint("ShowToast") ToastFrameworkImpl(Context context, String message, int length) { int offset = context.getResources().getDimensionPixelSize(R.dimen.tb_toast_y_offset); if(U.getCurrentApiVersion() > 29.0 && U.isDesktopModeActive(context)) { offset = offset + U.getNavbarHeight(context); } toast = Toast.makeText(context, message, length); toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, offset); } @Override public void show() { toast.show(); } @Override public void cancel() { toast.cancel(); } }
/* Copyright 2017 Braden Farmer * * 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.farmerbb.taskbar.util; import android.annotation.SuppressLint; import android.content.Context; import android.view.Gravity; import android.widget.Toast; import com.farmerbb.taskbar.R; class ToastFrameworkImpl implements ToastInterface { private Toast toast; @SuppressLint("ShowToast") ToastFrameworkImpl(Context context, String message, int length) { toast = Toast.makeText(context, message, length); toast.setGravity( Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, context.getResources().getDimensionPixelSize(R.dimen.tb_toast_y_offset)); } @Override public void show() { toast.show(); } @Override public void cancel() { toast.cancel(); } }
Move construction method accessor to interface.
/* Copyright © 2016 Matthew Champion All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of mattunderscore.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mattunderscore.specky.model; import java.util.List; /** * @author Matt Champion on 11/06/2016 */ public interface TypeDesc { String getName(); List<PropertyDesc> getProperties(); ConstructionDesc getConstruction(); }
/* Copyright © 2016 Matthew Champion All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of mattunderscore.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mattunderscore.specky.model; import java.util.List; /** * @author Matt Champion on 11/06/2016 */ public interface TypeDesc { String getName(); List<PropertyDesc> getProperties(); }
Move API key to environment variable
from os import environ import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): try: key = environ['GOOGLE_MAPS_API_KEY'] except KeyError: self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY') self.client = googlemaps.Client(key=key) def test_roundtrip(self): r = driving_roundtrip(self.client, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary) if __name__ == "__main__": unittest.main()
import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): # TODO: Sane way to import key with open('/Users/nhc/git/pyrules/google-maps-api-key.txt') as f: self.key = f.read() def test_roundtrip(self): c = googlemaps.Client(key=self.key) r = driving_roundtrip(c, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary) if __name__ == "__main__": unittest.main()
Add logging to script test
from gevent import monkey monkey.patch_all() # noqa import sys import time from ethereum import slogging from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": slogging.configure(':DEBUG') with socket_factory('0.0.0.0', 8885) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if len(sys.argv) > 1: t.send(None, (sys.argv[1], 8885), b'hello')
from gevent import monkey monkey.patch_all() # noqa import sys import time from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": with socket_factory('0.0.0.0', 8885) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if len(sys.argv) > 1: t.send(None, (sys.argv[1], 8885), b'hello')