text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove unneccesary / in url conf
"""<project_name> URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('pages.urls')), ]
"""<project_name> URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^/', include('pages.urls')), ]
Add a pointer to the raw file for easier use and comparison
// From: https://raw.githubusercontent.com/chilts/umd-template/master/template.js ;(function (f) { // module name and requires var name = ''; var requires = []; // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f.apply(null, requires.map(function(r) { return require(r); })); // RequireJS } else if (typeof define === "function" && define.amd) { define(requires, f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // seee https://github.com/facebook/react/issues/3037 g = this; } g[name] = f.apply(null, requires.map(function(r) { return g[r]; })); } })(function () { // code return something; });
;(function (f) { // module name and requires var name = ''; var requires = []; // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f.apply(null, requires.map(function(r) { return require(r); })); // RequireJS } else if (typeof define === "function" && define.amd) { define(requires, f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // seee https://github.com/facebook/react/issues/3037 g = this; } g[name] = f.apply(null, requires.map(function(r) { return g[r]; })); } })(function () { // code return something; });
Include data file in package.
import setuptools import pathlib setuptools.setup( name='crafter', version='0.18.0', description='Open world survival game for reinforcement learning.', url='http://github.com/danijar/crafter', long_description=pathlib.Path('README.md').read_text(), long_description_content_type='text/markdown', packages=['crafter'], package_data={'crafter': ['data.yaml', 'assets/*']}, entry_points={'console_scripts': ['crafter=crafter.run_gui:main']}, install_requires=[ 'numpy', 'imageio', 'pillow', 'opensimplex', 'ruamel.yaml'], extras_require={'gui': ['pygame']}, classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Topic :: Games/Entertainment', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], )
import setuptools import pathlib setuptools.setup( name='crafter', version='0.17.0', description='Open world survival game for reinforcement learning.', url='http://github.com/danijar/crafter', long_description=pathlib.Path('README.md').read_text(), long_description_content_type='text/markdown', packages=['crafter'], package_data={'crafter': ['assets/*']}, entry_points={'console_scripts': ['crafter=crafter.run_gui:main']}, install_requires=[ 'numpy', 'imageio', 'pillow', 'opensimplex', 'ruamel.yaml'], extras_require={'gui': ['pygame']}, classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Topic :: Games/Entertainment', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], )
Add response types for controllers and an option to not include the header and footer.
<?php ob_start(); /** * Initialize some variables */ $view_data = array(); $title = ''; $description = ''; $css_files = array('header' => array(), 'footer' => array()); $js_files = array('header' => array(), 'footer' => array()); include('config.php'); include('routing.php'); require('functions.php'); // Load the controller $extra = include(__DIR__ . DIRECTORY_SEPARATOR . $controller); if(isset($extra['response_type'])){ switch($extra['response_type']) { case 'json': header('Content-type: application/json'); echo $extra['response']; break; case 'file': break; case 'html': // There should be a $view defined default: break; } } // Stop execution if there's no view if(empty($view)) { exit; } // Don't try to load a non existant view if(!is_file(__DIR__ . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "$view.php")) { $view = '404'; } if(isset($extra['no_header']) OR !$extra['no_header']) { include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."header.php"); } extract($view_data); include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."$view.php"); if(isset($extra['no_footer']) OR !$extra['no_footer']) { include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."footer.php"); } ob_end_flush();
<?php ob_start(); /** * Initialize some variables */ $view_data = array(); $title = ''; $description = ''; $css_files = array('header' => array(), 'footer' => array()); $js_files = array('header' => array(), 'footer' => array()); include('config.php'); include('routing.php'); require('functions.php'); // Load the controller include(__DIR__ . DIRECTORY_SEPARATOR . $controller); // Stop execution if there's no view if(empty($view)) { exit; } // Don't try to load a non existant view if(!is_file(__DIR__ . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "$view.php")) { $view = '404'; } include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."header.php"); extract($view_data); include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."$view.php"); include(__DIR__ . DIRECTORY_SEPARATOR ."views" . DIRECTORY_SEPARATOR ."footer.php"); ob_end_flush();
Add short, domain, fqdn flags like hostname command.
package main import ( "flag" "fmt" "net" "regexp" ) func revers(ip4 string, fqdn bool, short bool, domain bool) { Hostname, err := net.LookupAddr(ip4) if err == nil { switch { case domain: regE := regexp.MustCompile("^[^.]*[.](.*)[.]$") fmt.Printf("%s\n", regE.FindStringSubmatch(Hostname[0])[1]) case fqdn: regE := regexp.MustCompile("^(.*)[.]$") fmt.Printf("%s\n", regE.FindStringSubmatch(Hostname[0])[1]) default: regE := regexp.MustCompile("^([^.]*)") fmt.Printf("%s\n", regE.FindStringSubmatch(Hostname[0])[1]) } } } func main() { fqdnPtr := flag.Bool("f", false, "long host name (FQDN)") shortPtr := flag.Bool("s", false, "short host name") domainPtr := flag.Bool("d", false, "DNS domain name") flag.Parse() regS := regexp.MustCompile("[0-9.]*") interfaces, _ := net.Interfaces() for _, inter := range interfaces { if addrs, err := inter.Addrs(); err == nil { for _, addr := range addrs { monip := regS.FindString(addr.String()) if monip != "127.0.0.1" { revers(monip, *fqdnPtr, *shortPtr, *domainPtr) } } } } }
package main import ( "fmt" "net" "regexp" ) func revers(ip4 string) { regE := regexp.MustCompile("[-a-z0-9]*") Hostname, err := net.LookupAddr(ip4) if err == nil { fmt.Printf("%s\n", regE.FindString(Hostname[0])) } } func main() { regS := regexp.MustCompile("[0-9.]*") interfaces, _ := net.Interfaces() for _, inter := range interfaces { if addrs, err := inter.Addrs(); err == nil { for _, addr := range addrs { monip := regS.FindString(addr.String()) if monip != "127.0.0.1" { revers(monip) } } } } }
Set command description using translation key
<?php /** * @file * Contains \Drupal\AppConsole\Command\ContainerDebugCommand. */ namespace Drupal\AppConsole\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ContainerDebugCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('container:debug') ->setDescription($this->trans('command.container.debug.description')) ; } protected function execute(InputInterface $input, OutputInterface $output) { $services = $this->getServices(); $table = $this->getHelperSet()->get('table'); $table->setHeaders(['Service ID', 'Class name']); $table->setlayout($table::LAYOUT_COMPACT); foreach ($services as $serviceId) { $service = $this->getContainer()->get($serviceId); $class = get_class($service); $table->addRow([$serviceId, $class]); } $table->render($output); } }
<?php /** * @file * Contains \Drupal\AppConsole\Command\ContainerDebugCommand. */ namespace Drupal\AppConsole\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ContainerDebugCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('container:debug') ->setDescription('Displays current services for an application') ; } protected function execute(InputInterface $input, OutputInterface $output) { $services = $this->getServices(); $table = $this->getHelperSet()->get('table'); $table->setHeaders(['Service ID', 'Class name']); $table->setlayout($table::LAYOUT_COMPACT); foreach ($services as $serviceId) { $service = $this->getContainer()->get($serviceId); $class = get_class($service); $table->addRow([$serviceId, $class]); } $table->render($output); } }
Add support for connecting to NCBI database
import os import sys import time import math import sqlite3 from contextlib import contextmanager import meta @contextmanager def timeit_msg(msg): print '{}...'.format(msg), sys.stdout.flush() start = time.time() yield stop = time.time() print ' ({:1.3f} s)'.format((stop-start)) def get_file_size(fname): fstats = os.stat(fname) size = fstats.st_size exponent = int(math.log(size, 10)) divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9} if exponent < 3: res = 'B' if exponent >= 3 and exponent < 6: res = 'kB' elif exponent >= 6 and exponent < 9: res = 'MB' else: res = 'GB' return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res) def get_ncbi_db_conn(): dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db') conn = sqlite3.connect(dbfile) conn.text_factory = str return conn
import os import sys import time import math from contextlib import contextmanager @contextmanager def timeit_msg(msg): print '{}...'.format(msg), sys.stdout.flush() start = time.time() yield stop = time.time() print ' ({:1.3f} s)'.format((stop-start)) def get_file_size(fname): fstats = os.stat(fname) size = fstats.st_size exponent = int(math.log(size, 10)) divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9} if exponent < 3: res = 'B' if exponent >= 3 and exponent < 6: res = 'kB' elif exponent >= 6 and exponent < 9: res = 'MB' else: res = 'GB' return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django import template from djangosaml2.conf import config_settings_loader register = template.Library() class IdPListNode(template.Node): def __init__(self, variable_name): self.variable_name = variable_name def render(self, context): conf = config_settings_loader() context[self.variable_name] = conf.get_available_idps() return '' @register.tag def idplist(parser, token): try: tag_name, as_part, variable = token.split_contents() except ValueError: raise template.TemplateSyntaxError( '%r tag requires two arguments' % token.contents.split()[0]) if not as_part == 'as': raise template.TemplateSyntaxError( '%r tag first argument must be the literal "as"' % tag_name) return IdPListNode(variable)
# Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django import template from djangosaml2.conf import config_settings_loader register = template.Library() class IdPListNode(template.Node): def __init__(self, variable_name): self.variable_name = variable_name self.conf = config_settings_loader() def render(self, context): context[self.variable_name] = self.conf.get_available_idps() return '' @register.tag def idplist(parser, token): try: tag_name, as_part, variable = token.split_contents() except ValueError: raise template.TemplateSyntaxError( '%r tag requires two arguments' % token.contents.split()[0]) if not as_part == 'as': raise template.TemplateSyntaxError( '%r tag first argument must be the literal "as"' % tag_name) return IdPListNode(variable)
Allow items to have actions
import Ember from 'ember'; import layout from './template'; import Registerable from '../../mixins/registerable'; export default Ember.Component.extend(Registerable, { layout: layout, tagName: 'flood-item', attributeBindings: [ 'tabIndex:tabindex', 'disabled:aria-disabled', 'disabled:disabled', 'role', ], role: 'listitem', // disabled: false, tabIndex: Ember.computed('disabled', function() { return this.get('disabled') ? '-1' : '0'; }), label: null, classNameBindings: ['isSelected:is-selected', 'disabled'], isSelected: Ember.computed('parentComponent.selectedIndex', function() { let selectedItem = this.get('parentComponent.selectedItem'); if (selectedItem) { return selectedItem.get('elementId') === this.get('elementId'); }else{ return false; } }), focusIn(event) { var parent = this.get('parentComponent'); parent.focusItem(this); event.preventDefault(); }, click() { if (this.get('disabled')) { return; } var parent = this.get('parentComponent'); parent.selectItem(this); this.sendAction('action'); } });
import Ember from 'ember'; import layout from './template'; import Registerable from '../../mixins/registerable'; export default Ember.Component.extend(Registerable, { layout: layout, tagName: 'flood-item', attributeBindings: [ 'tabIndex:tabindex', 'disabled:aria-disabled', 'disabled:disabled', 'role', ], role: 'listitem', // disabled: false, tabIndex: Ember.computed('disabled', function() { return this.get('disabled') ? '-1' : '0'; }), label: null, classNameBindings: ['isSelected:is-selected', 'disabled'], isSelected: Ember.computed('parentComponent.selectedIndex', function() { let selectedItem = this.get('parentComponent.selectedItem'); if (selectedItem) { return selectedItem.get('elementId') === this.get('elementId'); }else{ return false; } }), focusIn(event) { var parent = this.get('parentComponent'); parent.focusItem(this); event.preventDefault(); }, click() { if (this.get('disabled')) { return; } var parent = this.get('parentComponent'); parent.selectItem(this); } });
Remove kerning adjustment from blank lines
var escape = require('escape-latex'); var quotes = require('../replace-quotes'); var preprocess = function(input) { return escape(quotes(input)); }; var blankLine = ( '{\\leavevmode \\vbox{\\hrule width5\\parindent}}' ); module.exports = function run(element, numberStyle, conspicuous) { if (typeof element === 'string') { if (conspicuous) { return '{\\bf\\it ' + preprocess(element) + '}'; } else { return preprocess(element); } } else if (element.hasOwnProperty('definition')) { return '``{\\bf ' + element.definition + '}\'\''; } else if (element.hasOwnProperty('blank')) { return blankLine + ' (' + preprocess(element.blank) + ')'; } else if (element.hasOwnProperty('reference')) { var reference = element.reference; if ( element.hasOwnProperty('broken') || element.hasOwnProperty('ambiguous') ) { return ( blankLine + ' (reference to ``' + preprocess(element.reference) + '\'\')' ); } else { return preprocess('Section ' + numberStyle(reference)); } } else { throw new Error('Invalid type: ' + JSON.stringify(element)); } };
var escape = require('escape-latex'); var quotes = require('../replace-quotes'); var preprocess = function(input) { return escape(quotes(input)); }; var blankLine = ( '{\\leavevmode \\kern.06em \\vbox{\\hrule width5\\parindent}}' ); module.exports = function run(element, numberStyle, conspicuous) { if (typeof element === 'string') { if (conspicuous) { return '{\\bf\\it ' + preprocess(element) + '}'; } else { return preprocess(element); } } else if (element.hasOwnProperty('definition')) { return '``{\\bf ' + element.definition + '}\'\''; } else if (element.hasOwnProperty('blank')) { return blankLine + ' (' + preprocess(element.blank) + ')'; } else if (element.hasOwnProperty('reference')) { var reference = element.reference; if ( element.hasOwnProperty('broken') || element.hasOwnProperty('ambiguous') ) { return ( blankLine + ' (reference to ``' + preprocess(element.reference) + '\'\')' ); } else { return preprocess('Section ' + numberStyle(reference)); } } else { throw new Error('Invalid type: ' + JSON.stringify(element)); } };
Implement saving and loading the observer tau
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0') base="/home/spb/data/Cosmo/Cosmo"+str(sim)+"_V6/L25n256" savedir="/home/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0') #halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir) halo = rs.RandSpectra(snapnum, base,numlos=10000,savedir=savedir, savefile="rand_spectra.hdf5") #halo.get_observer_tau("Si",2) halo.get_tau("H",1,1) #halo.get_col_density("Z",-1) #halo.get_col_density("H",-1) halo.save_file()
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0') base="/home/spb/data/Cosmo/Cosmo"+str(sim)+"_V6/L25n256" savedir="/home/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0') #halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir) halo = rs.RandSpectra(snapnum, base,numlos=3000,savedir=savedir, savefile="rand_spectra_DLA.hdf5") halo.get_tau("Si",2,2) halo.get_tau("H",1,1) halo.get_col_density("Z",-1) halo.get_col_density("H",-1) halo.save_file()
Move the open outside the try, since the finally is only needed once the file is successfully opened.
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) src = open(filename) try: imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) try: src = open(filename) imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
Change 'read-write' scope to 'read+write'.
from datetime import timedelta from django.conf import settings CONFIDENTIAL = 0 PUBLIC = 1 CLIENT_TYPES = ( (CONFIDENTIAL, "Confidential (Web applications)"), (PUBLIC, "Public (Native and JS applications)") ) RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token")) READ = 1 << 1 WRITE = 1 << 2 READ_WRITE = READ | WRITE DEFAULT_SCOPES = ( (READ, 'read'), (WRITE, 'write'), (READ_WRITE, 'read+write'), ) SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES) EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365)) EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60)) ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False) ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True) SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
from datetime import timedelta from django.conf import settings CONFIDENTIAL = 0 PUBLIC = 1 CLIENT_TYPES = ( (CONFIDENTIAL, "Confidential (Web applications)"), (PUBLIC, "Public (Native and JS applications)") ) RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token")) READ = 1 << 1 WRITE = 1 << 2 READ_WRITE = READ | WRITE DEFAULT_SCOPES = ( (READ, 'read'), (WRITE, 'write'), (READ_WRITE, 'read-write'), ) SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES) EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365)) EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60)) ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False) ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True) SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
Introduce triggerChange, use it on input/textarea change
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); }, 'change input, textarea': function() { this.triggerChange(); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, triggerChange: function() { if (this._skipTriggerChange) { return; } this.trigger('change'); }, enableTriggerChangeOnInput: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; this.triggerChange(); } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, enableTriggerChange: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
[UI] Allow all admins to view user profile
<?php declare(strict_types=1); /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ParkManager\UI\Web\Action\Admin\User; use ParkManager\Domain\User\User; use ParkManager\UI\Web\Response\TwigResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; final class ShowUserAction { /** * @Route( * path="/user/{user}/show", * methods={"GET", "HEAD"}, * name="park_manager.admin.show_user" * ) */ public function __invoke(Request $request, User $user): Response { return new TwigResponse('admin/user/show.html.twig', ['user' => $user]); } }
<?php declare(strict_types=1); /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ParkManager\UI\Web\Action\Admin\User; use ParkManager\Domain\User\User; use ParkManager\UI\Web\Response\TwigResponse; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; final class ShowUserAction { /** * @Security("is_granted('ROLE_SUPER_ADMIN')") * * @Route( * path="/user/{user}/show", * methods={"GET", "HEAD"}, * name="park_manager.admin.show_user" * ) */ public function __invoke(Request $request, User $user): Response { return new TwigResponse('admin/user/show.html.twig', ['user' => $user]); } }
Add notification count fields to the user table.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique()->nullable(); $table->string('password', 60); $table->string('avatar')->nullable(); $table->boolean('blocked')->default(false)->index(); $table->integer('topic_count')->default(0)->index(); $table->integer('reply_count')->default(0)->index(); $table->integer('notification_count')->default(0); $table->string('city')->nullable(); $table->string('website')->nullable(); $table->string('signature')->nullable(); $table->string('introduction')->nullable(); $table->rememberToken(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique()->nullable(); $table->string('password', 60); $table->string('avatar')->nullable(); $table->boolean('blocked')->default(false)->index(); $table->integer('topic_count')->default(0)->index(); $table->integer('reply_count')->default(0)->index(); $table->string('city')->nullable(); $table->string('website')->nullable(); $table->string('signature')->nullable(); $table->string('introduction')->nullable(); $table->rememberToken(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Allow users from phishing website to continue
'use strict'; angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, $sessionStorage, droitsDescription, $timeout, ABTestingService, phishingExpressions) { [ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) { $scope[type] = droitsDescription[type]; $scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) { return total + Object.keys(droitsDescription[type][provider].prestations).length; }, 0); }); ABTestingService.setABTestingEnvironment(); var referrer = document.referrer; if (referrer.match(/ameli\.fr/)) { $state.go('ameli'); } else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) { if (! $sessionStorage.phishingNoticationDone) { $sessionStorage.phishingNoticationDone = true; $state.go('hameconnage'); } } else { $timeout(function() { document.querySelector('#valueProposition a').focus(); }, 1500); } });
'use strict'; angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, droitsDescription, $timeout, ABTestingService, phishingExpressions) { [ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) { $scope[type] = droitsDescription[type]; $scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) { return total + Object.keys(droitsDescription[type][provider].prestations).length; }, 0); }); ABTestingService.setABTestingEnvironment(); var referrer = document.referrer; if (referrer.match(/ameli\.fr/)) { $state.go('ameli'); } else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) { $state.go('hameconnage'); } else { $timeout(function() { document.querySelector('#valueProposition a').focus(); }, 1500); } });
Add search links to tag cloud terms
angular.module('chronontology.components') .component('periodTypeTagCloud',{ templateUrl: '../../partials/period/type-tag-cloud.html', controller: function ($http, chronontologySettings) { this.tags = []; var ctrl = this; var uri = "/data/period/?size=0&facet=resource.types"; $http.get(uri).then( function success(result) { result.data.facets['resource.types'].buckets.forEach(function(bucket) { ctrl.tags.push({ text: bucket.key, weight: bucket.doc_count, link: "/search?q=&fq=types:\"" + bucket.key + "\"" }); }); }, function error(err) { console.warn(err); } ); } });
angular.module('chronontology.components') .component('periodTypeTagCloud',{ templateUrl: '../../partials/period/type-tag-cloud.html', controller: function ($http, chronontologySettings) { this.tags = []; var ctrl = this; var uri = "/data/period/?size=0&facet=resource.types"; $http.get(uri).then( function success(result) { result.data.facets['resource.types'].buckets.forEach(function(bucket) { ctrl.tags.push({text: bucket.key, weight: bucket.doc_count}); }); }, function error(err) { console.warn(err); } ); } });
Read textures from WebGL correctly encoding floats
// Read texture into Float array // // args: // r -- registration object // t -- texture to read // w -- width of buffer // h -- height of buffer function read_texture ( r, t, w, h ) { var gl = r.gl; var out = new Float32Array(3*w*h); for ( var index = 0; index < 3; index++ ) { var pixels = new Uint8Array(w*h * 4); gl.bindFramebuffer(gl.FRAMEBUFFER, r.framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, r.textures['encode'], 0); render ( r, r.programs["encode_float"], [ {name: "image", value: t}, {name: "index", value: index}, ]); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels); out.set(new Float32Array(pixels.buffer), index*w*h); } return out; }
// Read texture into Float array // // args: // r -- registration object // t -- texture to read // w -- width of buffer // h -- height of buffer function read_texture ( r, t, w, h ) { var gl = r.gl; var pixels = new Uint8Array(w*h * 4); var tempBuffer = create_texture(r, w, h); gl.bindFramebuffer(gl.FRAMEBUFFER, r.framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tempBuffer, 0); render ( r, r.programs["encode_float"], [ {name: "image", value: t}, ]); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels); pixels = new Float32Array(pixels.buffer); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteTexture(tempBuffer); return pixels; }
Disable the update server JSON test
import chai from 'chai'; import fetch from 'node-fetch'; import https from 'https'; chai.should(); describe('Update Server', () => { it('should be online', (done) => { https.get('https://update.gpmdp.xyz', () => done()) .on('error', () => done(new Error('Update server was unreachable'))); }); it.skip('should return JSON from the api URL', (done) => { fetch('https://update.gpmdp.xyz/api/versions') .then((resp) => resp.json()) .then((json) => { json.should.be.a('array'); json.length.should.be.at.least(4); // There should be at lest 4 versions done(); }) .catch(() => done(new Error('Failed to access the update server API'))); }); });
import chai from 'chai'; import fetch from 'node-fetch'; import https from 'https'; chai.should(); describe('Update Server', () => { it('should be online', (done) => { https.get('https://update.gpmdp.xyz', () => done()) .on('error', () => done(new Error('Update server was unreachable'))); }); it('should return JSON from the api URL', (done) => { fetch('https://update.gpmdp.xyz/api/versions') .then((resp) => resp.json()) .then((json) => { json.should.be.a('array'); json.length.should.be.at.least(4); // There should be at lest 4 versions done(); }) .catch(() => done(new Error('Failed to access the update server API'))); }); });
Initialize the correct variable in init
from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.process import MpdProcess class MpdFrontend(object): """ The MPD frontend. """ def __init__(self): self.process = None self.dispatcher = None def start_server(self, core_queue): """ Starts the MPD server. :param core_queue: the core queue :type core_queue: :class:`multiprocessing.Queue` """ self.process = MpdProcess(core_queue) self.process.start() def create_dispatcher(self, backend): """ Creates a dispatcher for MPD requests. :param backend: the backend :type backend: :class:`mopidy.backends.base.BaseBackend` :rtype: :class:`mopidy.frontends.mpd.dispatcher.MpdDispatcher` """ self.dispatcher = MpdDispatcher(backend) return self.dispatcher
from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.process import MpdProcess class MpdFrontend(object): """ The MPD frontend. """ def __init__(self): self.server = None self.dispatcher = None def start_server(self, core_queue): """ Starts the MPD server. :param core_queue: the core queue :type core_queue: :class:`multiprocessing.Queue` """ self.process = MpdProcess(core_queue) self.process.start() def create_dispatcher(self, backend): """ Creates a dispatcher for MPD requests. :param backend: the backend :type backend: :class:`mopidy.backends.base.BaseBackend` :rtype: :class:`mopidy.frontends.mpd.dispatcher.MpdDispatcher` """ self.dispatcher = MpdDispatcher(backend) return self.dispatcher
ApiHelper: Make HTTP status available on failure as well
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const AjaxHelper = require("helpers/ajax_helper"); const parseError = require("helpers/mrequest").unwrapErrorExtractMessage; const Dfr = require("jquery").Deferred; /** This helper parses data, etags, and errors for a convenient API */ function req(exec) { return Dfr(function ajax() { const success = (data, _s, xhr) => this.resolve(data, parseEtag(xhr), xhr.status); const failure = (xhr) => this.reject(parseError(xhr.responseJSON, xhr), xhr.status); exec().then(success, failure); }).promise(); } function parseEtag(req) { return (req.getResponseHeader("ETag") || "").replace(/--(gzip|deflate)/, ""); } const ApiHelper = {}; for (const key in AjaxHelper) { ApiHelper[key] = (config) => req(() => AjaxHelper[key](config)); } module.exports = ApiHelper;
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const AjaxHelper = require("helpers/ajax_helper"); const parseError = require("helpers/mrequest").unwrapErrorExtractMessage; const Dfr = require("jquery").Deferred; /** This helper parses data, etags, and errors for a convenient API */ function req(exec) { return Dfr(function ajax() { const success = (data, _s, xhr) => this.resolve(data, parseEtag(xhr), xhr.status); const failure = (xhr) => this.reject(parseError(xhr.responseJSON, xhr)); exec().then(success, failure); }).promise(); } function parseEtag(req) { return (req.getResponseHeader("ETag") || "").replace(/--(gzip|deflate)/, ""); } const ApiHelper = {}; for (const key in AjaxHelper) { ApiHelper[key] = (config) => req(() => AjaxHelper[key](config)); } module.exports = ApiHelper;
Remove booleanfield from example app for now We rather want a non required field for testing and should add a NullBooleanField anyway
from django.db import models import i18n from i18n.models import TranslatableModel class Document(TranslatableModel): untranslated_charfield = models.CharField(max_length=50, blank=True) charfield = i18n.LocalizedCharField(max_length=50) textfield = i18n.LocalizedTextField(max_length=500, blank=True) filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True) imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True) # booleanfield = i18n.LocalizedBooleanField() datefield = i18n.LocalizedDateField(blank=True, null=True) fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True, related_name='+') urlfied = i18n.LocalizedURLField(null=True, blank=True) decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2, null=True, blank=True) integerfield = i18n.LocalizedIntegerField(null=True, blank=True) def __str__(self): return '%d, %s' % (self.pk, self.charfield) class Meta: app_label = 'example'
from django.db import models import i18n from i18n.models import TranslatableModel class Document(TranslatableModel): untranslated_charfield = models.CharField(max_length=50, blank=True) charfield = i18n.LocalizedCharField(max_length=50) textfield = i18n.LocalizedTextField(max_length=500, blank=True) filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True) imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True) booleanfield = i18n.LocalizedBooleanField() datefield = i18n.LocalizedDateField(blank=True, null=True) fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True, related_name='+') urlfied = i18n.LocalizedURLField(null=True, blank=True) decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2, null=True, blank=True) integerfield = i18n.LocalizedIntegerField(null=True, blank=True) def __str__(self): return '%d, %s' % (self.pk, self.charfield) class Meta: app_label = 'example'
Use `ui.writeWarnLine` instead of `console.warn`.
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); var hasBeenWarned = false; module.exports = { name: 'ember-factory-for-polyfill', included: function() { this._ensureThisImport(); var checker = new VersionChecker(this); var emberVersion = checker.forEmber(); if (emberVersion.lt('2.12.0-beta.1')) { this.import('vendor/ember-factory-for-polyfill/index.js'); } else if (this.parent === this.project && !hasBeenWarned){ this.ui.writeWarnLine('ember-factory-for-polyfill is not required for Ember 2.12.0 and later, please remove from your `package.json`.'); hasBeenWarned = true; } }, _ensureThisImport: function() { if (!this.import) { this._findHost = function findHostShim() { var current = this; var app; do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); return app; }; this.import = function importShim(asset, options) { var app = this._findHost(); app.import(asset, options); }; } } };
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); var hasBeenWarned = false; module.exports = { name: 'ember-factory-for-polyfill', included: function() { this._ensureThisImport(); var checker = new VersionChecker(this); var emberVersion = checker.forEmber(); if (emberVersion.lt('2.12.0-beta.1')) { this.import('vendor/ember-factory-for-polyfill/index.js'); } else if (this.parent === this.project && !hasBeenWarned){ console.warn('ember-factory-for-polyfill is not required for Ember 2.12.0 and later, please remove from your `package.json`.'); hasBeenWarned = true; } }, _ensureThisImport: function() { if (!this.import) { this._findHost = function findHostShim() { var current = this; var app; do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); return app; }; this.import = function importShim(asset, options) { var app = this._findHost(); app.import(asset, options); }; } } };
Remove assertion in test that should not have made it in
""" Tests for staticsite.py - the static site generator """ import os.path import pytest from fantail.staticsite import StaticSite def test_init(tmpdir, caplog): # Verify path does not exist path = str(tmpdir.join('test-site')) assert not os.path.isdir(path) # Create the site site = StaticSite(path) site.init_site() # Verify directories have been created assert path == site.path assert os.path.isdir(path) assert 'Welcome from' in caplog.text() assert str(repr(site)) == '<StaticSite "' + path + '">' def test_dir_properties(tmpdir): path = str(tmpdir.join('test-site')) site = StaticSite(path) assert site.template_dir == os.path.join(path, 'templates') assert site.pages_dir == os.path.join(path, 'pages') assert site.output_dir == os.path.join(path, 'output') def test_site_clean(tmpdir, caplog): path = str(tmpdir.join('test-site')) site = StaticSite(path) # This should fail as init() was not called first with pytest.raises(SystemExit): site.clean_site() assert 'Site at ' + path + ' does not exist. Please' in caplog.text() site.init_site() # This should succeed now site.clean_site() assert 'Removed output directory from' in caplog.text()
""" Tests for staticsite.py - the static site generator """ import os.path import pytest from fantail.staticsite import StaticSite def test_init(tmpdir, caplog): # Verify path does not exist path = str(tmpdir.join('test-site')) assert not os.path.isdir(path) # Create the site site = StaticSite(path) site.init_site() # Verify directories have been created assert path == site.path assert os.path.isdir(path) assert os.path.isdir(os.path.join(path, 'output', '.git')) assert 'Welcome from' in caplog.text() assert str(repr(site)) == '<StaticSite "' + path + '">' def test_dir_properties(tmpdir): path = str(tmpdir.join('test-site')) site = StaticSite(path) assert site.template_dir == os.path.join(path, 'templates') assert site.pages_dir == os.path.join(path, 'pages') assert site.output_dir == os.path.join(path, 'output') def test_site_clean(tmpdir, caplog): path = str(tmpdir.join('test-site')) site = StaticSite(path) # This should fail as init() was not called first with pytest.raises(SystemExit): site.clean_site() assert 'Site at ' + path + ' does not exist. Please' in caplog.text() site.init_site() # This should succeed now site.clean_site() assert 'Removed output directory from' in caplog.text()
Change help text wording to follow WorkflowStateMixin
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_press_releases', '0008_auto_20161128_1049'), ] operations = [ migrations.AddField( model_name='pressreleaselisting', name='admin_notes', field=models.TextField(help_text=b"Administrator's notes about this content", blank=True), ), migrations.AddField( model_name='pressreleaselisting', name='brief', field=models.TextField(help_text=b'A document brief describing the purpose of this content', blank=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_press_releases', '0008_auto_20161128_1049'), ] operations = [ migrations.AddField( model_name='pressreleaselisting', name='admin_notes', field=models.TextField(help_text=b"Administrator's notes about this item", blank=True), ), migrations.AddField( model_name='pressreleaselisting', name='brief', field=models.TextField(help_text=b'A document brief describing the purpose of this item', blank=True), ), ]
Use str_pad() and dechex() instead of sprint() This is a micro-optimization that improves memory usage when generating large quantities of UUIDs. See #159 and #160.
<?php /** * This file is part of the ramsey/uuid library * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> * @license http://opensource.org/licenses/MIT MIT * @link https://benramsey.com/projects/ramsey-uuid/ Documentation * @link https://packagist.org/packages/ramsey/uuid Packagist * @link https://github.com/ramsey/uuid GitHub */ namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Provider\NodeProviderInterface; /** * RandomNodeProvider provides functionality to generate a random node ID, in * the event that the node ID could not be obtained from the host system * * @link http://tools.ietf.org/html/rfc4122#section-4.5 */ class RandomNodeProvider implements NodeProviderInterface { /** * Returns the system node ID * * @return string System node ID as a hexadecimal string */ public function getNode() { $node = hexdec(bin2hex(random_bytes(6))); // Set the multicast bit; see RFC 4122, section 4.5. $node = $node | 0x010000000000; return str_pad(dechex($node), 12, '0', STR_PAD_LEFT); } }
<?php /** * This file is part of the ramsey/uuid library * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> * @license http://opensource.org/licenses/MIT MIT * @link https://benramsey.com/projects/ramsey-uuid/ Documentation * @link https://packagist.org/packages/ramsey/uuid Packagist * @link https://github.com/ramsey/uuid GitHub */ namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Provider\NodeProviderInterface; /** * RandomNodeProvider provides functionality to generate a random node ID, in * the event that the node ID could not be obtained from the host system * * @link http://tools.ietf.org/html/rfc4122#section-4.5 */ class RandomNodeProvider implements NodeProviderInterface { /** * Returns the system node ID * * @return string System node ID as a hexadecimal string */ public function getNode() { $node = hexdec(bin2hex(random_bytes(6))); // Set the multicast bit; see RFC 4122, section 4.5. $node = $node | 0x010000000000; return sprintf('%012x', $node); } }
GS-8956: Allow extracting Processing Unit Containers from a Compound Processing Unit Container svn path=/trunk/openspaces/; revision=89106 Former-commit-id: acf333707ebb008757b03896f93f1d252dca2b62
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.pu.container.support; import org.openspaces.pu.container.CannotCloseContainerException; import org.openspaces.pu.container.ProcessingUnitContainer; /** * Compound processing unit container wraps several processing unit containers and * allows to close them. * * @author kimchy */ public class CompoundProcessingUnitContainer implements ProcessingUnitContainer { private final ProcessingUnitContainer[] containers; public CompoundProcessingUnitContainer(ProcessingUnitContainer[] containers) { this.containers = containers; } /** * @return the underlying processing unit containers. * @since 8.0.3 */ public ProcessingUnitContainer[] getProcessingUnitContainers() { return containers; } public void close() throws CannotCloseContainerException { for (ProcessingUnitContainer container : containers) { container.close(); } } }
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.pu.container.support; import org.openspaces.pu.container.CannotCloseContainerException; import org.openspaces.pu.container.ProcessingUnitContainer; /** * Compound processing unit container wraps several processing unit containers and * allows to close them. * * @author kimchy */ public class CompoundProcessingUnitContainer implements ProcessingUnitContainer { private ProcessingUnitContainer[] containers; public CompoundProcessingUnitContainer(ProcessingUnitContainer[] containers) { this.containers = containers; } public void close() throws CannotCloseContainerException { for (ProcessingUnitContainer container : containers) { container.close(); } } }
Use correct version of antiscroll in blueprint
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/Addepar/antiscroll.git#e0d1538cf4f3fd61c5bedd6168df86d651f125da' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
Fix a bug when res.threads is undefined
'use strict'; /** * @file Retrieve threads from the account */ var googleapis = require('googleapis'); // Retrieve all threads associated with this user account, // using refresh_token // starting from message #`cursor`. module.exports = function retrieveThreads(options, cursor, threads, cb) { options.q = "-is:chat after:" + cursor.date.getFullYear() + "/" + (cursor.date.getMonth() + 1) + "/" + cursor.date.getDate(); googleapis.gmail('v1').users.threads .list(options, function(err, res) { if(err) { return cb(err); } // We can't use a cursor in the query, so we need to do the sorting ourselves if(res.threads) { res.threads.reverse(); threads = threads.concat(res.threads.filter(function(thread) { return parseInt(thread.historyId, 16) > cursor.id; })); } if(res.nextPageToken) { options.pageToken = res.nextPageToken; retrieveThreads(options, cursor, threads, cb); } else { cb(null, { date: new Date((new Date()).getTime() - 1000 * 3600 * 24), id: threads.length > 0 ? parseInt(threads[threads.length - 1].historyId, 16) : cursor.id }, threads); } }); };
'use strict'; /** * @file Retrieve threads from the account */ var googleapis = require('googleapis'); // Retrieve all threads associated with this user account, // using refresh_token // starting from message #`cursor`. module.exports = function retrieveThreads(options, cursor, threads, cb) { options.q = "-is:chat after:" + cursor.date.getFullYear() + "/" + (cursor.date.getMonth() + 1) + "/" + cursor.date.getDate(); googleapis.gmail('v1').users.threads .list(options, function(err, res) { if(err) { return cb(err); } // We can't use a cursor in the query, so we need to do the sorting ourselves res.threads.reverse(); threads = threads.concat(res.threads.filter(function(thread) { return parseInt(thread.historyId, 16) > cursor.id; })); if(res.nextPageToken) { options.pageToken = res.nextPageToken; retrieveThreads(options, cursor, threads, cb); } else { cb(null, { date: new Date((new Date()).getTime() - 1000 * 3600 * 24), id: threads.length > 0 ? parseInt(threads[threads.length - 1].historyId, 16) : cursor.id }, threads); } }); };
Make sure PureComponents don't use context
import React, {Component, PropTypes} from 'react'; import {GithubAuthProvider} from 'firebase/auth'; const AnonymousUser = ({onSignIn}) => ( <div> <button onClick={onSignIn}>Sign In</button> </div> ); const AuthenticatedUser = ({user, onSignOut}) => ( <div> {user.displayName} <button onClick={onSignOut}>Sign Out</button> </div> ); export default class Auth extends Component { static contextTypes = { app: PropTypes.object.isRequired, user: PropTypes.object.isRequired, }; onSignIn = (e) => { e.preventDefault(); const auth = this.context.app.auth(); const provider = new GithubAuthProvider(); auth.signInWithRedirect(provider); } onSignOut = (e) => { e.preventDefault(); const auth = this.context.app.auth(); auth.signOut(); } render() { const {user} = this.context; if (user.isAnonymous) { return ( <AnonymousUser onSignIn={this.onSignIn}/> ); } return ( <AuthenticatedUser user={user} onSignOut={this.onSignOut} /> ); } };
import React, {PureComponent, PropTypes} from 'react'; import {GithubAuthProvider} from 'firebase/auth'; const AnonymousUser = ({onSignIn}) => ( <div> <button onClick={onSignIn}>Sign In</button> </div> ); const AuthenticatedUser = ({user, onSignOut}) => ( <div> {user.displayName} <button onClick={onSignOut}>Sign Out</button> </div> ); export default class Auth extends PureComponent { static contextTypes = { app: PropTypes.object.isRequired, user: PropTypes.object.isRequired, }; onSignIn = (e) => { e.preventDefault(); const auth = this.context.app.auth(); const provider = new GithubAuthProvider(); auth.signInWithRedirect(provider); } onSignOut = (e) => { e.preventDefault(); const auth = this.context.app.auth(); auth.signOut(); } render() { const {user} = this.context; if (user.isAnonymous) { return ( <AnonymousUser onSignIn={this.onSignIn}/> ); } return ( <AuthenticatedUser user={user} onSignOut={this.onSignOut} /> ); } };
Enable right content types (based on file types) in compare editor opened from Synchronization view
/******************************************************************************* * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bastian Doetsch implementation *******************************************************************************/ package com.vectrace.MercurialEclipse.synchronize; import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.team.core.TeamException; import org.eclipse.team.core.variants.IResourceVariant; import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision; public class MercurialResourceVariant implements IResourceVariant { private final IStorageMercurialRevision rev; public MercurialResourceVariant(IStorageMercurialRevision rev) { this.rev = rev; } public byte[] asBytes() { return getContentIdentifier().getBytes(); } public String getContentIdentifier() { return rev.getGlobal(); } public String getName() { return rev.getResource().getName(); } public IStorage getStorage(IProgressMonitor monitor) throws TeamException { return rev; } public boolean isContainer() { return false; } /** * @return the rev */ public IStorageMercurialRevision getRev() { return rev; } }
/******************************************************************************* * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bastian Doetsch implementation *******************************************************************************/ package com.vectrace.MercurialEclipse.synchronize; import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.team.core.TeamException; import org.eclipse.team.core.variants.IResourceVariant; import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision; public class MercurialResourceVariant implements IResourceVariant { private IStorageMercurialRevision rev; public MercurialResourceVariant(IStorageMercurialRevision rev) { this.rev = rev; } public byte[] asBytes() { return getContentIdentifier().getBytes(); } public String getContentIdentifier() { return rev.getGlobal(); } public String getName() { return rev.getName(); } public IStorage getStorage(IProgressMonitor monitor) throws TeamException { return rev; } public boolean isContainer() { return false; } /** * @return the rev */ public IStorageMercurialRevision getRev() { return rev; } }
Fix wrong return phpdoc value
<?php /** * @title Provider Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Payment / Gateway / Api * @version 1.0 */ namespace PH7\Framework\Payment\Gateway\Api; defined('PH7') or exit('Restricted access'); abstract class Provider { protected $aParams = array(); /** * @param string $sName * @param string $sValue * * @return self */ public function param($sName, $sValue) { $this->aParams[$sName] = $sValue; return $this; } /** * Generate Output. * * @return string HTML tags */ public function generate() { $sHtml = ''; // Default Value foreach ($this->aParams as $sKey => $sVal) $sHtml .= "<input type=\"hidden\" name=\"$sKey\" value=\"$sVal\" />\n"; return $sHtml; } }
<?php /** * @title Provider Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Payment / Gateway / Api * @version 1.0 */ namespace PH7\Framework\Payment\Gateway\Api; defined('PH7') or exit('Restricted access'); abstract class Provider { protected $aParams = array(); /** * @param string $sName * @param string $sValue * * @return object this */ public function param($sName, $sValue) { $this->aParams[$sName] = $sValue; return $this; } /** * Generate Output. * * @return string HTML tags */ public function generate() { $sHtml = ''; // Default Value foreach ($this->aParams as $sKey => $sVal) $sHtml .= "<input type=\"hidden\" name=\"$sKey\" value=\"$sVal\" />\n"; return $sHtml; } }
Add missing github field to Author serializer.
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
Make specific tweet endpoint adhere to API schema
const Tweet = require('../models/tweet') const config = require('../config') const mongoose = require('mongoose') const specificTweetsController = function (req, res) { res.set('Access-Control-Allow-Origin', '*') if (!req.params.name) { res.status(400).send('Invalid trend name') return } let query if (!req.query.max_id) { query = {trend: req.params.name} } else { var max_oid = mongoose.Types.ObjectId(req.query.max_id) query = {trend: req.params.name, _id: {$lt: max_oid}} } Tweet.find(query, (err, tweets) => { if (err) { res.status(500).send('Internal error while retreiving tweets') } else { let resData = {tweets: tweets} res.json(resData) } }).sort({_id: -1}).limit(config.tweetsPerRequest) } module.exports = specificTweetsController
const Tweet = require('../models/tweet') const config = require('../config') const mongoose = require('mongoose') const specificTweetsController = function (req, res) { res.set('Access-Control-Allow-Origin', '*') if (!req.params.name) { res.status(400).send('Invalid trend name') return } let query if (!req.query.max_id) { query = {trend: req.params.name} } else { var max_oid = mongoose.Types.ObjectId(req.query.max_id) query = {trend: req.params.name, _id: {$lt: max_oid}} } Tweet.find(query, (err, tweets) => { if (err) { res.status(500).send('Internal error while retreiving tweets') } else { res.type('application/json') res.send(tweets) } }).sort({_id: -1}).limit(config.tweetsPerRequest) } module.exports = specificTweetsController
Move message id generation to requestmanager
import json class Jsonrpc(object): def toPayload(self, reqid, method, params): """ Should be called to valid json create payload object """ if not method: raise Exception("jsonrpc method should be specified!") return json.dumps({ "jsonrpc": "2.0", "method": method, "params": params or [], "id": reqid }) def fromPayload(self, raw): result = json.loads(raw) if not Jsonrpc.isValidResponse(result): raise errors.InvalidResponse(result) return result def isValidResponse(self, response): """ Should be called to check if jsonrpc response is valid """ return response is not None and not response["error"] and \ response["jsonrpc"] == "2.0" and \ utils.isInteger(response["id"]) and \ response["result"] is not None # def toBatchPayload(self, messages): # return [self.toPayload(message["method"], message["params"]) for]
class Jsonrpc(object): def __init__(self): self.messageId = 0 @staticmethod def getInstance(): return Jsonrpc() def toPayload(self, method, params): """ Should be called to valid json create payload object """ if not method: raise Exception("jsonrpc method should be specified!") self.messageId += 1 return { "jsonrpc": "2.0", "method": method, "params": params or [], "id": self.messageId } def isValidResponse(self, response): """ Should be called to check if jsonrpc response is valid """ return response is not None and not response["error"] and \ response["jsonrpc"] == "2.0" and \ utils.isInteger(response["id"]) and \ response["result"] is not None def toBatchPayload(self, messages): return [self.toPayload(message["method"], message["params"]) for]
Remove explicit commit as Solr will do a soft-commit already
<?php class Asm_Solr_Model_Indexer_Cms extends Mage_Index_Model_Indexer_Abstract { protected function _construct() { $this->_init('solr/indexer_cms'); } /** * Get Indexer name * * @return string */ public function getName() { return Mage::helper('solr')->__('Solr CMS Search Index'); } /** * Get Indexer description * * @return string */ public function getDescription() { return Mage::helper('solr')->__('Rebuild Solr CMS search index'); } /** * Register indexer required data inside event object * * @param Mage_Index_Model_Event $event */ protected function _registerEvent(Mage_Index_Model_Event $event) { // TODO: Implement _registerEvent() method. } /** * Process event based on event state data * * @param Mage_Index_Model_Event $event */ protected function _processEvent(Mage_Index_Model_Event $event) { // TODO: Implement _processEvent() method. } public function reindexAll() { $resource = $this->_getResource(); $resource->rebuildIndex(); } }
<?php class Asm_Solr_Model_Indexer_Cms extends Mage_Index_Model_Indexer_Abstract { protected function _construct() { $this->_init('solr/indexer_cms'); } /** * Get Indexer name * * @return string */ public function getName() { return Mage::helper('solr')->__('Solr CMS Search Index'); } /** * Get Indexer description * * @return string */ public function getDescription() { return Mage::helper('solr')->__('Rebuild Solr CMS search index'); } /** * Register indexer required data inside event object * * @param Mage_Index_Model_Event $event */ protected function _registerEvent(Mage_Index_Model_Event $event) { // TODO: Implement _registerEvent() method. } /** * Process event based on event state data * * @param Mage_Index_Model_Event $event */ protected function _processEvent(Mage_Index_Model_Event $event) { // TODO: Implement _processEvent() method. } public function reindexAll() { $resource = $this->_getResource(); $resource->rebuildIndex(); $connection = Mage::helper('solr/connectionManager')->getConnection(); $connection->commit(); } }
Format by removing extra new line.
package processor import "github.com/materials-commons/mcstore/pkg/db/schema" // fileProcess defines an interface for processing different // types of files. Processing may include extracting data, // conversion of the file to a different type, or whatever // is deemed appropriate for the file type. type Processor interface { Process() error } // newFileProcessor creates a new instance of a fileProcessor. It looks at // the mime type for the file to determine what kind of processor it should // use to handle this file. By default it returns a processor that does // nothing to the file. func New(fileID string, mediatype schema.MediaType) Processor { switch mediatype.Mime { case "image/tiff": return newImageFileProcessor(fileID) case "image/bmp": return newImageFileProcessor(fileID) case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": return newSpreadsheetFileProcessor(fileID) case "application/vnd.MS-Excel": return newSpreadsheetFileProcessor(fileID) default: // Not a file type we process (yet) return &noopFileProcessor{} } }
package processor import "github.com/materials-commons/mcstore/pkg/db/schema" // fileProcess defines an interface for processing different // types of files. Processing may include extracting data, // conversion of the file to a different type, or whatever // is deemed appropriate for the file type. type Processor interface { Process() error } // newFileProcessor creates a new instance of a fileProcessor. It looks at // the mime type for the file to determine what kind of processor it should // use to handle this file. By default it returns a processor that does // nothing to the file. func New(fileID string, mediatype schema.MediaType) Processor { switch mediatype.Mime { case "image/tiff": return newImageFileProcessor(fileID) case "image/bmp": return newImageFileProcessor(fileID) case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": return newSpreadsheetFileProcessor(fileID) case "application/vnd.MS-Excel": return newSpreadsheetFileProcessor(fileID) default: // Not a file type we process (yet) return &noopFileProcessor{} } }
Use NodeJS environmental variables as configuration points for DB URL, user, and password values, rather than opening an external configuration file.
module.exports = function(app) { var mongoose = require('mongoose'); // require mongoose (for mongodb integration var db = require('./app_api/models/db'); // handles database connection open/close var routesApi = require('./app_api/routes/index'); app.use('/api', routesApi); // provide routes in API route index db(process.env.DB_URL, process.env.DB_USER, process.env.DB_PASS); // connect to database app.get('/api/hello', function(request, response) { // provide RESTful GET API at /hello response.send('Hello, World!'); // respond with string }); app.listen(process.env.PORT, process.env.IP); // try to open port/ip and try to use Cloud9 Port/IP if none specified console.log('API running!'); }
module.exports = function(app) { var mongoose = require('mongoose'); // require mongoose (for mongodb integration var fs = require('fs'); // necessary to read from files var db = require('./app_api/models/db'); // handles database connection open/close var routesApi = require('./app_api/routes/index'); app.use('/api', routesApi); // provide routes in API route index fs.readFile('.config', 'utf8', function(err,data){ if (err) { console.log(err); } else { var config = JSON.parse(data); // if read successful, parse JSON into object db(config.url, config.user, config.password); // connect to database app.get('/api/hello', function(request, response) { // provide RESTful GET API at /hello response.send('Hello, World!'); // respond with string }); app.listen(config.port || process.env.PORT, config.ip || process.env.IP); // try to open port/ip and try to use Cloud9 Port/IP if none specified console.log('API running!'); } }); }
Fix tagName selection for IE8
(function () { 'use strict'; moj.Modules.SubmitOnce = { el: '.js-SubmitOnce', init: function () { this.cacheEls(); this.bindEvents(); this.options = { alt: this.$el.data('alt') || 'Please wait…' }; }, cacheEls: function () { this.$el = $(this.el); this.$submit = this.$el.find('[type=submit], button'); }, bindEvents: function () { this.$el.on('submit', $.proxy(this.disable, this)); }, disable: function () { switch(this.$submit[0].tagName) { case 'INPUT': case 'BUTTON': this.$submit.val(this.options.alt); break; default: this.$submit.text(this.options.alt); } this.$submit.prop('disabled', true); } }; }());
(function () { 'use strict'; moj.Modules.SubmitOnce = { el: '.js-SubmitOnce', init: function () { this.cacheEls(); this.bindEvents(); this.options = { alt: this.$el.data('alt') || 'Please wait…' }; }, cacheEls: function () { this.$el = $(this.el); this.$submit = this.$el.find('[type=submit], button'); }, bindEvents: function () { this.$el.on('submit', $.proxy(this.disable, this)); }, disable: function () { this.$submit[this.$submit[0].tagName === 'INPUT' ? 'val' : 'text'](this.options.alt); this.$submit.prop('disabled', true); } }; }());
Use _.extend instead of Object.assign
var _ = require('lodash'); var fs = require('fs'); var archiver = require('./archiver'); var createServiceFile = require('./service'); var createSpecFile = require('./spec'); var files = require('./files'); function generateServiceFile(root, pkg) { var serviceFileContents = createServiceFile(pkg); var serviceFilePath = files.serviceFile(root, pkg); fs.writeFileSync(serviceFilePath, serviceFileContents); } function generateSpecFile(root, pkg, release) { var specFileContents = createSpecFile(pkg, release); var specFilePath = files.specFile(root, pkg); fs.writeFileSync(specFilePath, specFileContents); } function addCustomFieldsToPackage(pkg, customName) { if (customName) { return _.extend({}, pkg, { name: customName }); } return pkg; } module.exports = function (root, pkg, release, customName, cb) { var customPackage = addCustomFieldsToPackage(pkg, customName); var specsDirectory = files.specsDirectory(root); var sourcesDirectory = files.sourcesDirectory(root); var sourcesArchive = files.sourcesArchive(root, customPackage); fs.mkdirSync(specsDirectory); fs.mkdirSync(sourcesDirectory); generateServiceFile(root, customPackage); generateSpecFile(specsDirectory, customPackage, release); archiver.compress(root, sourcesArchive, cb); };
var fs = require('fs'); var archiver = require('./archiver'); var createServiceFile = require('./service'); var createSpecFile = require('./spec'); var files = require('./files'); function generateServiceFile(root, pkg) { var serviceFileContents = createServiceFile(pkg); var serviceFilePath = files.serviceFile(root, pkg); fs.writeFileSync(serviceFilePath, serviceFileContents); } function generateSpecFile(root, pkg, release) { var specFileContents = createSpecFile(pkg, release); var specFilePath = files.specFile(root, pkg); fs.writeFileSync(specFilePath, specFileContents); } function addCustomFieldsToPackage(pkg, customName) { if (customName) { return Object.assign({}, pkg, { name: customName }); } return pkg; } module.exports = function (root, pkg, release, customName, cb) { var customPackage = addCustomFieldsToPackage(pkg, customName); var specsDirectory = files.specsDirectory(root); var sourcesDirectory = files.sourcesDirectory(root); var sourcesArchive = files.sourcesArchive(root, customPackage); fs.mkdirSync(specsDirectory); fs.mkdirSync(sourcesDirectory); generateServiceFile(root, customPackage); generateSpecFile(specsDirectory, customPackage, release); archiver.compress(root, sourcesArchive, cb); };
Save datetime in JSON as ISO
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json,os from datetime import datetime from scrapy.exporters import JsonLinesItemExporter path = "downloads" class OnlineparticipationdatasetPipeline(object): def process_item(self, item, spider): return item class JsonWriterPipeline(object): def open_spider(self, spider): if not os.path.isdir(path): os.makedirs(path) self.file = open("downloads/items_"+spider.name+".json", 'wb') self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False) self.exporter.start_exporting() def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() def process_item(self, item, spider): item['date_time'] = item['date_time'].isoformat() self.exporter.export_item(item) return item
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json,os from datetime import datetime from scrapy.exporters import JsonLinesItemExporter path = "downloads" class OnlineparticipationdatasetPipeline(object): def process_item(self, item, spider): return item class JsonWriterPipeline(object): def open_spider(self, spider): if not os.path.isdir(path): os.makedirs(path) self.file = open("downloads/items_"+spider.name+".json", 'wb') self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False) self.exporter.start_exporting() def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() def process_item(self, item, spider): self.exporter.export_item(item) return item
Add Neil Fincham's Lighthouse server to the random rotation - lighthouseprojects.io Fixes issue #144.
package lighthouse; import com.google.common.collect.*; import java.util.*; /** * Hard-coded list of project servers so the app can randomly pick between them and load balance the work. */ public class ServerList { // This would be so much easier and less verbose with Kotlin ... public static class Entry { public final String hostName; public final String emailAddress; public Entry(String hostName, String emailAddress) { this.hostName = hostName; this.emailAddress = emailAddress; } } public static final List<Entry> servers = ImmutableList.of( new Entry("vinumeris.com", "project-hosting@vinumeris.com"), new Entry("lighthouse.onetapsw.com", "lighthouse-projects@onetapsw.com"), new Entry("lighthouseprojects.io", "projects@lighthouseprojects.io") ); public static final Map<String, Entry> hostnameToServer; static { ImmutableMap.Builder<String, Entry> builder = ImmutableMap.builder(); for (Entry server : servers) builder.put(server.hostName, server); hostnameToServer = builder.build(); } public static Entry pickRandom() { return servers.get((int) (Math.random() * servers.size())); } }
package lighthouse; import com.google.common.collect.*; import java.util.*; /** * Hard-coded list of project servers so the app can randomly pick between them and load balance the work. */ public class ServerList { // This would be so much easier and less verbose with Kotlin ... public static class Entry { public final String hostName; public final String emailAddress; public Entry(String hostName, String emailAddress) { this.hostName = hostName; this.emailAddress = emailAddress; } } public static final List<Entry> servers = ImmutableList.of( new Entry("vinumeris.com", "project-hosting@vinumeris.com"), new Entry("lighthouse.onetapsw.com", "lighthouse-projects@onetapsw.com") ); public static final Map<String, Entry> hostnameToServer; static { ImmutableMap.Builder<String, Entry> builder = ImmutableMap.builder(); for (Entry server : servers) builder.put(server.hostName, server); hostnameToServer = builder.build(); } public static Entry pickRandom() { return servers.get((int) (Math.random() * servers.size())); } }
Stop error messages (from TestPipedRDFIterators) appearing in the console output. git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1444626 13f79535-47bb-0310-9956-ffa450edef68
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.riot.lang; import org.apache.jena.atlas.junit.BaseTest ; import org.junit.AfterClass ; import org.junit.BeforeClass ; import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @RunWith(Suite.class) @Suite.SuiteClasses( { TestIRI.class , TestLang.class , TestNodeAllocator.class , TestTurtleTerms.class , TestLangNTriples.class , TestLangNQuads.class , TestLangTurtle.class , TestLangTrig.class , TestLangRdfJson.class , TestParserFactory.class , TestPipedRDFIterators.class }) public class TS_Lang { @BeforeClass public static void beforeClass() { BaseTest.setTestLogging() ; } @AfterClass public static void afterClass() { BaseTest.unsetTestLogging() ; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.riot.lang; import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @RunWith(Suite.class) @Suite.SuiteClasses( { TestIRI.class , TestLang.class , TestNodeAllocator.class , TestTurtleTerms.class , TestLangNTriples.class , TestLangNQuads.class , TestLangTurtle.class , TestLangTrig.class , TestLangRdfJson.class , TestParserFactory.class , TestPipedRDFIterators.class }) public class TS_Lang {}
Change login request to post
const LOGIN_URL = '/login' export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL'; export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'; export const USER_LOGOUT = 'USER_LOGOUT'; let userLogInSuccess = email => { console.log('In userLogInSuccess, email=', email) return { type: USER_LOGIN_SUCCESS, payload: email } } let userLoginFail = () => { return { type: USER_LOGIN_FAIL, payload: null } } export const doLogout = () => { return { type : USER_LOGOUT, payload : null } } export const doLogin = (email, password) => { return dispatch => { fetch(LOGIN_URL, { method : 'post' }) .then(response => { return response.json() }) .then(json => { console.log('/login json=', json) dispatch(userLogInSuccess(json['email'])) }) .catch(error => { dispatch(userLoginFail()) }) } }
const LOGIN_URL = '/login' export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL'; export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'; export const USER_LOGOUT = 'USER_LOGOUT'; let userLogInSuccess = email => { console.log('In userLogInSuccess, email=', email) return { type: USER_LOGIN_SUCCESS, payload: email } } let userLoginFail = () => { return { type: USER_LOGIN_FAIL, payload: null } } export const doLogout = () => { return { type : USER_LOGOUT, payload : null } } export const doLogin = (email, password) => { return dispatch => { fetch(LOGIN_URL, { method : 'get' }) .then(response => { return response.json() }) .then(json => { console.log('/login json=', json) dispatch(userLogInSuccess(json['email'])) }) .catch(error => { dispatch(userLoginFail()) }) } }
Replace deprecated login/logout function-based views
""" Map puzzle URLs to views. Also maps the root URL to the latest puzzle. """ from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
""" Map puzzle URLs to views. Also maps the root URL to the latest puzzle. """ from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Support deprecated use of the interface property of Bond.
# Copyright 2015 Internap. # # 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. import warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] @property def interface(self): warnings.warn('Deprecated: Use directly the members of Bond instead.', category=DeprecationWarning) return self
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or []
Set date format leniency to false.
package org.jreform.types; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.jreform.InputDataType; public final class DateType implements InputDataType<Date> { private DateFormat dateFormat; private DateType(String dateFormatPattern) { dateFormat = new SimpleDateFormat(dateFormatPattern); dateFormat.setLenient(false); } public Date parseValue(String value) { try { return dateFormat.parse(value); } catch(ParseException ex) { return null; } } public Class<Date> getType() { return Date.class; } public static InputDataType<Date> dateType(String dateFormatPattern) { return new DateType(dateFormatPattern); } }
package org.jreform.types; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.jreform.InputDataType; public final class DateType implements InputDataType<Date> { private DateFormat dateFormat; private DateType(String dateFormatPattern) { dateFormat = new SimpleDateFormat(dateFormatPattern); } // TODO: test the parseValue method - dateFormat sometimes doesn't // fail if the input string is "invalid" public Date parseValue(String value) { try { return dateFormat.parse(value); } catch(ParseException ex) { return null; } } public Class<Date> getType() { return Date.class; } public static InputDataType<Date> dateType(String dateFormatPattern) { return new DateType(dateFormatPattern); } }
Add in missing src to path. Add project root constant.
<?php /* * This file is part of the PhpJobQueue package. * * (c) Mark Fullbrook <mark.fullbrook@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require __DIR__.'/vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php'; require __DIR__.'/vendor/symfony/src/Symfony/Component/ClassLoader/DebugUniversalClassLoader.php'; $classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader(); $classLoader->registerNamespaces(array( 'PhpJobQueue' => __DIR__.'/lib', 'Symfony' => __DIR__.'/vendor/symfony/src', 'Predis' => __DIR__.'/vendor/predis/lib', 'Monolog' => __DIR__.'/vendor/monolog/src', )); $classLoader->register(); // enable Debug loader Symfony\Component\ClassLoader\DebugUniversalClassLoader::enable(); // define the root of the project define('PHPJOBQUEUE_ROOT', __DIR__);
<?php /* * This file is part of the PhpJobQueue package. * * (c) Mark Fullbrook <mark.fullbrook@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require __DIR__.'/vendor/symfony/Symfony/Component/ClassLoader/UniversalClassLoader.php'; require __DIR__.'/vendor/symfony/Symfony/Component/ClassLoader/DebugUniversalClassLoader.php'; $classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader(); $classLoader->registerNamespaces(array( 'PhpJobQueue' => __DIR__.'/lib', 'Symfony' => __DIR__.'/vendor/symfony/src', 'Predis' => __DIR__.'/vendor/predis/lib', 'Monolog' => __DIR__.'/vendor/monolog/src', )); $classLoader->register(); // enable Debug loader Symfony\Component\ClassLoader\DebugUniversalClassLoader::enable();
Extend the right TaxonomyChoiceType class
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\TaxonomiesBundle\Form\Type; use Sylius\Bundle\TaxonomiesBundle\Form\Type\TaxonomyChoiceType; /** * Taxonomy entity choice form. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class TaxonomyEntityChoiceType extends TaxonomyChoiceType { /** * {@inheritdoc} */ public function getParent() { return 'entity'; } /** * {@inheritdoc} */ public function getName() { return 'sylius_taxonomy_entity_choice'; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\TaxonomiesBundle\Form\Type; use Symfony\Component\Form\AbstractType; /** * Taxonomy entity choice form. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class TaxonomyEntityChoiceType extends AbstractType { /** * {@inheritdoc} */ public function getParent() { return 'entity'; } /** * {@inheritdoc} */ public function getName() { return 'sylius_taxonomy_entity_choice'; } }
Ch20: Use login_required decorator in URL pattern.
from django.conf.urls import url from django.contrib.auth.decorators import \ login_required from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', login_required( TagCreate.as_view()), name='organizer_tag_create'), url(r'^(?P<slug>[\w\-]+)/$', TagDetail.as_view(), name='organizer_tag_detail'), url(r'^(?P<slug>[\w-]+)/delete/$', TagDelete.as_view(), name='organizer_tag_delete'), url(r'^(?P<slug>[\w\-]+)/update/$', TagUpdate.as_view(), name='organizer_tag_update'), ]
from django.conf.urls import url from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', TagCreate.as_view(), name='organizer_tag_create'), url(r'^(?P<slug>[\w\-]+)/$', TagDetail.as_view(), name='organizer_tag_detail'), url(r'^(?P<slug>[\w-]+)/delete/$', TagDelete.as_view(), name='organizer_tag_delete'), url(r'^(?P<slug>[\w\-]+)/update/$', TagUpdate.as_view(), name='organizer_tag_update'), ]
Fix grammer within doc string example
"""This example demonstrates how to perform different kinds of redirects using hug""" import hug @hug.get() def sum_two_numbers(number_1: int, number_2: int): """I'll be redirecting to this using a variety of approaches below""" return number_1 + number_2 @hug.post() def internal_redirection_automatic(number_1: int, number_2: int): """This will redirect internally to the sum_two_numbers handler passing along all passed in parameters. This kind of redirect happens internally within hug, fully transparent to clients. """ print("Internal Redirection Automatic {}, {}".format(number_1, number_2)) return sum_two_numbers @hug.post() def internal_redirection_manual(number: int): """Instead of normal redirecting: You can manually call other handlers, with computed parameters and return their results """ print("Internal Redirection Manual {}".format(number)) return sum_two_numbers(number, number) @hug.post() def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None): """Hug also fully supports classical HTTP redirects, providing built in convenience functions for the most common types. """ print("HTTP Redirect {}".format(redirect_type)) if not redirect_type: hug.redirect.to("/sum_two_numbers") else: getattr(hug.redirect, redirect_type)("/sum_two_numbers")
"""This example demonstrates how to perform different kinds of redirects using hug""" import hug @hug.get() def sum_two_numbers(number_1: int, number_2: int): """I'll be redirecting to this using a variety of approaches below""" return number_1 + number_2 @hug.post() def internal_redirection_automatic(number_1: int, number_2: int): """This will redirect internally to the sum_two_numbers handler passing along all passed in parameters. Redirect happens within internally within hug, fully transparent to clients. """ print("Internal Redirection Automatic {}, {}".format(number_1, number_2)) return sum_two_numbers @hug.post() def internal_redirection_manual(number: int): """Instead of normal redirecting: You can manually call other handlers, with computed parameters and return their results """ print("Internal Redirection Manual {}".format(number)) return sum_two_numbers(number, number) @hug.post() def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None): """Hug also fully supports classical HTTP redirects, providing built in convenience functions for the most common types. """ print("HTTP Redirect {}".format(redirect_type)) if not redirect_type: hug.redirect.to("/sum_two_numbers") else: getattr(hug.redirect, redirect_type)("/sum_two_numbers")
Fix for Quantities not working with numpy.linspace() in numpy 1.11
from __future__ import absolute_import import quantities as pq # At least up to quantities 0.10.1 the additional arguments to the min and max # function did not get passed along. # A fix already exists: # <https://github.com/dopplershift/python-quantities/commit/30e8812ac15f551c65311d808c2a004f53913a25> # Also a pull request exists which has not been merged at the time of writing # 01/18/2013: # <https://github.com/python-quantities/python-quantities/pull/41> def _Quanitity_max(self, axis=None, out=None): return pq.Quantity( self.magnitude.max(axis, out), self.dimensionality, copy=False ) pq.Quantity.max = _Quanitity_max def _Quanitity_min(self, axis=None, out=None): return pq.Quantity( self.magnitude.min(axis, out), self.dimensionality, copy=False ) pq.Quantity.min = _Quanitity_min # Python quantities does not use have additional parameters for astype() # which became a problem in linspace in numpy 1.11. This is a dirty, dirty # hack to allow the Quantity astype function to accept any arguments and work # with numpy >= 1.11. A bug has been filed at # <https://github.com/python-quantities/python-quantities/issues/105> _original_astype = pq.Quantity.astype def _Quantity_astype(self, dtype=None, *args, **kwargs): return _original_astype(self, dtype) pq.Quantity.astype = _Quantity_astype
from __future__ import absolute_import import quantities as pq # At least up to quantities 0.10.1 the additional arguments to the min and max # function did not get passed along. # A fix already exists: # <https://github.com/dopplershift/python-quantities/commit/30e8812ac15f551c65311d808c2a004f53913a25> # Also a pull request exists which has not been merged at the time of writing # 01/18/2013: # <https://github.com/python-quantities/python-quantities/pull/41> def _Quanitity_max(self, axis=None, out=None): return pq.Quantity( self.magnitude.max(axis, out), self.dimensionality, copy=False ) pq.Quantity.max = _Quanitity_max def _Quanitity_min(self, axis=None, out=None): return pq.Quantity( self.magnitude.min(axis, out), self.dimensionality, copy=False ) pq.Quantity.min = _Quanitity_min
Modify mongo database server saved to .env
let SakuyaBot = require('./src/SakuyaBot') let SakuyaDb = require('./src/SakuyaDb') let Twitter = require('twitter') let TwitterClient = require('./src/TwitterClient') let FollowCrawler = require('./src/FollowingCrawler') let MongoDb = require('mongodb').Db let MongoServer = require('mongodb').Server // 環境変数よみこみ require('dotenv').config() // Twitter クライアントのinstance生成 let twitter = new Twitter ({ consumer_key: process.env.consumer_key, consumer_secret: process.env.consumer_secret, access_token_key: process.env.access_token_key, access_token_secret: process.env.access_token_secret }) let client = new TwitterClient(twitter) // DB instance生成 let server = new MongoServer(process.env.mongo_server, process.env.mongo_port) let db = new MongoDb(process.env.mongo_database, server, {safe: true}) let sdb = new SakuyaDb(db) let sakuyaBot = new SakuyaBot(client, sdb) sakuyaBot.start() let autoRemove = new FollowCrawler(client) autoRemove.start()
let SakuyaBot = require('./src/SakuyaBot') let SakuyaDb = require('./src/SakuyaDb') let Twitter = require('twitter') let TwitterClient = require('./src/TwitterClient') let FollowCrawler = require('./src/FollowingCrawler') let MongoDb = require('mongodb').Db let MongoServer = require('mongodb').Server // 環境変数よみこみ require('dotenv').config() // Twitter クライアントのinstance生成 let twitter = new Twitter ({ consumer_key: process.env.consumer_key, consumer_secret: process.env.consumer_secret, access_token_key: process.env.access_token_key, access_token_secret: process.env.access_token_secret }) let client = new TwitterClient(twitter) // DB instance生成 let server = new MongoServer('localhost', 27017) let db = new MongoDb('SakuyaBot', server, {safe: true}) let sdb = new SakuyaDb(db) let sakuyaBot = new SakuyaBot(client, sdb) sakuyaBot.start() let autoRemove = new FollowCrawler(client) autoRemove.start(5)
Add numpy as an install requirement.
from setuptools import find_packages, setup import versioneer setup( name="bmipy", version=versioneer.get_version(), description="Basic Model Interface for Python", author="Eric Hutton", author_email="huttone@colorado.edu", url="http://csdms.colorado.edu", classifiers=[ "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Scientific/Engineering :: Physics", ], setup_requires=["setuptools"], install_requires=["numpy"], packages=find_packages(), cmdclass=versioneer.get_cmdclass(), )
from setuptools import find_packages, setup import versioneer setup( name="bmipy", version=versioneer.get_version(), description="Basic Model Interface for Python", author="Eric Hutton", author_email="huttone@colorado.edu", url="http://csdms.colorado.edu", classifiers=[ "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Scientific/Engineering :: Physics", ], setup_requires=["setuptools"], packages=find_packages(), cmdclass=versioneer.get_cmdclass(), )
Fix crash if no MOTD exists.
package irc import ( "bufio" "fmt" "os" "sync" ) const ( motdHeader = "- %s Message of the day - " motdFooter = "- End of /MOTD command" ) var ( motdOnce sync.Once motd []string ) // sendMOTD will send the message of the day to a relay. func sendMOTD(state state, sink sink) { motdOnce.Do(func() { loadMOTD(state) }) sendNumericTrailing(state, sink, replyMOTDStart, fmt.Sprintf(motdHeader, state.getConfig().Name)) for _, line := range motd { sendNumericTrailing(state, sink, replyMOTD, "- "+line) } sendNumericTrailing(state, sink, replyEndOfMOTD, motdFooter) } func loadMOTD(state state) { motdFile := state.getConfig().MOTD if motdFile == "" || motd != nil { return } file, err := os.Open(motdFile) if err != nil { logf(warn, "Could not open MOTD: %v", err) return } scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) motd = make([]string, 0) for scanner.Scan() { motd = append(motd, scanner.Text()) } file.Close() }
package irc import ( "bufio" "fmt" "os" "sync" ) const ( motdHeader = "- %s Message of the day - " motdFooter = "- End of /MOTD command" ) var ( motdOnce sync.Once motd []string ) // sendMOTD will send the message of the day to a relay. func sendMOTD(state state, sink sink) { motdOnce.Do(func() { loadMOTD(state) }) sendNumericTrailing(state, sink, replyMOTDStart, fmt.Sprintf(motdHeader, state.getConfig().Name)) for _, line := range motd { sendNumericTrailing(state, sink, replyMOTD, "- "+line) } sendNumericTrailing(state, sink, replyEndOfMOTD, motdFooter) } func loadMOTD(state state) { motdFile := state.getConfig().MOTD if motdFile == "" || motd != nil { return } file, err := os.Open(motdFile) if err != nil { logf(warn, "Could not open MOTD: %v", err) } scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) motd = make([]string, 0) for scanner.Scan() { motd = append(motd, scanner.Text()) } file.Close() }
Fix excess reason condition wrapping
/*global app, me, client*/ "use strict"; var _ = require('underscore'); var HumanModel = require('human-model'); var logger = require('andlog'); module.exports = HumanModel.define({ type: 'call', initialize: function (attrs) { this.contact.onCall = true; }, session: { contact: 'object', jingleSession: 'object', state: ['string', true, 'inactive'], multiUser: ['boolean', true, false] }, end: function (reasonForEnding) { var reason = reasonForEnding || 'success'; this.contact.onCall = false; if (this.jingleSession) { this.jingleSession.end(reasonForEnding); } this.collection.remove(this); } });
/*global app, me, client*/ "use strict"; var _ = require('underscore'); var HumanModel = require('human-model'); var logger = require('andlog'); module.exports = HumanModel.define({ type: 'call', initialize: function (attrs) { this.contact.onCall = true; }, session: { contact: 'object', jingleSession: 'object', state: ['string', true, 'inactive'], multiUser: ['boolean', true, false] }, end: function (reasonForEnding) { var reason = reasonForEnding || 'success'; this.contact.onCall = false; if (this.jingleSession) { this.jingleSession.end({ condition: reason }); } this.collection.remove(this); } });
Add help text for program_end date. Fixes 1411.
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext from soc.models import linkable class Timeline(linkable.Linkable): """The Timeline Model, representing the timeline for a Program. """ program_start = db.DateTimeProperty( verbose_name=ugettext('Program Start date')) program_end = db.DateTimeProperty( verbose_name=ugettext('Program End date')) program_end.help_text = ugettext( 'After this date no data (such as profiles and forms) can be changed.') accepted_organization_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Organizations Announced Deadline')) student_signup_start = db.DateTimeProperty( verbose_name=ugettext('Student Signup Start date')) student_signup_end = db.DateTimeProperty( verbose_name=ugettext('Student Signup End date'))
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext from soc.models import linkable class Timeline(linkable.Linkable): """The Timeline Model, representing the timeline for a Program. """ program_start = db.DateTimeProperty( verbose_name=ugettext('Program Start date')) program_end = db.DateTimeProperty( verbose_name=ugettext('Program End date')) accepted_organization_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Organizations Announced Deadline')) student_signup_start = db.DateTimeProperty( verbose_name=ugettext('Student Signup Start date')) student_signup_end = db.DateTimeProperty( verbose_name=ugettext('Student Signup End date'))
Remove jspm scripts on build
const gulp = require('gulp'); const replace = require('gulp-replace'); const Builder = require('jspm').Builder; const conf = require('../conf/gulp.conf'); gulp.task('systemjs', systemjs); gulp.task('systemjs:html', updateIndexHtml); function systemjs(done) { const builder = new Builder('./', 'jspm.config.js'); builder.config({ paths: { "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, packageConfigPaths: [ 'npm:@*/*.json', 'npm:*.json', 'github:*/*.json' ] }); builder.buildStatic( <%- entry %>, conf.path.tmp('index.js') ).then(() => done(), done); } function updateIndexHtml() { return gulp.src(conf.path.src('index.html')) .pipe(replace( /<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/, `<script src="index.js"></script>` )) .pipe(gulp.dest(conf.path.tmp())); }
const gulp = require('gulp'); const replace = require('gulp-replace'); const Builder = require('jspm').Builder; const conf = require('../conf/gulp.conf'); gulp.task('systemjs', systemjs); gulp.task('systemjs:html', updateIndexHtml); function systemjs(done) { const builder = new Builder('./', 'jspm.config.js'); builder.config({ paths: { "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, packageConfigPaths: [ 'npm:@*/*.json', 'npm:*.json', 'github:*/*.json' ] }); builder.buildStatic( <%- entry %>, conf.path.tmp('index.js') ).then(() => done(), done); } function updateIndexHtml() { return gulp.src(conf.path.src('index.html')) .pipe(replace( /<script>\n\s*System.import.*\n\s*<\/script>/, `<script src="index.js"></script>` )) .pipe(gulp.dest(conf.path.tmp())); }
Use globals.json instead of conf.json
// tpl - a general purpose template cli // (c) 2011 Paul Vorbach. Licensed under MIT. ;(function() { var fs = require('fs'); var path = require('path'); var append = require('append'); var confdir = require('confdir'); module.exports = function (cb) { confdir(process.cwd(), 'pub', function(err, dir) { if (err) cb(err); else cb(null, { version: 'v0.0.1', add: exp('add', dir), mv: exp('mv', dir), rm: exp('rm', dir) }); }); }; function exp(cmd, confdir) { return function (files, opt) { var defaultOpt = { cwd: process.cwd() }; var confOpt; try { confOpt = JSON.parse(fs.readFileSync(path.resolve(confdir, 'globals.json'), 'utf8')); } catch (e) { confOpt = {}; } confOpt = append(defaultOpt, confOpt); opt = append(confOpt, opt); if (typeof files == 'string') files = [ files ]; require(path.resolve(confdir, cmd + '.js'))(files, opt); }; }; }).call(this);
// tpl - a general purpose template cli // (c) 2011 Paul Vorbach. Licensed under MIT. ;(function() { var fs = require('fs'); var path = require('path'); var append = require('append'); var confdir = require('confdir'); module.exports = function (cb) { confdir(process.cwd(), 'pub', function(err, dir) { if (err) cb(err); else cb(null, { version: 'v0.0.1', add: exp('add', dir), mv: exp('mv', dir), rm: exp('rm', dir) }); }); }; function exp(cmd, confdir) { return function (files, opt) { var defaultOpt = { cwd: process.cwd() }; var confOpt; try { confOpt = JSON.parse(fs.readFileSync(path.resolve(confdir, 'conf.json'), 'utf8')); } catch (e) { confOpt = {}; } confOpt = append(defaultOpt, confOpt); opt = append(confOpt, opt); if (typeof files == 'string') files = [ files ]; require(path.resolve(confdir, cmd + '.js'))(files, opt); }; }; }).call(this);
Fix issue with phpunit and sessions
<?php namespace Michaeljennings\Carpenter\Tests; use Michaeljennings\Carpenter\Carpenter; use PHPUnit_Framework_TestCase; class TestCase extends PHPUnit_Framework_TestCase { public function __construct() { // Fixes error with session_start() and phpunit ob_start(); } public function setUp() { // Fixes issues with session_start and phpunit @session_start(); } protected function makeCarpenter() { $config = $this->getConfig(); return new Carpenter($config); } protected function makeTable() { $carpenter = $this->makeCarpenter(); return $carpenter->make('test', function ($table) {}); } protected function getConfig() { return require __DIR__ . '/../config/config.php'; } }
<?php namespace Michaeljennings\Carpenter\Tests; use Michaeljennings\Carpenter\Carpenter; use PHPUnit_Framework_TestCase; class TestCase extends PHPUnit_Framework_TestCase { public function __construct() { // Fixes error with session_start() and phpunit ob_start(); } protected function makeCarpenter() { $config = $this->getConfig(); return new Carpenter($config); } protected function makeTable() { $carpenter = $this->makeCarpenter(); return $carpenter->make('test', function ($table) {}); } protected function getConfig() { return require __DIR__ . '/../config/config.php'; } }
Set scheduler to start at 8pm
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) @scheduler.scheduled_job(trigger='cron', hour=20, minute=0) def on_job(): """Start at 10:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=0, minute=1) def off_job(): """End at 12:01am PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) @scheduler.scheduled_job(trigger='cron', hour=22, minute=0) def on_job(): """Start at 10:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=0, minute=1) def off_job(): """End at 12:01am PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
Make sure we actually exit when we fail on startup
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exit(1); } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exitCode = 1; } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
Update dataProvider on BitField structure
<?php namespace Redtrine\Tests\Structure; use Redtrine\Tests\RedtrineTestCase; use Redtrine\Structure\BitField; class BitFieldTest extends RedtrineTestCase { /** * @var bitField */ protected $bit; public function setUp() { parent::setUp(); $this->bit = new BitField('TestBitField'); $this->bit->setClient($this->getRedisClient()); } /** * @dataProvider bitValues */ public function testToSetAndGetBitField($key, $value) { $this->bit->set($key, $value); $this->assertEquals($this->bit->get($key), $value); } public function bitValues() { return array( array(100,0), array(101,0), array(100,1), array(101,1), ); } }
<?php namespace Redtrine\Tests\Structure; use Redtrine\Tests\RedtrineTestCase; use Redtrine\Structure\BitField; class BitFieldTest extends RedtrineTestCase { /** * @var bitField */ protected $bit; public function setUp() { parent::setUp(); $this->bit = new BitField('TestBitField'); $this->bit->setClient($this->getRedisClient()); } /** * @dataProvider bitValues */ public function testToSetAndGetBitField($value) { $this->bit->set(100, $value); $this->assertEquals($this->bit->get(100), $value); } public function bitValues() { return array( array(0), array(1) ); } }
Insert request method option storage driver URLFor Docker-DCO-1.1-Signed-off-by: Josh Hawn <josh.hawn@docker.com> (github: jlhawn)
package storage import ( "net/http" "time" "github.com/docker/distribution" "github.com/docker/distribution/digest" ) // layerReader implements Layer and provides facilities for reading and // seeking. type layerReader struct { fileReader digest digest.Digest } var _ distribution.Layer = &layerReader{} func (lr *layerReader) Digest() digest.Digest { return lr.digest } func (lr *layerReader) Length() int64 { return lr.size } func (lr *layerReader) CreatedAt() time.Time { return lr.modtime } // Close the layer. Should be called when the resource is no longer needed. func (lr *layerReader) Close() error { return lr.closeWithErr(distribution.ErrLayerClosed) } func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Docker-Content-Digest", lr.digest.String()) if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{"method": r.Method}); err == nil { http.Redirect(w, r, url, http.StatusTemporaryRedirect) } http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr) }
package storage import ( "net/http" "time" "github.com/docker/distribution" "github.com/docker/distribution/digest" ) // layerReader implements Layer and provides facilities for reading and // seeking. type layerReader struct { fileReader digest digest.Digest } var _ distribution.Layer = &layerReader{} func (lr *layerReader) Digest() digest.Digest { return lr.digest } func (lr *layerReader) Length() int64 { return lr.size } func (lr *layerReader) CreatedAt() time.Time { return lr.modtime } // Close the layer. Should be called when the resource is no longer needed. func (lr *layerReader) Close() error { return lr.closeWithErr(distribution.ErrLayerClosed) } func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Docker-Content-Digest", lr.digest.String()) if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{}); err == nil { http.Redirect(w, r, url, http.StatusTemporaryRedirect) } http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr) }
Set locale/timezone correctly when in format
import moment from 'moment-timezone'; import AbstractFormat from './abstract'; export default class DateFormat extends AbstractFormat { format(dateValue, dateFormat, locale, timezone) { locale = locale || this._locale; timezone = timezone || this._timezone; return this .moment(dateValue, locale, timezone) .format(dateFormat); } moment(dateValue, locale, timezone) { locale = locale || this._locale; timezone = timezone || this._timezone; return moment(dateValue) .locale(locale) .tz(timezone); } parse(dateValue, dateFormat, locale, timezone) { locale = locale || this._locale; timezone = timezone || this._timezone; const result = moment.tz( dateValue, dateFormat, locale, true, timezone ); return result.isValid() === true ? result.toDate() : null; } }
import moment from 'moment-timezone'; import AbstractFormat from './abstract'; export default class DateFormat extends AbstractFormat { format(dateValue, dateFormat, locale, timezone) { return this .moment(dateValue, locale, timezone) .format(dateFormat); } moment(dateValue, locale, timezone) { return moment(dateValue) .locale(locale || this._locale) .tz(timezone || this._timezone); } parse(dateValue, dateFormat, locale, timezone) { const result = moment.tz( dateValue, dateFormat, locale || this._locale, true, timezone || this._timezone ); return result.isValid() === true ? result.toDate() : null; } }
Fix initial state of list subscribers table
import React, { PropTypes } from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import BSTyle from 'react-bootstrap-table/dist/react-bootstrap-table.min.css'; export default class ManageSubscribersTable extends React.Component { constructor(props) { super(props); this.state = { data: this.props.data || [] }; } static propTypes = { data: PropTypes.array.isRequired } componentWillReceiveProps(newProps) { this.setState({ data: newProps.data }) } formatFieldSubscribed(subscribed) { // this is a placeholder for now, since we are not yet handling // user subscription state return '<span class="label label-success">Subscribed</span>' } render() { return ( <BootstrapTable data={this.state.data} pagination={true} hover={true}> <TableHeaderColumn dataField="id" hidden={true} isKey={true}>id</TableHeaderColumn> <TableHeaderColumn dataField="email">email</TableHeaderColumn> <TableHeaderColumn dataField="subscribed" dataFormat={this.formatFieldSubscribed}>status</TableHeaderColumn> </BootstrapTable> ); } }
import React, { PropTypes } from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import BSTyle from 'react-bootstrap-table/dist/react-bootstrap-table.min.css'; export default class ManageSubscribersTable extends React.Component { constructor(props) { super(props); this.state = { data: this.props.data }; } static propTypes = { data: PropTypes.array.isRequired } componentWillReceiveProps(newProps) { this.setState({ data: newProps.data }) } formatFieldSubscribed(subscribed) { // this is a placeholder for now, since we are not yet handling // user subscription state return '<span class="label label-success">Subscribed</span>' } render() { return ( <BootstrapTable data={this.props.data} pagination={true} hover={true}> <TableHeaderColumn dataField="id" hidden={true} isKey={true}>id</TableHeaderColumn> <TableHeaderColumn dataField="email">email</TableHeaderColumn> <TableHeaderColumn dataField="subscribed" dataFormat={this.formatFieldSubscribed}>status</TableHeaderColumn> </BootstrapTable> ); } }
Add static field for texture in basic energy creator
package info.u_team.u_team_test.screen; import info.u_team.u_team_core.gui.elements.EnergyStorageWidget; import info.u_team.u_team_core.screen.UBasicContainerScreen; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.container.BasicEnergyCreatorContainer; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraftforge.api.distmarker.*; import net.minecraftforge.energy.CapabilityEnergy; @OnlyIn(Dist.CLIENT) public class BasicEnergyCreatorScreen extends UBasicContainerScreen<BasicEnergyCreatorContainer> { private static final ResourceLocation BACKGROUND = new ResourceLocation(TestMod.MODID, "textures/gui/energy_creator.png"); public BasicEnergyCreatorScreen(BasicEnergyCreatorContainer container, PlayerInventory playerInventory, ITextComponent title) { super(container, playerInventory, title, BACKGROUND, 176, 173); } @Override protected void func_231160_c_() { super.func_231160_c_(); func_230480_a_(new EnergyStorageWidget(guiLeft + 9, guiTop + 20, 54, container.getTileEntity().getCapability(CapabilityEnergy.ENERGY))); } }
package info.u_team.u_team_test.screen; import info.u_team.u_team_core.gui.elements.EnergyStorageWidget; import info.u_team.u_team_core.screen.UBasicContainerScreen; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.container.BasicEnergyCreatorContainer; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraftforge.api.distmarker.*; import net.minecraftforge.energy.CapabilityEnergy; @OnlyIn(Dist.CLIENT) public class BasicEnergyCreatorScreen extends UBasicContainerScreen<BasicEnergyCreatorContainer> { public BasicEnergyCreatorScreen(BasicEnergyCreatorContainer container, PlayerInventory playerInventory, ITextComponent title) { super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/energy_creator.png"), 176, 173); } @Override protected void func_231160_c_() { super.func_231160_c_(); func_230480_a_(new EnergyStorageWidget(guiLeft + 9, guiTop + 20, 54, container.getTileEntity().getCapability(CapabilityEnergy.ENERGY))); } }
Remove unnescessary routes from registration parameters
'use strict'; require('css/registrations.css'); var ko = require('knockout'); var $ = require('jquery'); var $osf = require('js/osfHelpers'); var RegistrationManager = require('js/registrationUtils').RegistrationManager; var ctx = window.contextVars; var node = window.contextVars.node; $(document).ready(function() { $('#registrationsTabs').tab(); $('#registrationsTabs a').click(function (e) { e.preventDefault(); $(this).tab('show'); }); var draftManager = new RegistrationManager(node, '#draftRegistrationScope', { list: node.urls.api + 'draft/', // TODO: uncomment when we support draft submission for review //submit: node.urls.api + 'draft/{draft_pk}/submit/', delete: node.urls.api + 'draft/{draft_pk}/', schemas: '/api/v1/project/schema/', edit: node.urls.web + 'draft/{draft_pk}/' }); draftManager.init(); $('#registerNode').click(function(event) { event.preventDefault(); draftManager.beforeCreateDraft(); }); });
'use strict'; require('css/registrations.css'); var ko = require('knockout'); var $ = require('jquery'); var $osf = require('js/osfHelpers'); var RegistrationManager = require('js/registrationUtils').RegistrationManager; var ctx = window.contextVars; var node = window.contextVars.node; $(document).ready(function() { $('#registrationsTabs').tab(); $('#registrationsTabs a').click(function (e) { e.preventDefault(); $(this).tab('show'); }); var draftManager = new RegistrationManager(node, '#draftRegistrationScope', { list: node.urls.api + 'draft/', submit: node.urls.api + 'draft/{draft_pk}/submit/', get: node.urls.api + 'draft/{draft_pk}/', delete: node.urls.api + 'draft/{draft_pk}/', schemas: '/api/v1/project/schema/', edit: node.urls.web + 'draft/{draft_pk}/' }); draftManager.init(); $('#registerNode').click(function(event) { event.preventDefault(); draftManager.beforeCreateDraft(); }); });
Improve equalizer fixes: avoid flickering
import $ from 'jquery'; import * as _ from 'lodash'; /** * data-equalizer-ignore-class takes a string of classes that should be applied to an element that * uses data-equalizer-watch, but which should be ignored while the height calculations are being * performed. */ $('[data-equalizer-ignore-class]').each((index, element) => { 'use strict'; const $targetElement = $(element); const equalizerId = $targetElement.data('equalizer-watch'); const $equalizerContainer = $targetElement.closest('[data-equalizer="' + equalizerId + '"]'); const equalizerIgnoreClasses = $targetElement.data('equalizer-ignore-class'); const _addIgnoredClassesDebounced = _.debounce(_addIgnoredClasses, 250); let calculationsInProgress = 0; $equalizerContainer.on('preequalizedrow.zf.equalizer', (event) => { calculationsInProgress++; $targetElement.removeClass(equalizerIgnoreClasses); }); $equalizerContainer.on('postequalizedrow.zf.equalizer', (event) => { calculationsInProgress--; // Timeout appears to be needed, otherwise height calculation still includes the classes // that are supposed to be ignored. setTimeout(() => { if (calculationsInProgress < 1) { calculationsInProgress = 0; _addIgnoredClassesDebounced(); } }); }); $targetElement.addClass(equalizerIgnoreClasses); function _addIgnoredClasses() { $targetElement.addClass(equalizerIgnoreClasses); } });
import $ from 'jquery'; /** * data-equalizer-ignore-class takes a string of classes that should be applied to an element that * uses data-equalizer-watch, but which should be ignored while the height calculations are being * performed. */ $('[data-equalizer-ignore-class]').each((index, element) => { 'use strict'; const $targetElement = $(element); const equalizerId = $targetElement.data('equalizer-watch'); const $equalizerContainer = $targetElement.closest('[data-equalizer="' + equalizerId + '"]'); const equalizerIgnoreClasses = $targetElement.data('equalizer-ignore-class'); let calculationInProgress = false; $equalizerContainer.on('preequalizedrow.zf.equalizer', (event) => { calculationInProgress = true; $targetElement.removeClass(equalizerIgnoreClasses); }); $equalizerContainer.on('postequalizedrow.zf.equalizer', (event) => { calculationInProgress = false; // Timeout appears to be needed, otherwise height calculation still includes the classes // that are supposed to be ignored. setTimeout(() => { if (!calculationInProgress) { $targetElement.addClass(equalizerIgnoreClasses); } }); }); $targetElement.addClass(equalizerIgnoreClasses); });
Make jsdoc the default task
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('default', ['jsdoc']); gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
Revoke starting player from the board.
package game; import static com.google.common.base.Preconditions.checkArgument; import java.util.Optional; /** * Created by Dimitry on 14.05.2016. */ public class Board { private final int numberOfRows; private final int numberOfColumns; private Player[][] occupiers; public Board(final int numberOfRows, final int numberOfColumns) { this.numberOfRows = numberOfRows; this.numberOfColumns = numberOfColumns; occupiers = new Player[numberOfRows][numberOfColumns]; } public Optional<Player> slotOwner(final int row, final int column) { if (occupiers[row][column] == null) { return Optional.empty(); } else { return Optional.of(occupiers[row][column]); } } public void insertChip(final int columnNumber, final Player player) { int index = numberOfRows - 1; while (index >= 0 && occupiers[index][columnNumber] != null) { index--; } checkArgument(index >= 0); occupiers[index][columnNumber] = player; } public int getNumberOfRows() { return numberOfRows; } public int getNumberOfColumns() { return numberOfColumns; } }
package game; import static com.google.common.base.Preconditions.checkArgument; import java.util.Optional; /** * Created by Dimitry on 14.05.2016. */ public class Board { private Player startingPlayer; private final int numberOfRows; private final int numberOfColumns; private Player[][] occupiers; public Board(final int numberOfRows, final int numberOfColumns) { this.numberOfRows = numberOfRows; this.numberOfColumns = numberOfColumns; occupiers = new Player[numberOfRows][numberOfColumns]; } public Optional<Player> slotOwner(final int row, final int column) { if (occupiers[row][column] == null) { return Optional.empty(); } else { return Optional.of(occupiers[row][column]); } } public void insertChip(final int columnNumber, final Player player) { int index = numberOfRows - 1; while (index >= 0 && occupiers[index][columnNumber] != null) { index--; } checkArgument(index >= 0); occupiers[index][columnNumber] = player; } public int getNumberOfRows() { return numberOfRows; } public int getNumberOfColumns() { return numberOfColumns; } public void setStartingPlayer(final Player player) { this.startingPlayer = player; } public Player getStartingPlayer() { return startingPlayer; } }
MP3: Replace hardcoded names with tracklist
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
#!/usr/bin/python3 import ID3 import os import sys mp3_extension = ".mp3" names = ["final_name_1", "final_name_2", "final_name_3"] files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(names): raise RuntimeError( str(len(names)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, names[i] + mp3_extension) i += 1
Add fix for null images
import Ember from 'ember'; export default Ember.Object.extend({ posterDefaultSize: 2, posterUrl: function() { var posterPath = this.get('poster_path'); var config = this.get('tmdbConfig'); if (posterPath === undefined || posterPath === null) { return 'https://d3a8mw37cqal2z.cloudfront.net/assets/f996aa2014d2ffddfda8463c479898a3/images/no-poster-w185.jpg'; } else { var posterSizes = config.get('images.poster_sizes'); var baseUrl = config.get('images.base_url'); var posterDefaultSize = this.get('posterDefaultSize'); return baseUrl + posterSizes[posterDefaultSize] + posterPath; } }.property('poster_path'), backdropDefaultSize: 2, backdropUrl: function() { var backdropPath = this.get('backdrop_path'); var config = this.get('tmdbConfig'); if (backdropPath === undefined || backdropPath === null) { return ''; } else { var backdropSizes = config.get('images.backdrop_sizes'); var baseUrl = config.get('images.base_url'); var backdropDefaultSize = this.get('backdropDefaultSize'); return baseUrl + backdropSizes[backdropDefaultSize] + backdropPath; } }.property('backdrop_path') });
import Ember from 'ember'; export default Ember.Object.extend({ posterDefaultSize: 2, posterUrl: function() { var posterPath = this.get('poster_path'); var config = this.get('tmdbConfig'); console.log('config',this,config); if (posterPath === undefined) { return 'https://d3a8mw37cqal2z.cloudfront.net/assets/f996aa2014d2ffddfda8463c479898a3/images/no-poster-w185.jpg'; } var posterSizes = config.get('images.poster_sizes'); var baseUrl = config.get('images.base_url'); var posterDefaultSize = this.get('posterDefaultSize'); return baseUrl + posterSizes[posterDefaultSize] + posterPath; }.property('poster_path'), backdropDefaultSize: 2, backdropUrl: function() { var backdropPath = this.get('backdrop_path'); var config = this.get('tmdbConfig'); console.log('config',config); if (backdropPath === undefined) { return ''; } var backdropSizes = config.get('images.backdrop_sizes'); var baseUrl = config.get('images.base_url'); var backdropDefaultSize = this.get('backdropDefaultSize'); return baseUrl + backdropSizes[backdropDefaultSize] + backdropPath; }.property('backdrop_path') });
Add gradient background to GraphScheme
# -*- coding: utf-8 -*- from PySide import QtGui, QtCore class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super(GraphScheme, self).__init__() self.layout = QtGui.QGraphicsGridLayout() self.form = QtGui.QGraphicsWidget() self.form.setLayout(self.layout) self.addItem(self.form) self.form.setPos(0, 0) gradient = QtGui.QLinearGradient(0, 0, 0, 4000) gradient.setColorAt( 0, QtGui.QColor(255, 255, 255)) gradient.setColorAt( 1, QtGui.QColor(0, 0, 255)) self.setBackgroundBrush(gradient) def add_block(self, block, row, column): """ Add GraphBlock to scheme into specified row and column """ self.layout.addItem(block, row, column)
# -*- coding: utf-8 -*- from PySide import QtGui class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super(GraphScheme, self).__init__() self.layout = QtGui.QGraphicsGridLayout() self.form = QtGui.QGraphicsWidget() self.form.setLayout(self.layout) self.addItem(self.form) self.form.setPos(0, 0) def add_block(self, block, row, column): """ Add GraphBlock to scheme into specified row and column """ self.layout.addItem(block, row, column)
Add case_sharing to saved_app view so that the case sharing warning will work
function(doc){ if((doc.doc_type == 'Application' || doc.doc_type == 'RemoteApp') && doc.copy_of != null) { emit([doc.domain, doc.copy_of, doc.version], { doc_type: doc.doc_type, short_url: doc.short_url, version: doc.version, _id: doc._id, name: doc.name, build_spec: doc.build_spec, copy_of: doc.copy_of, domain: doc.domain, built_on: doc.built_on, built_with: doc.built_with, build_comment: doc.build_comment, is_released: doc.is_released, case_sharing: doc.case_sharing }); } }
function(doc){ if((doc.doc_type == 'Application' || doc.doc_type == 'RemoteApp') && doc.copy_of != null) { emit([doc.domain, doc.copy_of, doc.version], { doc_type: doc.doc_type, short_url: doc.short_url, version: doc.version, _id: doc._id, name: doc.name, build_spec: doc.build_spec, copy_of: doc.copy_of, domain: doc.domain, built_on: doc.built_on, built_with: doc.built_with, build_comment: doc.build_comment, is_released: doc.is_released }); } }
FIX: Remove empty field, hangover from access keys module
<?php class FacebookMetadataSiteConfig extends DataExtension { static $db = array( 'SkipToMainContentAccessKey' => 'VarChar(1)' ); static $has_one = array( 'FacebookLogo' => 'Image' ); public function updateCMSFields(FieldList $fields) { $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square of minimum size 200px'))); } } ?>
<?php class FacebookMetadataSiteConfig extends DataExtension { static $db = array( 'SkipToMainContentAccessKey' => 'VarChar(1)' ); static $has_one = array( 'FacebookLogo' => 'Image' ); public function updateCMSFields(FieldList $fields) { $tf2 = new TextField('SkipToMainContentAccessKey'); $tf2->setMaxLength(1); $fields->addFieldToTab('Root.FacebookMetadata', $tf2); $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square'))); } } ?>
Change default compiler and default compilers list.
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0', 'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0', 'clang-10.0', 'clang-11.0', 'clang-11.1', 'clang-12.0', 'clang-13.0', 'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3', 'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8.2', 'gcc-8.3', 'gcc-8.4', 'gcc-8.5', 'gcc-9.1', 'gcc-9.2', 'gcc-9.3', 'gcc-9.4', 'gcc-10.1', 'gcc-10.2', 'gcc-10.3', 'gcc-11.1', 'gcc-11.2']; export default { allCompilers: ALL_COMPILERS, latestCompiler: 'clang-13.0' };
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0', 'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0', 'clang-10.0', 'clang-11.0', 'clang-12.0', 'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3', 'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8.2', 'gcc-8.3', 'gcc-8.4', 'gcc-9.1', 'gcc-9.2', 'gcc-9.3', 'gcc-10.1', 'gcc-10.2', 'gcc-10.3']; export default { allCompilers: ALL_COMPILERS, latestCompiler: 'clang-12.0' };
Refactor algorithm to perform better
'use strict' var visit = require('unist-util-visit') var toString = require('nlcst-to-string') var posjs = require('pos') module.exports = pos var tagger = new posjs.Tagger() function pos() { return transformer } function transformer(tree) { visit(tree, 'SentenceNode', visitor) // Patch all words in `parent`. function visitor(node) { var children = node.children var length = children.length var index = -1 var values = [] var words = [] var child var tags // Find words. while (++index < length) { child = children[index] if (child.type === 'WordNode') { values.push(toString(child)) words.push(child) } } // Apply tags if there are words. if (values.length !== 0) { tags = tagger.tag(values) length = tags.length index = -1 while (++index < length) { patch(words[index], tags[index][1]) } } // Don’t enter sentences. return visit.SKIP } // Patch a `partOfSpeech` property on `node`s. function patch(node, tag) { var data = node.data || (node.data = {}) data.partOfSpeech = tag } }
'use strict' var visit = require('unist-util-visit') var toString = require('nlcst-to-string') var posjs = require('pos') module.exports = pos var tagger = new posjs.Tagger() function pos() { return transformer } function transformer(tree) { var queue = [] visit(tree, 'WordNode', visitor) /* Gather a parent if not already gathered. */ function visitor(node, index, parent) { if (parent && queue.indexOf(parent) === -1) { queue.push(parent) one(parent) } } /* Patch all words in `parent`. */ function one(node) { var children = node.children var length = children.length var index = -1 var values = [] var words = [] var child var tags while (++index < length) { child = children[index] if (child.type === 'WordNode') { values.push(toString(child)) words.push(child) } } tags = tagger.tag(values) index = -1 length = tags.length while (++index < length) { patch(words[index], tags[index][1]) } } // Patch a `partOfSpeech` property on `node`s. function patch(node, tag) { var data = node.data || (node.data = {}) data.partOfSpeech = tag } }
Update docs and license for python
#!/usr/bin/env python # Very very very quick demo of how to recover the compressed payloads again. # TODO - at least take the same command line arguments as mosq-squasher # See LICENSE.txt import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
#!/usr/bin/env python import zlib import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test/out") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("Received compressed on: " + msg.topic) print(zlib.decompress(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
Update not found page to fix command request link. The new command label seems to have changed recently. This commit fixes the broken link.
//@flow /******************************************************************************* * Imports *******************************************************************************/ import React from 'react' import { Markdown, Cr } from 'tldr/components/Markdown' import Link from 'tldr/components/Link' import Tldr from 'tldr/components/Tldr' /******************************************************************************* * Public API *******************************************************************************/ export default () => ( <Markdown className="content"> # Oops! Command not found! {Cr} We looked and looked for it, but it's nowhere. Maybe you can help us find it? {Cr} <Tldr size="small"/> is a community effort, we need people like you to raise the bar and find missing commands, suggest editions, and propose new pages. {Cr} ### How can I help? {Cr} Take a look at the open <Link href="https://github.com/tldr-pages/tldr/issues?q=is%3Aissue+is%3Aopen+label%3A%22new+command%22" text="Command Requests" /> to throw a jab at things people need, or maybe join in on any of the open <Link href="https://github.com/tldr-pages/tldr/pulls" text="command proposals" />. {Cr} If the command you want hasn't been proposed yet, feel encouraged to submit a proposal yourself! 😉 &mdash; <Link href="https://github.com/tldr-pages/tldr/blob/master/CONTRIBUTING.md" text="Start here" /> {Cr} </Markdown> )
//@flow /******************************************************************************* * Imports *******************************************************************************/ import React from 'react' import { Markdown, Cr } from 'tldr/components/Markdown' import Link from 'tldr/components/Link' import Tldr from 'tldr/components/Tldr' /******************************************************************************* * Public API *******************************************************************************/ export default () => ( <Markdown className="content"> # Oops! Command not found! {Cr} We looked and looked for it, but it's nowhere. Maybe you can help us find it? {Cr} <Tldr size="small"/> is a community effort, we need people like you to raise the bar and find missing commands, suggest editions, and propose new pages. {Cr} ### How can I help? {Cr} Take a look at the open <Link href="https://github.com/tldr-pages/tldr/issues?q=is%3Aopen+is%3Aissue+label%3Acommand" text="Command Requests" /> to throw a jab at things people need, or maybe join in on any of the open <Link href="https://github.com/tldr-pages/tldr/pulls" text="command proposals" />. {Cr} If the command you want hasn't been proposed yet, feel encouraged to submit a proposal yourself! 😉 &mdash; <Link href="https://github.com/tldr-pages/tldr/blob/master/CONTRIBUTING.md" text="Start here" /> {Cr} </Markdown> )
Remove testing from gulp watch
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var util = require('gulp-util'); var wait = require('gulp-wait'); var runSequence = require('run-sequence'); var mocha = require('gulp-mocha'); var sourceFiles = [ 'app.js', './controllers/*.js', './helpers/*.js', './models/*.js', './tests/*.js' ]; var testFiles = ['tests/*.js', 'tests/**/*.js']; gulp.task('jshint', function() { gulp.src(sourceFiles) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function() { gulp.src(testFiles, { read: false }) // wait until all jshint logs are printed .pipe(wait(500)) .pipe(mocha({ reporter: 'spec'})) .on('error', util.log); }); gulp.task('default', function(callback) { runSequence('jshint', 'test', callback); }); gulp.task('watch', function() { gulp.watch(sourceFiles, ['jshint']); });
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var util = require('gulp-util'); var wait = require('gulp-wait'); var runSequence = require('run-sequence'); var mocha = require('gulp-mocha'); var sourceFiles = [ 'app.js', './controllers/*.js', './helpers/*.js', './models/*.js', './tests/*.js' ]; var testFiles = ['tests/*.js', 'tests/**/*.js']; gulp.task('jshint', function() { gulp.src(sourceFiles) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function() { gulp.src(testFiles, { read: false }) // wait until all jshint logs are printed .pipe(wait(500)) .pipe(mocha({ reporter: 'spec'})) .on('error', util.log); }); gulp.task('default', function(callback) { runSequence('jshint', 'test', callback); }); gulp.task('watch', function() { gulp.watch(sourceFiles, ['default']); });
fix: Add guard against empty stdin
// @flow /* eslint-disable no-console */ import _ from 'lodash' import stdin from 'get-stdin' import Promise from 'bluebird' import { parseOptions } from './cli' import { checkFiles, checkString } from './checks' import { formatOutput } from './formatters' import { hasError } from './utils' import { getDiffInformation } from './utils/git' import { setErrorToWarning } from './utils/checkstyle' import setup from './setup' function handleResult(result, options) { const output = options.warning ? _.map(result, setErrorToWarning) : result console.log(formatOutput(options.format, output)) process.exit(hasError(output) ? 1 : 0) } export default async function main(): Promise<> { const options = parseOptions() if (options.command === 'generate-config') { return setup(options) } const diff = await getDiffInformation(options) if (options.command === 'list-files') { return console.log(_.keys(diff).join(' ')) } if (!options.command) { let result if (_.isEmpty(options.files)) { const input = await stdin() if (input === '') { throw new Error('stdin was empty') } result = await checkString(diff, input, options) } else { result = await checkFiles(diff, options.files, options) } return handleResult(result, options) } throw new Error(`Unknown command '${options.command}'`) } if (!module.parent) { exports.default() }
// @flow /* eslint-disable no-console */ import _ from 'lodash' import stdin from 'get-stdin' import Promise from 'bluebird' import { parseOptions } from './cli' import { checkFiles, checkString } from './checks' import { formatOutput } from './formatters' import { hasError } from './utils' import { getDiffInformation } from './utils/git' import { setErrorToWarning } from './utils/checkstyle' import setup from './setup' function handleResult(result, options) { const output = options.warning ? _.map(result, setErrorToWarning) : result console.log(formatOutput(options.format, output)) process.exit(hasError(output) ? 1 : 0) } export default async function main(): Promise<> { const options = parseOptions() if (options.command === 'generate-config') { return setup(options) } const diff = await getDiffInformation(options) if (options.command === 'list-files') { return console.log(_.keys(diff).join(' ')) } if (!options.command) { let result if (_.isEmpty(options.files)) { const input = await stdin() result = await checkString(diff, input, options) } else { result = await checkFiles(diff, options.files, options) } return handleResult(result, options) } throw new Error(`Unknown command '${options.command}'`) } if (!module.parent) { exports.default() }
Remove text transformation on user account dropdown button
import {Dropdown} from 'reactjs-components'; import React from 'react'; class UserAccountDropdown extends React.Component { handleItemSelection(item) { if (item.onClick) { item.onClick(); } } render() { return ( <Dropdown buttonClassName="user-account-dropdown-button text-no-transform" dropdownMenuClassName="user-account-dropdown-menu dropdown-menu" dropdownMenuListClassName="user-account-dropdown-list dropdown-menu-list" items={this.props.menuItems} onItemSelection={this.handleItemSelection} persistentID="dropdown-trigger" transition={true} wrapperClassName="user-account-dropdown dropdown header flex-item-shrink-0" /> ); } }; module.exports = UserAccountDropdown;
import {Dropdown} from 'reactjs-components'; import React from 'react'; class UserAccountDropdown extends React.Component { handleItemSelection(item) { if (item.onClick) { item.onClick(); } } render() { return ( <Dropdown buttonClassName="user-account-dropdown-button" dropdownMenuClassName="user-account-dropdown-menu dropdown-menu" dropdownMenuListClassName="user-account-dropdown-list dropdown-menu-list" items={this.props.menuItems} onItemSelection={this.handleItemSelection} persistentID="dropdown-trigger" transition={true} wrapperClassName="user-account-dropdown dropdown header flex-item-shrink-0" /> ); } }; module.exports = UserAccountDropdown;
[display] Rewrite component and pass all props to the children.
//Dependencies. const builder = require('focus').component.builder; const React = require('react'); const type = require('focus').component.types; /** * Input text mixin. * @type {Object} */ const displayTextMixin = { /** @inheritdoc */ getDefaultProps(){ return { formatter: (data)=> data }; }, /** @inheritdoc */ propTypes: { type: type('string'), value: type(['string', 'number']), name: type('string'), style: type('object') }, /** * Render the value. * @return {string} The formated value. */ renderValue(){ const {formatter, value} = this.props; return formatter(value); }, /** @inheritdoc */ render: function renderInput() { return <div {...this.props}>{this.renderValue()}</div>; } }; module.exports = builder(displayTextMixin);
//Dependencies. var builder = require('focus').component.builder; var React = require('react'); var type = require('focus').component.types; /** * Input text mixin. * @type {Object} */ var displayTextMixin = { /** @inheritdoc */ getDefaultProps: function getInputDefaultProps() { return { value: undefined, name: undefined, formatter: function(data){return data;}, style: {} }; }, /** @inheritdoc */ propTypes: { type: type('string'), value: type(['string', 'number']), name: type('string'), style: type('object') }, renderValue: function renderValueDisplayText(){ return this.props.formatter(this.props.value); }, /** * Render a display field. * @return {DOM} - The dom of an input. */ render: function renderInput() { return ( <div id={this.props.name} name={this.props.name} className={this.props.style.class} >{this.renderValue()}</div> ); } }; module.exports = builder(displayTextMixin);
Fix missing filePath in Error and PluginError. file.contents = … somehow resets file.path on error so we have to store it. Also, React Error does not specify fileName, so add it if missing.
'use strict'; var path = require('path'); var gutil = require('gulp-util'); var through = require('through2'); var react = require('react-tools'); module.exports = function (options) { return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-react', 'Streaming not supported')); return cb(); } var str = file.contents.toString(); var filePath = file.path; if (path.extname(filePath) === '.jsx' && str.indexOf('/** @jsx') === -1) { str = '/** @jsx React.DOM */\n' + str; } try { file.contents = new Buffer(react.transform(str, options)); file.path = gutil.replaceExtension(filePath, '.js'); this.push(file); } catch (err) { err.fileName = err.fileName || filePath; this.emit('error', new gutil.PluginError('gulp-react', err, { fileName: filePath })); } cb(); }); };
'use strict'; var path = require('path'); var gutil = require('gulp-util'); var through = require('through2'); var react = require('react-tools'); module.exports = function (options) { return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-react', 'Streaming not supported')); return cb(); } var str = file.contents.toString(); if (path.extname(file.path) === '.jsx' && str.indexOf('/** @jsx') === -1) { str = '/** @jsx React.DOM */\n' + str; } try { file.contents = new Buffer(react.transform(str, options)); file.path = gutil.replaceExtension(file.path, '.js'); this.push(file); } catch (err) { this.emit('error', new gutil.PluginError('gulp-react', err, { fileName: file.path })); } cb(); }); };
Add test to verify storage check
import enhancer from '../src/enhancer' import createMockStorage from './utils/testStorage' describe('enhancer', () => { it('returns enhanced store with initial storage state', () => { const enhancedCreateStore = enhancer({ storage: createMockStorage() }) expect(enhancedCreateStore).toBeInstanceOf(Function) }) it('sets up store with initial storage state', () => { const mock = jest.fn() const dummyData = { authenticated: { authenticator: 'dummy', token: 'abcde' } } const storage = createMockStorage(dummyData) const createStore = jest.fn() const enhancedCreateStore = enhancer({ storage })(createStore)( mock, null, mock ) expect(createStore).toHaveBeenCalledWith( mock, { session: { authenticator: 'dummy', data: { token: 'abcde' }, isAuthenticated: false } }, mock ) }) it('throws when no storage given', () => { expect(() => enhancer({ storage: null })).toThrow( 'Expected `storage` to be a valid storage. You either forgot to ' + 'include it or you passed an invalid storage object' ) }) })
import enhancer from '../src/enhancer' import createMockStorage from './utils/testStorage' describe('enhancer', () => { it('returns enhanced store with initial storage state', () => { const enhancedCreateStore = enhancer() expect(enhancedCreateStore).toBeInstanceOf(Function) }) it('sets up store with initial storage state', () => { const mock = jest.fn() const dummyData = { authenticated: { authenticator: 'dummy', token: 'abcde' } } const storage = createMockStorage(dummyData) const createStore = jest.fn() const enhancedCreateStore = enhancer({ storage })(createStore)( mock, null, mock ) expect(createStore).toHaveBeenCalledWith( mock, { session: { authenticator: 'dummy', data: { token: 'abcde' }, isAuthenticated: false } }, mock ) }) })
Fix needed after rename of method
package org.opencode4workspace.it; import java.io.UnsupportedEncodingException; import java.util.List; import org.opencode4workspace.WWClient; import org.opencode4workspace.WWException; import org.opencode4workspace.endpoints.WWAuthenticationEndpoint; import org.opencode4workspace.endpoints.WWGraphQLEndpoint; import org.opencode4workspace.graphql.SpaceWrapper; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ITgraphQL { @Test(enabled=false) @Parameters({ "appId", "appSecret" }) public void testgetSpacesAsApp(String appId, String appSecret) throws UnsupportedEncodingException, WWException { WWClient client = WWClient.buildClientApplicationAccess(appId, appSecret, new WWAuthenticationEndpoint()); assert !client.isAuthenticated(); client.authenticate(); assert client.isAuthenticated(); WWGraphQLEndpoint ep = new WWGraphQLEndpoint(client); List<SpaceWrapper> spaces = ep.getSpaces(); assert (spaces.size() > 0); } }
package org.opencode4workspace.it; import java.io.UnsupportedEncodingException; import java.util.List; import org.opencode4workspace.WWClient; import org.opencode4workspace.WWException; import org.opencode4workspace.endpoints.WWAuthenticationEndpoint; import org.opencode4workspace.endpoints.WWGraphQLEndpoint; import org.opencode4workspace.graphql.SpaceWrapper; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ITgraphQL { @Test(enabled=false) @Parameters({ "appId", "appSecret" }) public void testgetSpacesAsApp(String appId, String appSecret) throws UnsupportedEncodingException, WWException { WWClient client = WWClient.buildClientApplicaitonAccess(appId, appSecret, new WWAuthenticationEndpoint()); assert !client.isAuthenticated(); client.authenticate(); assert client.isAuthenticated(); WWGraphQLEndpoint ep = new WWGraphQLEndpoint(client); List<SpaceWrapper> spaces = ep.getSpaces(); assert (spaces.size() > 0); } }
Fix potential panic in TimeoutAfter
package util import ( "fmt" "time" ) // TimeoutError is error returned after timeout occured. type TimeoutError struct { after time.Duration } // Error implements the Go error interface. func (t *TimeoutError) Error() string { return fmt.Sprintf("calling the function timeout after %v", t.after) } // TimeoutAfter executes the provide function and return the TimeoutError in // case when the execution time of the provided function is bigger than provided // time duration. func TimeoutAfter(t time.Duration, fn func() error) error { c := make(chan error, 1) go func() { defer close(c); c <- fn() }() select { case err := <-c: return err case <-time.After(t): return &TimeoutError{after: t} } } // IsTimeoutError checks if the provided error is timeout. func IsTimeoutError(e error) bool { _, ok := e.(*TimeoutError) return ok }
package util import ( "fmt" "time" ) // TimeoutError is error returned after timeout occured. type TimeoutError struct { after time.Duration } // Error implements the Go error interface. func (t *TimeoutError) Error() string { return fmt.Sprintf("calling the function timeout after %v", t.after) } // TimeoutAfter executes the provide function and return the TimeoutError in // case when the execution time of the provided function is bigger than provided // time duration. func TimeoutAfter(t time.Duration, fn func() error) error { c := make(chan error, 1) defer close(c) go func() { c <- fn() }() select { case err := <-c: return err case <-time.After(t): return &TimeoutError{after: t} } } // IsTimeoutError checks if the provided error is timeout. func IsTimeoutError(e error) bool { _, ok := e.(*TimeoutError) return ok }
Correct relative link to the categories
<aside id="blog-sidebar"> <section class="latest-posts"> <h3>Latest Posts</h3> <ul> <?php global $post; $args = array( 'numberposts' => 5 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <p class="meta"><?php echo the_time('jS F Y');?></p> </li> <?php endforeach; ?> </ul> </section> <section class="sidebar-categories"> <h3>Categories</h3> <ul class="sidebar-list"> <?php $categories = get_categories(); $base = get_bloginfo('url'); foreach ($categories as $category) { echo "<li><a href='{$base}/category/{$category->category_nicename}'>{$category->cat_name}</a></li>"; } ?> </ul> </section> <section class="sidebar-archive"> <h3>Archive</h3> <ul class="sidebar-list"> <?php wp_get_archives('type=yearly'); ?> </ul> </section> </aside>
<aside id="blog-sidebar"> <section class="latest-posts"> <h3>Latest Posts</h3> <ul> <?php global $post; $args = array( 'numberposts' => 5 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <p class="meta"><?php echo the_time('jS F Y');?></p> </li> <?php endforeach; ?> </ul> </section> <section class="sidebar-categories"> <h3>Categories</h3> <ul class="sidebar-list"> <?php $categories = get_categories(); foreach ($categories as $category) { echo "<li><a href='/category/{$category->category_nicename}'>{$category->cat_name}</a></li>"; } ?> </ul> </section> <section class="sidebar-archive"> <h3>Archive</h3> <ul class="sidebar-list"> <?php wp_get_archives('type=yearly'); ?> </ul> </section> </aside>
Add `pathfinder` to the library namespace
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
Allow task third parameter to be optional
'use strict'; var nomnom = require('nomnom'); var signal = require('./lib/signal'); var tree = require('./lib/tree'); var task = function (name, callback, options) { options = options || []; var command = nomnom.command(name); options.forEach(function (option) { command = command.option(option.name, { abbr: option.abbr, flag: option.flag, default: option.default }); }); command.callback(function (opts) { var args = options.map(function (option) { return opts[option.name]; }); callback.apply(null, args); }); }; var combine = function (/* ...signals */) { var args = Array.prototype.slice.call(arguments); var combinator = tree.merge; args.unshift(combinator); return signal.combine.apply(null, args); }; module.exports = { task: task, combine: combine, files: require('./base/files'), write: require('./base/write'), noop: require('./base/noop') };
'use strict'; var nomnom = require('nomnom'); var signal = require('./lib/signal'); var tree = require('./lib/tree'); var task = function (name, callback, options) { var command = nomnom.command(name); options.forEach(function (option) { command = command.option(option.name, { abbr: option.abbr, flag: option.flag, default: option.default }); }); command.callback(function (opts) { var args = options.map(function (option) { return opts[option.name]; }); callback.apply(null, args); }); }; var combine = function (/* ...signals */) { var args = Array.prototype.slice.call(arguments); var combinator = tree.merge; args.unshift(combinator); return signal.combine.apply(null, args); }; module.exports = { task: task, combine: combine, files: require('./base/files'), write: require('./base/write'), noop: require('./base/noop') };
Remove assignment of non-existing member.
<?php declare(strict_types = 1); namespace Apha\Saga; use Apha\Domain\Identity; use Apha\EventHandling\EventHandler; use Apha\Message\Event; use Apha\Message\Events; use JMS\Serializer\Annotation as Serializer; abstract class Saga implements EventHandler { /** * @Serializer\Type("Apha\Domain\Identity") * @var Identity */ private $identity; /** * @Serializer\Type("Apha\Saga\AssociationValues") * @var AssociationValues */ protected $associationValues; /** * @param Identity $identity * @param AssociationValues $associationValues */ public function __construct(Identity $identity, AssociationValues $associationValues) { $this->identity = $identity; $this->associationValues = $associationValues; } /** * @return Identity */ final public function getId(): Identity { return $this->identity; } /** * @return AssociationValues */ final public function getAssociationValues(): AssociationValues { return $this->associationValues; } /** * @param Event $event * @return void */ abstract public function on(Event $event); /** * @return bool */ abstract public function isActive(): bool; }
<?php declare(strict_types = 1); namespace Apha\Saga; use Apha\Domain\Identity; use Apha\EventHandling\EventHandler; use Apha\Message\Event; use Apha\Message\Events; use JMS\Serializer\Annotation as Serializer; abstract class Saga implements EventHandler { /** * @Serializer\Type("Apha\Domain\Identity") * @var Identity */ private $identity; /** * @Serializer\Type("Apha\Saga\AssociationValues") * @var AssociationValues */ protected $associationValues; /** * @param Identity $identity * @param AssociationValues $associationValues */ public function __construct(Identity $identity, AssociationValues $associationValues) { $this->identity = $identity; $this->associationValues = $associationValues; $this->changes = new Events(); } /** * @return Identity */ final public function getId(): Identity { return $this->identity; } /** * @return AssociationValues */ final public function getAssociationValues(): AssociationValues { return $this->associationValues; } /** * @param Event $event * @return void */ abstract public function on(Event $event); /** * @return bool */ abstract public function isActive(): bool; }
Add timeout for the request and catch more exceptions and print them if debug enabled in the conf
import urllib.request import os import re ## Get HTML for given url def getHtml( self, url, useragent): try: if useragent == True: user_agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)" headers = { 'User-Agent' : user_agent } req = urllib.request.Request(url, None, headers) else: req = urllib.request.Request(url, None) html = urllib.request.urlopen(req, timeout = 10).read() return(html) except Exception as e: if self.config["debug"] == "true": print(e) ## End ## Check if the city exists in Finland def checkCity ( city ): try: line = "" city = city.title() with open("modules/data/cities.txt", "r", encoding="UTF-8") as file: for l in file: line = l.strip() if city == line: return(True) except IOError as e: print(e) ## End def delHtml( html ): html = re.sub('<[^<]+?>', '', html) return(html)
import urllib.request import os ## Get HTML for given url def getHtml( self, url, useragent): try: if useragent == True: user_agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)" headers = { 'User-Agent' : user_agent } req = urllib.request.Request(url, None, headers) else: req = urllib.request.Request(url, None) html = urllib.request.urlopen(req).read() return(html) except urllib.error.HTTPError as msg: return(msg) except: if self.config["debug"] == "true": print("Fetching data faile for some reason") ## End ## Check if the city exists in Finland def checkCity ( self, city ): try: line = "" city = city.title() with open("modules/data/cities.txt", "r", encoding="UTF-8") as file: for l in file: line = l.strip() if city == line: return(True) except IOError as msg: print(msg) ## End
Switch to python3 specifically in gephi mock script. Can't change the docker image to make python==python3 right now because we need python2 on the image as it is used in the older branches that still support that version. CTR
#!/usr/bin/env python3 # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from http.server import BaseHTTPRequestHandler, HTTPServer class GephiHandler(BaseHTTPRequestHandler): def respond(self): self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write("{}") def do_GET(self): self.respond() def do_POST(self): self.respond() def main(): try: server = HTTPServer(('', 8080), GephiHandler) print('listening on port 8080...') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server') server.socket.close() if __name__ == '__main__': main()
#!/usr/bin/env python # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from http.server import BaseHTTPRequestHandler, HTTPServer class GephiHandler(BaseHTTPRequestHandler): def respond(self): self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write("{}") def do_GET(self): self.respond() def do_POST(self): self.respond() def main(): try: server = HTTPServer(('', 8080), GephiHandler) print('listening on port 8080...') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server') server.socket.close() if __name__ == '__main__': main()
Check for nulls (fix nullpointer on newer OSX?)
package oslib.osx; import java.io.Serializable; import oslib.Arch; import oslib.OperatingSystem; import oslib.UnixOperatingSystem; public class OSXOperatingSystem extends UnixOperatingSystem implements Serializable { private static final long serialVersionUID = 1929142018487788734L; private OSXVersion version; public OSXOperatingSystem() { this(OSXVersion.getFromString()); } public OSXOperatingSystem(OSXVersion version, Arch arch) { super(OperatingSystem.OSX, arch); this.version = version; } public OSXOperatingSystem(OSXVersion version) { this(version, Arch.getArch()); } public void setVersion(OSXVersion version) { this.version = version; } public OSXVersion getVersion() { return this.version; } @Override public String getDisplayString() { String s = "Mac OS X"; if (version.getDisplay() != null) { s += " " + version.getDisplay(); } if (version.getVersion() != null) { s += " " + version.getVersion(); } return s; } @Override public String getDetailedString() { return this.getDisplayString(); } }
package oslib.osx; import java.io.Serializable; import oslib.Arch; import oslib.OperatingSystem; import oslib.UnixOperatingSystem; public class OSXOperatingSystem extends UnixOperatingSystem implements Serializable { private static final long serialVersionUID = 1929142018487788734L; private OSXVersion version; public OSXOperatingSystem() { this(OSXVersion.getFromString()); } public OSXOperatingSystem(OSXVersion version, Arch arch) { super(OperatingSystem.OSX, arch); this.version = version; } public OSXOperatingSystem(OSXVersion version) { this(version, Arch.getArch()); } public void setVersion(OSXVersion version) { this.version = version; } public OSXVersion getVersion() { return this.version; } @Override public String getDisplayString() { return "Mac OS X " + version.getDisplay() + " " + version.getVersion(); } @Override public String getDetailedString() { return "Mac OS X " + version.getDisplay() + " " + version.getVersion(); } }
Make sure to set MySQL charset.
import aiomysql from .. import config from ..event import bus from .migration import MigrationManager host = config.create("storage", "host", fallback="localhost", comment="The database server host") port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port") user = config.create("storage", "user", fallback="plumeria", comment="The database server username") password = config.create("storage", "password", fallback="", comment="The database server password") db = config.create("storage", "db", fallback="plumeria", comment="The database name") class Pool: def __init__(self): self.pool = None def acquire(self): return self.pool.acquire() pool = Pool() migrations = MigrationManager(pool) @bus.event('preinit') async def preinit(): pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True, charset='utf8mb4') await migrations.setup()
import aiomysql from .. import config from ..event import bus from .migration import MigrationManager host = config.create("storage", "host", fallback="localhost", comment="The database server host") port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port") user = config.create("storage", "user", fallback="plumeria", comment="The database server username") password = config.create("storage", "password", fallback="", comment="The database server password") db = config.create("storage", "db", fallback="plumeria", comment="The database name") class Pool: def __init__(self): self.pool = None def acquire(self): return self.pool.acquire() pool = Pool() migrations = MigrationManager(pool) @bus.event('preinit') async def preinit(): pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True) await migrations.setup()
Make bluebird as default promise overriding ES6 promise
import mongoose from 'mongoose'; import util from 'util'; import config from './config/server/env'; import app from './config/server/express'; const debug = require('debug')('express-mongoose-es6-rest-api:index'); // make bluebird default Promise Promise = require('bluebird'); // eslint-disable-line no-global-assign // plugin bluebird promise in mongoose mongoose.Promise = Promise; // connect to mongo db mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } }); mongoose.connection.on('error', () => { throw new Error(`unable to connect to database: ${config.db}`); }); // print mongoose logs in dev env if (config.MONGOOSE_DEBUG) { mongoose.set('debug', (collectionName, method, query, doc) => { debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc); }); } // listen on port config.port app.listen(config.port, () => { debug(`server started on port ${config.port} (${config.env})`); }); export default app;
import Promise from 'bluebird'; import mongoose from 'mongoose'; import util from 'util'; import config from './config/server/env'; import app from './config/server/express'; const debug = require('debug')('express-mongoose-es6-rest-api:index'); // plugin bluebird promise in mongoose mongoose.Promise = Promise; // connect to mongo db mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } }); mongoose.connection.on('error', () => { throw new Error(`unable to connect to database: ${config.db}`); }); // print mongoose logs in dev env if (config.MONGOOSE_DEBUG) { mongoose.set('debug', (collectionName, method, query, doc) => { debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc); }); } // listen on port config.port app.listen(config.port, () => { debug(`server started on port ${config.port} (${config.env})`); }); export default app;
Fix typo in login_required decorator
from functools import update_wrapper from flask import session, redirect, flash import auth def login_required(permission=None): ''' Login required decorator. Requires user to be logged in. If a permission is provided, then user must also have the appropriate permissions to access the page. ''' def decorator(fn): def wrapped_function(*args, **kwargs): # User must be logged in. if 'username' not in session: flash("This page requires you to be logged in.") # Store page to be loaded after login in session. session['next'] = request.url return redirect(url_for('login')) # Check permissions. if permission != None: if not auth.check_permission(permission): flash("You do not have permission to access this page.") session['next'] = request.url return redirect(url_for('login')) return fn(*args, **kwargs) return update_wrapper(wrapped_function, fn) return decorator
from functools import update_wrapper from flask import session, redirect, flash import auth def login_required(permission=None): ''' Login required decorator. Requires user to be logged in. If a permission is provided, then user must also have the appropriate permissions to access the page. ''' def decorator(fn): def wrapped_function(*args, **kwargs): # User must be logged in. if 'username' not in session: flash("This page requires you to be logged in.") # Store page to be loaded after login in session. session['next'] = request.url return redirect(url_for('login')) # Check permissions. if permission != None: if not auth.check_permission(permission): flash("You do have have permission to access this page.") session['next'] = request.url return redirect(url_for('login')) return fn(*args, **kwargs) return update_wrapper(wrapped_function, fn) return decorator
Make sure container is not marked as ghost when it starts
package docker import ( "fmt" "github.com/dotcloud/docker/utils" "sync" "time" ) type State struct { sync.Mutex Running bool Pid int ExitCode int StartedAt time.Time Ghost bool } // String returns a human-readable description of the state func (s *State) String() string { if s.Running { if s.Ghost { return fmt.Sprintf("Ghost") } return fmt.Sprintf("Up %s", utils.HumanDuration(time.Now().Sub(s.StartedAt))) } return fmt.Sprintf("Exit %d", s.ExitCode) } func (s *State) setRunning(pid int) { s.Running = true s.Ghost = false s.ExitCode = 0 s.Pid = pid s.StartedAt = time.Now() } func (s *State) setStopped(exitCode int) { s.Running = false s.Pid = 0 s.ExitCode = exitCode }
package docker import ( "fmt" "github.com/dotcloud/docker/utils" "sync" "time" ) type State struct { sync.Mutex Running bool Pid int ExitCode int StartedAt time.Time Ghost bool } // String returns a human-readable description of the state func (s *State) String() string { if s.Running { if s.Ghost { return fmt.Sprintf("Ghost") } return fmt.Sprintf("Up %s", utils.HumanDuration(time.Now().Sub(s.StartedAt))) } return fmt.Sprintf("Exit %d", s.ExitCode) } func (s *State) setRunning(pid int) { s.Running = true s.ExitCode = 0 s.Pid = pid s.StartedAt = time.Now() } func (s *State) setStopped(exitCode int) { s.Running = false s.Pid = 0 s.ExitCode = exitCode }